<?php

namespace App\Http\Controllers;

use App\Models\Kurikulum;
use App\Models\Sekolah;
use App\Models\SesiKuis;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\SystemSetting;
use App\Models\Siswa;

class HomeController extends Controller
{
    public function dashboard()
    {
        $admin = Auth::user();

        // Ambil total siswa
        $totalSiswa = Siswa::count();
        $totalKurikulum = Kurikulum::count();
        $totalResponden = SesiKuis::count();
        $totalSekolah = Sekolah::count();

        // Tambah status quiz access
        $quizAccessStatus = SystemSetting::isPerhitunganOpen();

        return view('admin.dashboard', compact('admin', 'totalSiswa', 'totalKurikulum', 'totalResponden', 'totalSekolah', 'quizAccessStatus'));
    }

    // Tambah method untuk toggle quiz access
    public function toggleQuizAccess()
    {
        try {
            $newStatus = SystemSetting::togglePerhitunganOpen();
            
            if ($newStatus) {
                toastr()->success('Akses quiz berhasil dibuka untuk semua user');
            } else {
                toastr()->success('Akses quiz berhasil ditutup');
            }
            
            return response()->json([
                'success' => true,
                'status' => $newStatus,
                'message' => $newStatus 
                    ? 'Akses quiz berhasil dibuka untuk semua user'
                    : 'Akses quiz berhasil ditutup'
            ]);
        } catch (\Exception $e) {
            toastr()->error('Terjadi kesalahan: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ], 500);
        }
    }
}
