<?php

namespace App\Http\Controllers\Instansi;

use App\Http\Controllers\Controller;
use App\Models\Cuti;
use App\Models\JatahCuti;
use App\Models\Karyawan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CutiController extends Controller
{
    public function index(Request $request)
    {
        $instansiId = Auth::user()->instansi_id;

        $status     = $request->input('status', '');
        $karyawanId = $request->input('karyawan_id');

        $query = Cuti::with(['karyawan.user', 'karyawan.jabatan', 'approver'])
            ->whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))
            ->orderByRaw("FIELD(status, 'pending', 'disetujui', 'ditolak')")
            ->orderByDesc('created_at');

        if ($status !== '')  $query->where('status', $status);
        if ($karyawanId)     $query->where('karyawan_id', $karyawanId);

        $cutiList     = $query->paginate(15)->withQueryString();
        $karyawanList = Karyawan::with('user')->where('instansi_id', $instansiId)->get();

        $statPending   = Cuti::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))->where('status', 'pending')->count();
        $statDisetujui = Cuti::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))->where('status', 'disetujui')->count();
        $statDitolak   = Cuti::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))->where('status', 'ditolak')->count();

        return view('instansi.cuti.index', compact(
            'cutiList', 'karyawanList', 'status', 'karyawanId',
            'statPending', 'statDisetujui', 'statDitolak'
        ));
    }

    public function approve(Request $request, $id)
    {
        $instansiId = Auth::user()->instansi_id;
        $cuti = Cuti::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))
                    ->findOrFail($id);

        $cuti->update([
            'status'         => 'disetujui',
            'disetujui_oleh' => Auth::id(),
            'catatan_admin'  => $request->input('catatan'),
        ]);

        // Kurangi jatah cuti tahunan
        if ($cuti->jenis === 'tahunan') {
            $tahun = $cuti->tanggal_mulai->year;
            $jatah = JatahCuti::getOrCreate($cuti->karyawan_id, $tahun);
            $jatah->increment('terpakai_hari', $cuti->durasi_hari);
        }

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'message' => 'Cuti disetujui.']);
        }
        return back()->with('success', 'Pengajuan cuti disetujui.');
    }

    public function reject(Request $request, $id)
    {
        $instansiId = Auth::user()->instansi_id;
        $cuti = Cuti::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))
                    ->findOrFail($id);

        $cuti->update([
            'status'         => 'ditolak',
            'disetujui_oleh' => Auth::id(),
            'catatan_admin'  => $request->input('catatan'),
        ]);

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'message' => 'Cuti ditolak.']);
        }
        return back()->with('success', 'Pengajuan cuti ditolak.');
    }

    public function setJatah(Request $request, $karyawanId)
    {
        $request->validate(['jatah_hari' => 'required|integer|min:1|max:90']);

        $instansiId = Auth::user()->instansi_id;
        $karyawan   = Karyawan::where('instansi_id', $instansiId)->findOrFail($karyawanId);

        $jatah = JatahCuti::getOrCreate($karyawan->id);
        $jatah->update(['jatah_hari' => $request->jatah_hari]);

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'message' => 'Jatah cuti diperbarui.']);
        }
        return back()->with('success', 'Jatah cuti berhasil diperbarui.');
    }
}