<?php

use App\Contracts\AuthServiceInterface;
use App\Http\Middleware\EnsurePasswordIsChanged;
use App\Livewire\Auth\ForceChangePassword;
use App\Livewire\Auth\Login;
use App\Livewire\Dashboard;
use App\Livewire\Users\UserIndex;
use Illuminate\Support\Facades\Route;

// Redirect Root URL
Route::get('/', function () {
    return auth()->check() ? redirect()->route('dashboard') : redirect()->route('login');
});

// Guest Routes
Route::middleware('guest')->group(function () {
    Route::get('/login', Login::class)->name('login');
});

// Public Read-Only Parent Portal (No Auth Required)
Route::get('/parent/view/{token}', \App\Livewire\Parent\ParentPortalShow::class)->name('parent.portal');

// ADMS Direct Server Push Protocol Routes (ZKTeco / Fingerspot Revo W-230N)
Route::any('/iclock/cdata', [\App\Http\Controllers\Api\AdmsController::class, 'handleCdata'])->name('adms.cdata');
Route::any('/iclock/cdata.php', [\App\Http\Controllers\Api\AdmsController::class, 'handleCdata']);
Route::any('/iclock/getrequest', [\App\Http\Controllers\Api\AdmsController::class, 'handleGetRequest'])->name('adms.getrequest');
Route::any('/iclock/getrequest.php', [\App\Http\Controllers\Api\AdmsController::class, 'handleGetRequest']);
Route::any('/iclock/devicecmd', [\App\Http\Controllers\Api\AdmsController::class, 'handleDeviceCmd'])->name('adms.devicecmd');

// Authenticated Routes
Route::middleware('auth')->group(function () {
    
    
    // Force Change Password Route
    Route::get('/force-change-password', ForceChangePassword::class)->name('force-change-password');

    // Logout Route
    Route::post('/logout', function (AuthServiceInterface $authService) {
        $authService->logout();
        return redirect()->route('login')->with('success', 'Anda telah berhasil keluar dari sistem.');
    })->name('logout');

    // Protected Routes (Harus melewati EnsurePasswordIsChanged)
    Route::middleware(EnsurePasswordIsChanged::class)->group(function () {
        Route::get('/dashboard', Dashboard::class)->name('dashboard');
        Route::get('/users', UserIndex::class)->name('users.index');
        Route::get('/shifts', \App\Livewire\Shifts\ShiftIndex::class)->name('shifts.index');
        Route::get('/personnel', \App\Livewire\Personnel\PersonnelIndex::class)->name('personnel.index');
        Route::get('/personnel/id-cards', \App\Livewire\Personnel\StudentIdCardIndex::class)->name('personnel.id-cards');
        Route::get('/personnel/id-cards/print', function (\Illuminate\Http\Request $request) {
            \Illuminate\Support\Facades\Gate::authorize('viewAny', \App\Models\User::class);

            $className = $request->get('class');
            $students = \App\Models\User::whereNotNull('class_name')
                ->when(!empty($className), fn($q) => $q->where('class_name', $className))
                ->orderBy('name', 'asc')
                ->get();
            $schoolSettings = \App\Models\SchoolSetting::getAllCached();
            return view('reports.print-id-cards', [
                'students' => $students,
                'school' => $schoolSettings,
                'logoUrl' => \App\Models\SchoolSetting::getFileUrl('school_logo'),
            ]);
        })->name('personnel.id-cards.print');
        Route::get('/personnel/{id}', \App\Livewire\Personnel\PersonnelShow::class)->name('personnel.show');
        Route::get('/machines', \App\Livewire\Machines\MachineIndex::class)->name('machines.index');

        Route::get('/reports', \App\Livewire\Reports\ReportIndex::class)->name('reports.index');
        Route::get('/reports/class-recap', \App\Livewire\Reports\ClassRecapIndex::class)->name('reports.class-recap');
        Route::get('/reports/warning-letters', \App\Livewire\Reports\WarningLetterIndex::class)->name('reports.warning-letters');
        Route::get('/reports/warning-letters/pdf/{id}', function (int $id, \App\Services\WarningLetterService $service) {
            $letter = \App\Models\WarningLetter::findOrFail($id);
            \Illuminate\Support\Facades\Gate::authorize('view', $letter);

            $data = $service->getPdfData($letter);
            return view('reports.print-warning-letter-pdf', $data);
        })->name('reports.warning-letter-pdf');
        Route::get('/roles-permissions', \App\Livewire\Permissions\RolePermissionIndex::class)->name('roles-permissions.index');
        Route::get('/academic-calendar', \App\Livewire\Academic\AcademicCalendarIndex::class)->name('academic-calendar.index');
        Route::get('/leave-applications', \App\Livewire\Leave\LeaveApplicationIndex::class)->name('leave-applications.index');
        Route::get('/system-monitoring', \App\Livewire\Monitoring\SystemMonitoringIndex::class)->name('system-monitoring.index');
        Route::get('/backup-restore', \App\Livewire\Backup\BackupRestoreIndex::class)->name('backup-restore.index');
        Route::get('/whatsapp-gateway', \App\Livewire\WhatsApp\WhatsAppGatewayIndex::class)->name('whatsapp-gateway.index');
        Route::get('/school-settings', \App\Livewire\Settings\SchoolSettingIndex::class)->name('school-settings.index');
        Route::get('/help/guide', \App\Livewire\Help\UserGuideIndex::class)->name('help.guide');
        Route::get('/reports/print-pdf', function (\Illuminate\Http\Request $request, \App\Services\ReportService $reportService) {
            \Illuminate\Support\Facades\Gate::authorize('viewAny', \App\Models\AttendanceRecord::class);

            $startDate = $request->get('start_date', now()->startOfMonth()->toDateString());
            $endDate = $request->get('end_date', now()->toDateString());
            $roleId = $request->get('role_id') ? (int)$request->get('role_id') : null;
            $status = $request->get('status');

            // Membatasi query untuk mencegah crash browser saat render HTML
            $records = $reportService->getFilteredReport(null, $startDate, $endDate, $roleId, $status, '', 2000);
            
            $isTruncated = $records->total() > 2000;

            return view('reports.print-pdf', [
                'records' => $records,
                'startDate' => $startDate,
                'endDate' => $endDate,
                'isTruncated' => $isTruncated,
            ]);
        })->name('reports.print-pdf');
    });
});
