<?php

namespace App\Http\Controllers\Checker;

use App\Http\Controllers\Controller;
use App\Models\Iklan;
use App\Models\Pengesahan;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'role:checker']);
    }

    public function index()
    {
        $checker = Auth::user();
        $tahun = (int) date('Y');

        $stats = [
            'jumlah'      => Pengesahan::where('checker_id', $checker->id)->where('tahun', $tahun)->count(),
            'belum_semak' => Pengesahan::where('checker_id', $checker->id)->where('tahun', $tahun)->where('status', 'belum_semak')->count(),
            'lulus'        => Pengesahan::where('checker_id', $checker->id)->where('tahun', $tahun)->where('status', 'lulus')->count(),
            'ditolak'      => Pengesahan::where('checker_id', $checker->id)->where('tahun', $tahun)->where('status', 'ditolak')->count(),
        ];

        $terkini = Pengesahan::with('user')
            ->where('checker_id', $checker->id)
            ->where('tahun', $tahun)
            ->where('status', 'belum_semak')
            ->latest('dihantar_pada')
            ->take(5)
            ->get();

        $iklanList = Iklan::where('is_aktif', true)
            ->where(function ($q) {
                $q->whereJsonContains('target_role', 'checker')
                  ->orWhereJsonContains('target_role', 'semua');
            })
            ->where('tarikh_mula', '<=', now())
            ->where(function ($q) {
                $q->whereNull('tarikh_tamat')
                  ->orWhere('tarikh_tamat', '>=', now());
            })
            ->latest()
            ->get();

        return view('checker.dashboard', compact('stats', 'tahun', 'terkini', 'iklanList'));
    }
}
