<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\AcademicRecord;
use App\Models\CustomField;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class RecordController extends Controller {
    public function index() {
        $records = AcademicRecord::orderBy('last_names')->paginate(15);
        return view('admin.index', compact('records'));
    }

    public function create() {
        $customFields = CustomField::where('is_active', true)->get();
        return view('admin.create', compact('customFields'));
    }

    public function store(Request $request) {
        $data = $request->validate([
            'first_names' => 'required|string|max:255',
            'last_names' => 'required|string|max:255',
            'dni' => 'required|string|unique:academic_records,dni',
            'cohort' => 'required|string',
            'specialty' => 'required|string',
            'birth_date' => 'required|date',
            'registration_date' => 'required|date',
            'book' => 'required|string',
            'folio' => 'required|string',
            'location' => 'required|string'
        ]);
        if ($request->has('custom')) { $data['custom_values'] = $request->input('custom'); }
        AcademicRecord::create($data);
        return redirect()->route('admin.records.index')->with('success', 'Ficha académica creada correctamente.');
    }

    public function edit(AcademicRecord $record) {
        $customFields = CustomField::where('is_active', true)->get();
        return view('admin.edit', compact('record', 'customFields'));
    }

    public function update(Request $request, AcademicRecord $record) {
        $data = $request->validate([
            'first_names' => 'required|string|max:255',
            'last_names' => 'required|string|max:255',
            'dni' => 'required|string|unique:academic_records,dni,' . $record->id,
            'cohort' => 'required|string',
            'specialty' => 'required|string',
            'birth_date' => 'required|date',
            'registration_date' => 'required|date',
            'book' => 'required|string',
            'folio' => 'required|string',
            'location' => 'required|string'
        ]);
        $data['custom_values'] = $request->input('custom', null);
        $record->update($data);
        return redirect()->route('admin.records.index')->with('success', 'Ficha académica actualizada.');
    }

    public function destroy(AcademicRecord $record) {
        $record->delete();
        return redirect()->route('admin.records.index')->with('success', 'Registro eliminado.');
    }

    // ==========================================
    // LÓGICA DE IMPORTACIÓN MASIVA (CSV)
    // ==========================================
    public function import(Request $request) {
        $request->validate(['file' => 'required|mimes:csv,txt']);
        $file = $request->file('file');
        $handle = fopen($file->getRealPath(), 'r');
        $header = fgetcsv($handle, 1000, ','); // Leer cabecera

        $count = 0;
        $errors = 0;

        // Obtener nombres de campos personalizados para mapeo automático
        $customFieldLabels = CustomField::pluck('label')->toArray();

        while (($row = fgetcsv($handle, 1000, ',')) !== FALSE) {
            $data = array_combine($header, $row);

            // Validar si la cédula ya existe para saltar duplicados
            if (AcademicRecord::where('dni', $data['dni'])->exists()) {
                $errors++;
                continue;
            }

            // Datos base
            $recordData = [
                'first_names'       => $data['first_names'],
                'last_names'        => $data['last_names'],
                'dni'               => $data['dni'],
                'cohort'            => $data['cohort'],
                'specialty'         => $data['specialty'],
                'birth_date'        => $data['birth_date'],
                'registration_date' => $data['registration_date'],
                'book'              => $data['book'],
                'folio'             => $data['folio'],
                'location'          => $data['location'],
            ];

            // Mapear campos dinámicos si las columnas coinciden
            $customValues = [];
            foreach ($customFieldLabels as $label) {
                if (isset($data[$label])) {
                    $customValues[$label] = $data[$label];
                }
            }
            if (!empty($customValues)) {
                $recordData['custom_values'] = $customValues;
            }

            AcademicRecord::create($recordData);
            $count++;
        }
        fclose($handle);

        return back()->with('success', "Se importaron $count registros correctamente. Se saltaron $errors registros duplicados.");
    }

    // ==========================================
    // LÓGICA DE EXPORTACIÓN (EXCEL / CSV)
    // ==========================================
    public function exportAll() {
        $records = AcademicRecord::all();
        return $this->generateCsvResponse($records, 'listado_fichas_completo');
    }

    public function exportSingle(AcademicRecord $record) {
        return $this->generateCsvResponse(collect([$record]), "ficha_{$record->dni}");
    }

    private function generateCsvResponse($records, $filename) {
        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Disposition' => "attachment; filename={$filename}.csv",
        ];

        $callback = function() use ($records) {
            $file = fopen('php://output', 'w');

            // Bom para Excel (Soporte caracteres especiales como tildes)
            fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));

            // Definir cabeceras
            $columns = ['dni', 'first_names', 'last_names', 'cohort', 'specialty', 'birth_date', 'registration_date', 'book', 'folio', 'location'];

            // Agregar cabeceras de campos personalizados dinámicamente
            $customFieldLabels = CustomField::pluck('label')->toArray();
            $allColumns = array_merge($columns, $customFieldLabels);

            fputcsv($file, $allColumns);

            foreach ($records as $record) {
                $row = [
                    $record->dni, $record->first_names, $record->last_names, $record->cohort,
                    $record->specialty, $record->birth_date->format('Y-m-d'),
                    $record->registration_date->format('Y-m-d'), $record->book, $record->folio, $record->location
                ];

                // Llenar valores dinámicos
                foreach ($customFieldLabels as $label) {
                    $row[] = $record->custom_values[$label] ?? '';
                }

                fputcsv($file, $row);
            }
            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }
}
