<?php

namespace App\Http\Controllers\Admin;

use App\Models\Applicant;
use App\Models\Vacancy;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AdminApplicantController extends Controller
{
    public function index(Request $request)
    {
        $query = Applicant::with('vacancy')->latest();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('full_name', 'like', "%{$search}%")
                  ->orWhere('nik', 'like', "%{$search}%");
            });
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('vacancy_id')) {
            $query->where('vacancy_id', $request->vacancy_id);
        }

        $applicants = $query->paginate(15)->withQueryString();
        $vacancies = Vacancy::all();

        return view('admin.applicants.index', compact('applicants', 'vacancies'));
    }

    public function show($id)
    {
        $applicant = Applicant::with('vacancy')->findOrFail($id);
        return view('admin.applicants.show', compact('applicant'));
    }

    public function edit($id)
    {
        $applicant = Applicant::findOrFail($id);
        return view('admin.applicants.edit', compact('applicant'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:TERKIRIM,PROSES,DITERIMA,DITOLAK',
        ]);

        $applicant = Applicant::findOrFail($id);
        $applicant->update(['status' => $request->status]);

        return redirect()->route('admin.applicants.index')
            ->with('success', "Status pelamar {$applicant->full_name} berhasil diubah menjadi {$request->status}.");
    }

    public function destroy($id)
    {
        $applicant = Applicant::findOrFail($id);
        $name = $applicant->full_name;
        $applicant->delete();

        return redirect()->route('admin.applicants.index')
            ->with('success', "Data pelamar {$name} berhasil dihapus.");
    }

    public function export()
    {
        $applicants = Applicant::with('vacancy')->latest()->get();

        $response = new StreamedResponse(function () use ($applicants) {
            $handle = fopen('php://output', 'w');
            // BOM for Excel UTF-8
            fprintf($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));

            // Header — sesuai 6 step form
            fputcsv($handle, [
                'No',
                // Step 1: Identitas
                'Jabatan Dilamar',
                'Nama Lengkap',
                'Jenis Kelamin',
                'Golongan Darah',
                'Tempat Lahir',
                'Tanggal Lahir',
                'Agama',
                'Tinggi Badan (cm)',
                'Berat Badan (kg)',
                'Alamat KTP',
                'Kota',
                'Kode Pos',
                'Email',
                'No HP',
                'No KK',
                'No KTP/NIK',
                'Alamat Tinggal Saat Ini',
                'Tempat Tinggal Milik',
                'Status Pernikahan',
                // Step 2: Keluarga
                'Keluarga (Hubungan)',
                'Keluarga (Nama)',
                'Keluarga (L/P)',
                'Keluarga (Tempat/Tgl Lahir)',
                'Keluarga (Pendidikan)',
                'Keluarga (Pekerjaan)',
                'Keluarga (No Telepon)',
                // Step 3: Pendidikan
                'Pendidikan (Tingkat)',
                'Pendidikan (Sekolah)',
                'Pendidikan (Jurusan)',
                'Pendidikan (Tempat)',
                'Pendidikan (Tahun)',
                'Pendidikan (Lulus)',
                'Pendidikan (IPK)',
                // Step 4: Pekerjaan
                'Pekerjaan (Perusahaan)',
                'Pekerjaan (Jabatan)',
                'Pekerjaan (Periode)',
                'Pekerjaan (Gaji Akhir)',
                'Pekerjaan (Alasan Berhenti)',
                'Pekerjaan (Uraian Tugas)',
                // Step 5: Lain-lain
                'Organisasi',
                'Hobby',
                'Referensi',
                'Kontak Darurat',
                // Step 6: Dokumen
                'Dokumen',
                // Meta
                'Status',
                'Lowongan',
                'Tanggal Melamar',
            ]);

            foreach ($applicants as $i => $a) {
                $other = is_array($a->other_data) ? $a->other_data : [];
                $family = is_array($a->family_data) ? $a->family_data : [];
                $edu = is_array($a->education_data) ? $a->education_data : [];
                $exp = is_array($a->experience_data) ? $a->experience_data : [];
                $docs = is_array($a->documents) ? $a->documents : [];

                // Flatten family
                $famRelation = collect($family)->pluck('relationship')->filter()->implode(' | ');
                $famName = collect($family)->pluck('name')->filter()->implode(' | ');
                $famGender = collect($family)->pluck('gender')->filter()->implode(' | ');
                $famBirth = collect($family)->map(fn($f) => $f['birth_place_date'] ?? ($f['age'] ?? ''))->filter()->implode(' | ');
                $famEdu = collect($family)->pluck('education')->filter()->implode(' | ');
                $famJob = collect($family)->pluck('occupation')->filter()->implode(' | ');
                $famPhone = collect($family)->pluck('phone')->filter()->implode(' | ');

                // Flatten education
                $eduLevel = collect($edu)->map(fn($e) => $e['level'] ?? $e['degree'] ?? '')->filter()->implode(' | ');
                $eduSchool = collect($edu)->pluck('institution')->filter()->implode(' | ');
                $eduMajor = collect($edu)->pluck('major')->filter()->implode(' | ');
                $eduLoc = collect($edu)->pluck('location')->filter()->implode(' | ');
                $eduYear = collect($edu)->map(fn($e) => ($e['year_start'] ?? '') . '-' . ($e['year_end'] ?? $e['year'] ?? ''))->filter()->implode(' | ');
                $eduGrad = collect($edu)->pluck('graduated')->filter()->implode(' | ');
                $eduGpa = collect($edu)->pluck('gpa')->filter()->implode(' | ');

                // Flatten experience
                $expCompany = collect($exp)->pluck('company')->filter()->implode(' | ');
                $expPosition = collect($exp)->map(fn($e) => is_array($e['positions'] ?? null) ? implode(', ', array_filter($e['positions'])) : ($e['position'] ?? ''))->filter()->implode(' | ');
                $expPeriod = collect($exp)->map(fn($e) => is_array($e['periods'] ?? null) ? implode(', ', array_filter($e['periods'])) : ($e['duration'] ?? ''))->filter()->implode(' | ');
                $expSalary = collect($exp)->map(fn($e) => is_array($e['salaries'] ?? null) ? implode(', ', array_filter($e['salaries'])) : ($e['salary'] ?? ''))->filter()->implode(' | ');
                $expReason = collect($exp)->pluck('reason_leave')->filter()->implode(' | ');
                $expResp = collect($exp)->map(fn($e) => $e['responsibilities'] ?? $e['description'] ?? '')->filter()->implode(' | ');

                // Flatten other
                $orgList = collect($other['social_activities'] ?? [])->map(fn($s) => ($s['organization'] ?? '') . ' (' . ($s['position'] ?? '') . ')')->implode(' | ');
                $hobby = $other['hobbies'] ?? '';
                $refList = collect($other['references'] ?? [])->map(fn($r) => ($r['name'] ?? '') . ' - ' . ($r['relationship'] ?? ''))->implode(' | ');
                $emergList = collect($other['emergency_contacts'] ?? [])->map(fn($e) => ($e['name'] ?? '') . ' / ' . ($e['phone'] ?? '') . ' (' . ($e['relationship'] ?? '') . ')')->implode(' | ');

                $docList = collect($docs)->keys()->map(fn($k) => ucwords(str_replace('_', ' ', $k)))->implode(', ');

                fputcsv($handle, [
                    $i + 1,
                    $a->vacancy->title ?? '-',
                    $a->full_name,
                    $a->gender,
                    $other['blood_type'] ?? '-',
                    $a->birth_place,
                    $a->birth_date ? $a->birth_date->format('d/m/Y') : '-',
                    $a->religion,
                    $a->height,
                    $a->weight,
                    $a->address,
                    $a->city,
                    $a->postal_code,
                    $a->email,
                    $a->phone,
                    $other['no_kk'] ?? '-',
                    "'{$a->nik}",
                    $other['current_address'] ?? $a->address,
                    $other['residence_owner'] ?? '-',
                    $other['marital_status'] ?? '-',
                    $famRelation,
                    $famName,
                    $famGender,
                    $famBirth,
                    $famEdu,
                    $famJob,
                    $famPhone,
                    $eduLevel,
                    $eduSchool,
                    $eduMajor,
                    $eduLoc,
                    $eduYear,
                    $eduGrad,
                    $eduGpa,
                    $expCompany,
                    $expPosition,
                    $expPeriod,
                    $expSalary,
                    $expReason,
                    $expResp,
                    $orgList,
                    $hobby,
                    $refList,
                    $emergList,
                    $docList,
                    $a->status,
                    $a->vacancy->title ?? '-',
                    $a->created_at->format('d/m/Y H:i'),
                ]);
            }

            fclose($handle);
        });

        $response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="data-pelamar-' . date('Y-m-d') . '.csv"');

        return $response;
    }

    public function exportSingle(Applicant $applicant)
    {
        $filename = "Formulir_Pelamar_" . str_replace(' ', '_', $applicant->full_name) . ".xlsx";
        return \Maatwebsite\Excel\Facades\Excel::download(new \App\Exports\ApplicantExport($applicant), $filename);
    }
}