<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminCutiController extends Controller
{
    public function index(Request $request)
    {
        $q = $request->query('q');
        $items = DB::table('cuti')
            ->leftJoin('users', 'users.id', '=', 'cuti.user_id')
            ->when($q, function ($query) use ($q) {
                $query->where(function ($w) use ($q) {
                    $w->where('users.name', 'like', "%$q%")
                      ->orWhere('cuti.jenis', 'like', "%$q%")
                      ->orWhere('cuti.alasan', 'like', "%$q%")
                      ->orWhere('cuti.status', 'like', "%$q%");
                });
            })
            ->select('cuti.*', 'users.name as user_name', 'users.username')
            ->orderByDesc('cuti.created_at')
            ->paginate(15)
            ->appends($request->query());

        return view('admin.cuti.index', [
            'title' => 'Persetujuan Cuti',
            'items' => $items,
            'q' => $q,
        ]);
    }

    public function updateStatus(Request $request, int $id)
    {
        $validated = $request->validate([
            'action' => ['required', 'in:setujui,tolak'],
        ]);
        $status = $validated['action'] === 'setujui' ? 'disetujui' : 'ditolak';

        DB::table('cuti')->where('id', $id)->update([
            'status' => $status,
            'updated_at' => now(),
        ]);

        return back()->with('success', "Pengajuan cuti #$id telah $status.");
    }
}
