<?php

use App\Http\Controllers\Api\ActivityAssignmentController;
use App\Http\Controllers\Api\ActivityController;
use App\Http\Controllers\Api\AttendanceController;
use App\Http\Controllers\Api\AttendanceCorrectionController;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\BusinessTripController;
use App\Http\Controllers\Api\DeviceController;
use App\Http\Controllers\Api\DocumentController;
use App\Http\Controllers\Api\EarlyLeaveController;
use App\Http\Controllers\Api\EmployeeCardController;
use App\Http\Controllers\Api\ExportController;
use App\Http\Controllers\Api\HolidayController;
use App\Http\Controllers\Api\LateArrivalController;
use App\Http\Controllers\Api\LocationController;
use App\Http\Controllers\Api\NotificationController;
use App\Http\Controllers\Api\OfficeController;
use App\Http\Controllers\Api\OvertimeController;
use App\Http\Controllers\Api\QrScannerController;
use App\Http\Controllers\Api\SettingsController;
use App\Http\Controllers\Api\ShiftController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
*/

// Public routes (tanpa auth)
Route::prefix('auth')->group(function () {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/check-approval-status', [AuthController::class, 'checkApprovalStatus']);
    Route::get('/companies', [AuthController::class, 'companies']);
});

// Protected routes (membutuhkan auth)
Route::middleware('auth:sanctum')->group(function () {

    // Auth routes
    Route::prefix('auth')->group(function () {
        Route::post('/logout', [AuthController::class, 'logout']);
        Route::post('/logout-all', [AuthController::class, 'logoutAll']);
        Route::get('/profile', [AuthController::class, 'profile']);
        Route::put('/profile', [AuthController::class, 'updateProfile']);
        Route::post('/profile', [AuthController::class, 'updateProfile']); // For file upload (multipart/form-data)
        Route::put('/password', [AuthController::class, 'updatePassword']);
        Route::put('/home-location', [AuthController::class, 'updateHomeLocation']);
    });

    // Attendance routes (Presensi Harian)
    Route::prefix('attendance')->group(function () {
        Route::post('/check-in', [AttendanceController::class, 'checkIn']);
        Route::post('/check-out', [AttendanceController::class, 'checkOut']);
        Route::get('/today', [AttendanceController::class, 'today']);
        Route::get('/today-list', [AttendanceController::class, 'todayList']);
        Route::get('/history', [AttendanceController::class, 'history']);
        Route::get('/statistics', [AttendanceController::class, 'statistics']);
        Route::get('/calendar', [AttendanceController::class, 'calendar']);
        Route::get('/missing-activities', [AttendanceController::class, 'missingActivities']);
        Route::get('/today-missing-activity', [AttendanceController::class, 'todayMissingActivity']);
        Route::get('/red-flags', [AttendanceController::class, 'getRedFlags']);

        // Backdate & edit attendance (all users within cutoff period)
        Route::post('/backdate', [AttendanceController::class, 'backdateAttendance']);
        Route::put('/{attendance}', [AttendanceController::class, 'updateAttendance']);

        Route::get('/{date}', [AttendanceController::class, 'show']);
    });

    // Business Trip routes (Perjalanan Dinas)
    Route::prefix('business-trips')->group(function () {
        Route::get('/', [BusinessTripController::class, 'index']);
        Route::post('/', [BusinessTripController::class, 'store']);
        Route::get('/active', [BusinessTripController::class, 'active']);
        Route::get('/pending-approvals', [BusinessTripController::class, 'pendingApprovals']);

        // Routes untuk absen dinas tanpa pengajuan
        Route::get('/locations', [BusinessTripController::class, 'allLocations']);
        Route::get('/locations/nearby', [BusinessTripController::class, 'nearbyLocations']);
        Route::post('/direct-check-in', [BusinessTripController::class, 'directCheckIn']);
        Route::post('/direct-check-out', [BusinessTripController::class, 'directCheckOut']);

        Route::prefix('{businessTrip}')->group(function () {
            Route::get('/', [BusinessTripController::class, 'show']);
            Route::post('/cancel', [BusinessTripController::class, 'cancel']);
            Route::post('/approve', [BusinessTripController::class, 'approve']);
            Route::post('/reject', [BusinessTripController::class, 'reject']);
            Route::post('/check-in', [BusinessTripController::class, 'checkIn']);
            Route::post('/check-out', [BusinessTripController::class, 'checkOut']);
            Route::get('/today-status', [BusinessTripController::class, 'todayStatus']);
            Route::get('/recommended-locations', [BusinessTripController::class, 'recommendedLocations']);
            Route::get('/documents', [DocumentController::class, 'byBusinessTrip']);
        });
    });

    // Document routes (Dokumen Pendukung)
    Route::prefix('documents')->group(function () {
        Route::get('/', [DocumentController::class, 'index']);
        Route::get('/types', [DocumentController::class, 'types']);
        Route::post('/', [DocumentController::class, 'store']);
        Route::get('/{document}', [DocumentController::class, 'show']);
        Route::delete('/{document}', [DocumentController::class, 'destroy']);
    });

    // Office routes (Kantor/Lokasi) - Legacy, tetap dipertahankan untuk backward compatibility
    Route::prefix('offices')->group(function () {
        Route::get('/', [OfficeController::class, 'index']);
        Route::get('/{office}', [OfficeController::class, 'show']);
    });

    // Location routes (Unified: Kantor + Lokasi Dinas)
    Route::prefix('locations')->group(function () {
        Route::get('/', [LocationController::class, 'index']);
        Route::get('/nearby', [LocationController::class, 'nearby']);
        Route::get('/offices', [LocationController::class, 'offices']);
        Route::get('/business-trip', [LocationController::class, 'businessTripDestinations']);
        Route::get('/recommendations', [LocationController::class, 'recommendations']);
        Route::post('/', [LocationController::class, 'store']); // Admin only
        Route::get('/{location}', [LocationController::class, 'show']);
        Route::put('/{location}', [LocationController::class, 'update']); // Admin only
    });

    // Activity routes (Aktivitas Harian)
    Route::prefix('activities')->group(function () {
        Route::get('/', [ActivityController::class, 'index']);
        Route::get('/can-create', [ActivityController::class, 'canCreate']); // Cek apakah bisa buat activity
        Route::post('/', [ActivityController::class, 'store']);
        Route::put('/{activity}', [ActivityController::class, 'update']);
    });

    // Integrated Activity routes (dari Attendance)
    Route::prefix('attendance')->group(function () {
        Route::post('/{attendance}/activities', [ActivityController::class, 'storeFromAttendance']);
    });

    // Settings routes (Pengaturan)
    Route::prefix('settings')->group(function () {
        Route::get('/', [SettingsController::class, 'index']);
        Route::get('/activity', [SettingsController::class, 'activity']);
        Route::put('/', [SettingsController::class, 'update']); // Super admin only
        Route::get('/company-location', [SettingsController::class, 'getCompanyLocation']);
        Route::put('/company-location', [SettingsController::class, 'updateCompanyLocation']); // Admin only
    });

    // Notification routes (Notifikasi)
    Route::prefix('notifications')->group(function () {
        Route::get('/', [NotificationController::class, 'index']);
        Route::get('/unread-count', [NotificationController::class, 'unreadCount']);
        Route::post('/mark-all-read', [NotificationController::class, 'markAllAsRead']);
        Route::post('/clear-all', [NotificationController::class, 'clearAll']);
        Route::post('/fcm-token', [NotificationController::class, 'updateFcmToken']);
        Route::post('/{notification}/read', [NotificationController::class, 'markAsRead']);
        Route::delete('/{notification}', [NotificationController::class, 'destroy']);
    });

    // Holiday routes (Hari Libur)
    Route::prefix('holidays')->group(function () {
        Route::get('/', [HolidayController::class, 'index']);
        Route::get('/check', [HolidayController::class, 'check']);
        Route::get('/upcoming', [HolidayController::class, 'upcoming']);
        Route::get('/weekend-settings', [HolidayController::class, 'weekendSettings']);
        Route::put('/weekend-settings', [HolidayController::class, 'updateWeekendSettings']); // Super admin only
        Route::post('/', [HolidayController::class, 'store']); // Admin only
        Route::put('/{holiday}', [HolidayController::class, 'update']); // Admin only
        Route::delete('/{holiday}', [HolidayController::class, 'destroy']); // Admin only
    });

    // Overtime routes (Lembur)
    Route::prefix('overtimes')->group(function () {
        Route::get('/', [OvertimeController::class, 'index']);
        Route::get('/summary', [OvertimeController::class, 'summary']);
        Route::get('/pending', [OvertimeController::class, 'pending']); // Admin only
        Route::post('/', [OvertimeController::class, 'store']);
        Route::get('/{overtime}', [OvertimeController::class, 'show']);
        Route::post('/{overtime}/cancel', [OvertimeController::class, 'cancel']);
        Route::post('/{overtime}/approve', [OvertimeController::class, 'approve']); // Admin only
        Route::post('/{overtime}/reject', [OvertimeController::class, 'reject']); // Admin only
        Route::post('/bulk-approve', [OvertimeController::class, 'bulkApprove']); // Admin only
        Route::post('/bulk-reject', [OvertimeController::class, 'bulkReject']); // Admin only
    });

    // Device management routes (Manajemen Device)
    Route::prefix('devices')->group(function () {
        Route::get('/', [DeviceController::class, 'myDevices']);
        Route::post('/register', [DeviceController::class, 'register']);
        Route::post('/check-status', [DeviceController::class, 'checkStatus']);
        Route::post('/migrate', [DeviceController::class, 'migrate']); // Migrate old device ID to new format
        Route::delete('/{device}', [DeviceController::class, 'remove']);
        Route::post('/{device}/set-primary', [DeviceController::class, 'setPrimary']);

        // Admin routes
        Route::get('/pending-approvals', [DeviceController::class, 'pendingApprovals']); // Admin only
        Route::get('/user/{user}', [DeviceController::class, 'userDevices']); // Admin only
        Route::post('/{device}/approve', [DeviceController::class, 'approve']); // Admin only
        Route::post('/{device}/reject', [DeviceController::class, 'reject']); // Admin only
        Route::delete('/admin/{device}', [DeviceController::class, 'adminRemove']); // Admin only
    });

    // Attendance Correction routes (Koreksi Absen)
    Route::prefix('corrections')->group(function () {
        Route::get('/', [AttendanceCorrectionController::class, 'history']);
        Route::get('/settings', [AttendanceCorrectionController::class, 'settings']);
        Route::get('/eligible-attendances', [AttendanceCorrectionController::class, 'eligibleAttendances']);
        Route::post('/', [AttendanceCorrectionController::class, 'store']);
        Route::get('/{correction}', [AttendanceCorrectionController::class, 'show']);
        Route::delete('/{correction}', [AttendanceCorrectionController::class, 'cancel']);
    });

    // Early Leave routes (Izin Pulang Cepat)
    Route::prefix('early-leave')->group(function () {
        Route::get('/', [EarlyLeaveController::class, 'index']);
        Route::get('/status', [EarlyLeaveController::class, 'status']);
        Route::get('/reason-types', [EarlyLeaveController::class, 'getReasonTypes']);
        Route::post('/', [EarlyLeaveController::class, 'store']);
        Route::get('/{earlyLeave}', [EarlyLeaveController::class, 'show']);
        Route::delete('/{earlyLeave}', [EarlyLeaveController::class, 'destroy']);
    });

    // Late Arrival routes (Izin Terlambat)
    Route::prefix('late-arrival')->group(function () {
        Route::get('/', [LateArrivalController::class, 'index']);
        Route::get('/status', [LateArrivalController::class, 'status']);
        Route::get('/reason-types', [LateArrivalController::class, 'getReasonTypes']);
        Route::post('/', [LateArrivalController::class, 'store']);
        Route::get('/{lateArrival}', [LateArrivalController::class, 'show']);
        Route::delete('/{lateArrival}', [LateArrivalController::class, 'destroy']);
    });

    // Admin routes (Admin only)
    Route::prefix('admin')->group(function () {
        Route::prefix('attendance')->group(function () {
            Route::get('/status', [AttendanceController::class, 'adminAttendanceStatus']);
            Route::get('/missing', [AttendanceController::class, 'adminAttendanceMissing']);
            Route::post('/backdate', [AttendanceController::class, 'backdateAttendance']);
            Route::put('/{attendance}', [AttendanceController::class, 'updateAttendance']);
        });

        // Admin Correction routes
        Route::prefix('corrections')->group(function () {
            Route::get('/pending', [AttendanceCorrectionController::class, 'adminPending']);
            Route::post('/{correction}/approve', [AttendanceCorrectionController::class, 'adminApprove']);
            Route::post('/{correction}/reject', [AttendanceCorrectionController::class, 'adminReject']);
        });

        // Admin Early Leave routes
        Route::prefix('early-leave')->group(function () {
            Route::get('/pending', [EarlyLeaveController::class, 'adminPending']);
            Route::post('/{earlyLeave}/approve', [EarlyLeaveController::class, 'adminApprove']);
            Route::post('/{earlyLeave}/reject', [EarlyLeaveController::class, 'adminReject']);
        });

        // Admin Late Arrival routes
        Route::prefix('late-arrival')->group(function () {
            Route::get('/pending', [LateArrivalController::class, 'adminPending']);
            Route::post('/{lateArrival}/approve', [LateArrivalController::class, 'adminApprove']);
            Route::post('/{lateArrival}/reject', [LateArrivalController::class, 'adminReject']);
        });
    });

    // Export routes (Download Laporan)
    Route::prefix('export')->group(function () {
        Route::get('/attendance', [ExportController::class, 'attendanceExport']);
        Route::get('/my-attendance', [ExportController::class, 'myAttendanceExport']);
        Route::get('/download', [ExportController::class, 'download'])->name('api.export.download');
    });

    // Employee Card routes (Kartu Karyawan)
    Route::prefix('employee-card')->group(function () {
        Route::get('/my-card', [EmployeeCardController::class, 'myCard']);
        Route::get('/', [EmployeeCardController::class, 'index']); // Admin only
        Route::post('/generate', [EmployeeCardController::class, 'generate']); // Admin only
        Route::post('/batch-generate', [EmployeeCardController::class, 'batchGenerate']); // Admin only
        Route::get('/{card}', [EmployeeCardController::class, 'show']); // Admin only
        Route::get('/{card}/pdf', [EmployeeCardController::class, 'downloadPdf']);
        Route::post('/{card}/revoke', [EmployeeCardController::class, 'revoke']); // Admin only
    });

    // QR Scanner routes (Scanner QR untuk Admin)
    Route::prefix('qr-scanner')->group(function () {
        Route::get('/status', [QrScannerController::class, 'status']);
        Route::post('/scan', [QrScannerController::class, 'scan']); // Admin only
        Route::get('/history', [QrScannerController::class, 'history']); // Admin only
        Route::get('/statistics', [QrScannerController::class, 'statistics']); // Admin only
    });

    // Shift routes (Shift Kerja)
    Route::prefix('shifts')->group(function () {
        Route::get('/', [ShiftController::class, 'index']);
        Route::get('/my-shift', [ShiftController::class, 'myShift']);
        Route::get('/users', [ShiftController::class, 'usersWithShifts']); // Admin only
        Route::post('/', [ShiftController::class, 'store']); // Admin only
        Route::get('/{shift}', [ShiftController::class, 'show']);
        Route::put('/{shift}', [ShiftController::class, 'update']); // Admin only
        Route::delete('/{shift}', [ShiftController::class, 'destroy']); // Admin only
        Route::post('/{shift}/assign-users', [ShiftController::class, 'assignUsers']); // Admin only
        Route::delete('/{shift}/users/{targetUser}', [ShiftController::class, 'removeUser']); // Admin only
    });

    // Activity Assignment routes (Pengaturan Aktivitas Wajib)
    Route::prefix('activity-rules')->group(function () {
        Route::get('/check-mandatory', [ActivityAssignmentController::class, 'checkMandatory']);
        Route::get('/', [ActivityAssignmentController::class, 'index']); // Admin only
        Route::post('/', [ActivityAssignmentController::class, 'store']); // Admin only
        Route::put('/{rule}', [ActivityAssignmentController::class, 'update']); // Admin only
        Route::delete('/{rule}', [ActivityAssignmentController::class, 'destroy']); // Admin only
        Route::get('/statistics', [ActivityAssignmentController::class, 'statistics']); // Admin only
        Route::get('/departments', [ActivityAssignmentController::class, 'departments']); // Admin only
        Route::get('/positions', [ActivityAssignmentController::class, 'positions']); // Admin only
        Route::post('/preview', [ActivityAssignmentController::class, 'preview']); // Admin only
    });
});
