<?php

namespace App\Http\Controllers;

use App\Models\Personil;
use App\Support\Dropdown;
use Illuminate\Http\Request;

class PersonilController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');
        $statusSkk = $request->input('status_skk');

        $personilsQuery = Personil::withCount('lelangPersonils');

        if ($search) {
            $personilsQuery->where(function ($q) use ($search) {
                $q->where('nama_personil', 'like', "%$search%")
                  ->orWhere('id_personil', 'like', "%$search%");
            });
        }

        // Filter status_skk using date calculations
        if ($statusSkk) {
            $today = now()->startOfDay();
            switch ($statusSkk) {
                case 'AKTIF':
                    $personilsQuery->where(function ($q) use ($today) {
                        $q->whereNotNull('tanggal_ditetapkan')
                          ->whereNotNull('masa_berlaku_tahun')
                          ->whereRaw("DATE_ADD(tanggal_ditetapkan, INTERVAL masa_berlaku_tahun YEAR) > ?", [$today->copy()->addDays(180)]);
                    });
                    break;
                case 'WARNING H-180':
                    $personilsQuery->where(function ($q) use ($today) {
                        $q->whereNotNull('tanggal_ditetapkan')
                          ->whereNotNull('masa_berlaku_tahun')
                          ->whereRaw("DATE_ADD(tanggal_ditetapkan, INTERVAL masa_berlaku_tahun YEAR) BETWEEN ? AND ?", [
                              $today->copy()->addDays(91),
                              $today->copy()->addDays(180)
                          ]);
                    });
                    break;
                case 'SIAGA H-90':
                    $personilsQuery->where(function ($q) use ($today) {
                        $q->whereNotNull('tanggal_ditetapkan')
                          ->whereNotNull('masa_berlaku_tahun')
                          ->whereRaw("DATE_ADD(tanggal_ditetapkan, INTERVAL masa_berlaku_tahun YEAR) BETWEEN ? AND ?", [
                              $today->copy()->addDays(31),
                              $today->copy()->addDays(90)
                          ]);
                    });
                    break;
                case 'KRITIS H-30':
                    $personilsQuery->where(function ($q) use ($today) {
                        $q->whereNotNull('tanggal_ditetapkan')
                          ->whereNotNull('masa_berlaku_tahun')
                          ->whereRaw("DATE_ADD(tanggal_ditetapkan, INTERVAL masa_berlaku_tahun YEAR) BETWEEN ? AND ?", [
                              $today->copy(),
                              $today->copy()->addDays(30)
                          ]);
                    });
                    break;
                case 'EXPIRED':
                    $personilsQuery->where(function ($q) use ($today) {
                        $q->whereNotNull('tanggal_ditetapkan')
                          ->whereNotNull('masa_berlaku_tahun')
                          ->whereRaw("DATE_ADD(tanggal_ditetapkan, INTERVAL masa_berlaku_tahun YEAR) < ?", [$today]);
                    });
                    break;
                case 'Belum Input':
                    $personilsQuery->where(function ($q) {
                        $q->whereNull('tanggal_ditetapkan')
                          ->orWhereNull('masa_berlaku_tahun');
                    });
                    break;
            }
        }

        $personils = $personilsQuery->paginate(10)->withQueryString();

        return view('personils.index', compact('personils', 'search', 'statusSkk'));
    }

    public function create()
    {
        $statusVerifikasi = Dropdown::statusVerifikasi();
        return view('personils.create', compact('statusVerifikasi'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'id_personil' => 'required|unique:personils',
            'nama_personil' => 'required',
            'nik' => 'nullable',
            'email' => 'nullable|email',
            'no_hp' => 'nullable',
            'perusahaan_pemilik_data' => 'nullable',
            'posisi_usulan' => 'nullable',
            'klasifikasi' => 'nullable',
            'subklasifikasi' => 'nullable',
            'kualifikasi' => 'nullable',
            'jenjang' => 'nullable|integer',
            'okupasi' => 'nullable',
            'no_sertifikat' => 'nullable',
            'no_registrasi' => 'nullable',
            'no_blanko' => 'nullable',
            'lsp' => 'nullable',
            'tanggal_ditetapkan' => 'nullable|date',
            'masa_berlaku_tahun' => 'nullable|integer',
            'status_verifikasi' => 'nullable|in:' . implode(',', Dropdown::statusVerifikasi()),
            'link_folder_personil' => 'nullable|url',
            'link_file_skk' => 'nullable|url',
            'link_bukti_verifikasi' => 'nullable|url',
            'catatan' => 'nullable',
        ]);

        Personil::create($validated);

        return redirect()->route('personils.index')->with('success', 'Personil berhasil ditambahkan.');
    }

    public function show(Personil $personil)
    {
        $personil->load('personilChecklist', 'lelangPersonils.paketLelang');
        return view('personils.show', compact('personil'));
    }

    public function edit(Personil $personil)
    {
        $statusVerifikasi = Dropdown::statusVerifikasi();
        $statusBerkas = Dropdown::statusBerkas();
        return view('personils.edit', compact('personil', 'statusVerifikasi', 'statusBerkas'));
    }

    public function update(Request $request, Personil $personil)
    {
        $validated = $request->validate([
            'id_personil' => 'required|unique:personils,id_personil,' . $personil->id,
            'nama_personil' => 'required',
            'nik' => 'nullable',
            'email' => 'nullable|email',
            'no_hp' => 'nullable',
            'perusahaan_pemilik_data' => 'nullable',
            'posisi_usulan' => 'nullable',
            'klasifikasi' => 'nullable',
            'subklasifikasi' => 'nullable',
            'kualifikasi' => 'nullable',
            'jenjang' => 'nullable|integer',
            'okupasi' => 'nullable',
            'no_sertifikat' => 'nullable',
            'no_registrasi' => 'nullable',
            'no_blanko' => 'nullable',
            'lsp' => 'nullable',
            'tanggal_ditetapkan' => 'nullable|date',
            'masa_berlaku_tahun' => 'nullable|integer',
            'status_verifikasi' => 'nullable|in:' . implode(',', Dropdown::statusVerifikasi()),
            'link_folder_personil' => 'nullable|url',
            'link_file_skk' => 'nullable|url',
            'link_bukti_verifikasi' => 'nullable|url',
            'catatan' => 'nullable',
        ]);

        $personil->update($validated);

        return redirect()->route('personils.index')->with('success', 'Personil berhasil diperbarui.');
    }

    public function updateChecklist(Request $request, Personil $personil)
    {
        $validated = $request->validate([
            'ktp' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_ktp' => 'nullable|url',
            'npwp' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_npwp' => 'nullable|url',
            'ijazah' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_ijazah' => 'nullable|url',
            'cv_terbaru' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_cv' => 'nullable|url',
            'pas_foto' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_pas_foto' => 'nullable|url',
            'skk' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_skk' => 'nullable|url',
            'bukti_verifikasi_qr_siki' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_verifikasi' => 'nullable|url',
            'portofolio_pengalaman' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_pengalaman' => 'nullable|url',
            'referensi_kerja' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_referensi' => 'nullable|url',
            'surat_pernyataan' => 'nullable|in:' . implode(',', Dropdown::statusBerkas()),
            'link_surat' => 'nullable|url',
            'pic_update' => 'nullable',
            'tanggal_update' => 'nullable|date',
            'catatan' => 'nullable',
        ]);

        $personil->personilChecklist()->updateOrCreate(
            ['personil_id' => $personil->id],
            $validated
        );

        return redirect()->route('personils.edit', $personil)->with('success', 'Checklist berhasil diperbarui.');
    }

    public function destroy(Personil $personil)
    {
        $personil->delete();
        return redirect()->route('personils.index')->with('success', 'Personil berhasil dihapus.');
    }
}
