<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Attendance, Holiday};
use Carbon\Carbon;
use RealRashid\SweetAlert\Facades\Alert;

class SiswaController extends Controller
{
    public function dashboard()
    {
        $user = auth()->user();
        $today = today();
        $thisMonth = Carbon::now()->startOfMonth();
        
        // Kehadiran hari ini
        $todayAttendance = $user->attendance()->whereDate('date', $today)->first();
        
        // Statistik bulanan kehadiran
        $monthlyStats = [
            'hadir' => $user->attendance()->where('status', 'hadir')->where('date', '>=', $thisMonth)->count(),
            'izin' => $user->attendance()->where('status', 'izin')->where('date', '>=', $thisMonth)->count(),
            'alfa' => $user->attendance()->where('status', 'alfa')->where('date', '>=', $thisMonth)->count()
        ];
        
        // Statistik jurnal
        $jurnalStats = [
            'total' => $user->jurnal()->count(),
            'pending' => $user->jurnal()->where('status_verifikasi', 'pending')->count(),
            'diterima' => $user->jurnal()->where('status_verifikasi', 'diterima')->count(),
            'ditolak' => $user->jurnal()->where('status_verifikasi', 'ditolak')->count()
        ];
        
        // Jurnal hari ini
        $todayJurnal = $user->jurnal()->whereDate('tanggal', $today)->first();
        
        return view('siswa.dashboard', compact('todayAttendance', 'monthlyStats', 'jurnalStats', 'todayJurnal'));
    }

    public function presensiHarian()
    {
        $user = auth()->user();
        $todayAttendance = $user->attendance()->whereDate('date', today())->first();
        return view('siswa.presensi-harian', compact('todayAttendance'));
    }

    public function riwayatKehadiran(Request $request)
    {
        $user = auth()->user();
        $query = $user->attendance();
        
        if ($request->start_date) $query->whereDate('date', '>=', $request->start_date);
        if ($request->end_date) $query->whereDate('date', '<=', $request->end_date);
        if ($request->status) $query->where('status', $request->status);
        
        return view('siswa.riwayat-kehadiran', [
            'attendance' => $query->orderBy('date', 'desc')->paginate(10)
        ]);
    }

    public function presensi(Request $request)
    {
        $user = auth()->user();
        $today = today();
        $now = Carbon::now('Asia/Jakarta');

        // Check for holiday
        if (Holiday::isHoliday($today)) {
            Alert::error('Error!', 'Hari ini adalah hari libur, presensi tidak dapat dilakukan');
            return back();
        }
        
        $attendance = Attendance::firstOrCreate(
            ['user_id' => $user->id, 'date' => $today],
            ['status' => 'hadir']
        );

        switch ($request->type) {
            case 'masuk':
                return $this->handleCheckIn($attendance, $now);
            
            case 'pulang':
                return $this->handleCheckOut($attendance, $now);
                
            case 'izin':
                return $this->handleIzin($attendance, $request);
        }

        return back();
    }

    private function handleCheckIn($attendance, $now)
    {
        if ($attendance->check_in_time) {
            Alert::error('Error!', 'Anda sudah melakukan presensi masuk hari ini');
            return back();
        }
        
        $attendance->update([
            'status' => 'hadir', 
            'check_in_time' => $now
        ]);
        
        Alert::success('Berhasil!', 'Presensi masuk berhasil dicatat pada ' . $now->format('H:i:s'));
        return back();
    }

    private function handleCheckOut($attendance, $now)
    {
        if (!$attendance->check_in_time) {
            Alert::error('Error!', 'Anda belum melakukan presensi masuk hari ini');
            return back();
        }
        
        if ($attendance->check_out_time) {
            Alert::error('Error!', 'Anda sudah melakukan presensi pulang hari ini');
            return back();
        }
        
        $minimumCheckoutTime = Carbon::today('Asia/Jakarta')->setHour(16)->setMinute(0);
        if ($now->lt($minimumCheckoutTime)) {
            Alert::error('Error!', 'Presensi pulang hanya bisa dilakukan mulai jam 16:00');
            return back();
        }
        
        $attendance->update(['check_out_time' => $now]);
        Alert::success('Berhasil!', 'Presensi pulang berhasil dicatat pada ' . $now->format('H:i:s'));
        return back();
    }

    private function handleIzin($attendance, $request)
    {
        if ($attendance->check_in_time || $attendance->status !== 'hadir') {
            Alert::error('Error!', 'Presensi hari ini sudah tercatat');
            return back();
        }
        
        $request->validate(['alasan_izin' => 'required|string|max:255']);
        
        $attendance->update([
            'status' => 'izin', 
            'notes' => $request->alasan_izin
        ]);
        
        Alert::success('Berhasil!', 'Izin berhasil dicatat');
        return back();
    }
}
