<?php

namespace App\Http\Controllers\Instansi;

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

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

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

        $query = IzinSakit::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);

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

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

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

    public function approve($id)
    {
        $instansiId = Auth::user()->instansi_id;

        $izin = IzinSakit::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))
            ->findOrFail($id);

        $izin->update([
            'status'         => 'disetujui',
            'disetujui_oleh' => Auth::id(),
        ]);

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

        return back()->with('success', 'Pengajuan izin disetujui.');
    }

    public function reject($id)
    {
        $instansiId = Auth::user()->instansi_id;

        $izin = IzinSakit::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))
            ->findOrFail($id);

        $izin->update([
            'status'         => 'ditolak',
            'disetujui_oleh' => Auth::id(),
        ]);

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

        return back()->with('success', 'Pengajuan izin ditolak.');
    }
}