<?php

namespace App\Http\Controllers;

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

class AutomationController extends Controller
{
    public function runAutoAlfa()
    {
        try {
            $alfaCount = $this->processAutoAlfa();
            
            if ($alfaCount === null) {
                Alert::error('Error!', 'Proses alfa otomatis sudah dijalankan hari ini atau hari libur');
                return back();
            }
            
            Alert::success('Berhasil!', "Proses alfa otomatis berhasil dijalankan. {$alfaCount} siswa ditandai alfa.");
            return back();
        } catch (\Exception $e) {
            Alert::error('Error!', 'Terjadi kesalahan: ' . $e->getMessage());
            return back();
        }
    }

    public function checkAndRunAutoAlfa()
    {
        $now = Carbon::now('Asia/Jakarta');
        $currentTime = $now->format('H:i');
        $today = $now->toDateString();
        
        if ($currentTime >= '10:00') {
            $logExists = AutomationLog::where('action', 'auto_alfa')
                                      ->whereDate('executed_at', $today)
                                      ->exists();
            
            if (!$logExists) {
                $this->processAutoAlfa();
            }
        }
    }

    private function processAutoAlfa()
    {
        $today = today();

        if ($today->isWeekend() || Holiday::isHoliday($today)) {
            return null;
        }

        $logExists = AutomationLog::where('action', 'auto_alfa')
                                  ->whereDate('executed_at', $today)
                                  ->exists();
        if ($logExists) {
            return null;
        }

        $siswaUsers = User::whereHas('role', fn($q) => $q->where('nama_role', 'siswa magang'))->get();
        $alfaCount = 0;

        foreach ($siswaUsers as $user) {
            $hasAttendance = Attendance::where('user_id', $user->id)
                                      ->whereDate('date', $today)
                                      ->exists();
            
            if (!$hasAttendance) {
                Attendance::create([
                    'user_id' => $user->id,
                    'date' => $today,
                    'status' => 'alfa',
                    'check_in_time' => null,
                    'check_out_time' => null,
                    'notes' => 'Dibuat otomatis pada ' . now()->format('H:i:s')
                ]);
                $alfaCount++;
            }
        }

        AutomationLog::create([
            'action' => 'auto_alfa',
            'executed_at' => now(),
            'details' => "Processed {$alfaCount} auto alfa records for {$today->format('Y-m-d')}. Total siswa checked: " . $siswaUsers->count()
        ]);

        return $alfaCount;
    }
}