<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\Certificate;
use App\Models\Participant;
use App\Models\Program;
use App\Models\QuestionnaireResponse;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        // Sijil dijana tapi belum dihantar emel (ada emel peserta)
        $emailsPending = DB::table('certificates')
            ->join('participants', 'participants.id', '=', 'certificates.participant_id')
            ->where('certificates.status', 'generated')
            ->whereNull('certificates.emailed_at')
            ->whereNotNull('participants.email')
            ->count();

        $stats = [
            'total_programs'       => Program::count(),
            'active_programs'      => Program::where('status', 'published')->count(),
            'total_participants'   => Participant::count(),
            'total_attendances'    => Attendance::count(),
            'total_certificates'   => Certificate::count(),
            'generated_certs'      => Certificate::whereIn('status', ['generated', 'emailed', 'downloaded'])->count(),
            'downloaded_certs'     => Certificate::where('status', 'downloaded')->count(),
            'total_download_count' => (int) Certificate::sum('download_count'),
            'total_responses'      => QuestionnaireResponse::count(),
            'emails_pending'       => $emailsPending,
            'emails_sent'          => Certificate::whereNotNull('emailed_at')->count(),
            'emails_failed'        => DB::table('program_participants')->where('status_sent_emel', 'failed')->count(),
        ];

        $recentPrograms = Program::with('creator')
            ->latest()
            ->limit(5)
            ->get();

        return view('admin.dashboard', compact('stats', 'recentPrograms'));
    }
}
