<?php

use App\Http\Controllers\Employee\ExportController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

// Temporary cache clear route - HAPUS SETELAH DIGUNAKAN
Route::get('/clear-cache-xyz123', function () {
    $results = [];

    // Laravel caches
    \Illuminate\Support\Facades\Artisan::call('optimize:clear');
    $results[] = 'optimize:clear done';

    \Illuminate\Support\Facades\Artisan::call('filament:clear-cached-components');
    $results[] = 'filament:clear-cached-components done';

    \Illuminate\Support\Facades\Artisan::call('view:clear');
    $results[] = 'view:clear done';

    // OPcache - invalidate specific files
    if (function_exists('opcache_invalidate')) {
        $filesToInvalidate = [
            app_path('Filament/Employee/Resources/MyAttendanceResource.php'),
            app_path('Filament/Resources/AttendanceResource.php'),
            resource_path('views/filament/infolists/attendance-map.blade.php'),
            resource_path('views/components/google-map.blade.php'),
        ];

        foreach ($filesToInvalidate as $file) {
            if (file_exists($file)) {
                opcache_invalidate($file, true);
                $results[] = "opcache_invalidate: " . basename($file);
            }
        }
    }

    // Reset entire OPcache as fallback
    if (function_exists('opcache_reset')) {
        opcache_reset();
        $results[] = 'opcache_reset done';
    }

    return 'Cache cleared! ' . now() . "\n\n" . implode("\n", $results);
});

// Debug route to check file version - HAPUS SETELAH DIGUNAKAN
Route::get('/debug-file-xyz123', function () {
    $results = [];

    // 1. Check MyAttendanceResource.php
    $file1 = app_path('Filament/Employee/Resources/MyAttendanceResource.php');
    if (file_exists($file1)) {
        $content1 = file_get_contents($file1);
        $results['MyAttendanceResource'] = [
            'exists' => true,
            'size' => filesize($file1),
            'modified' => date('Y-m-d H:i:s', filemtime($file1)),
            'has_peta_lokasi' => str_contains($content1, 'Peta Lokasi'),
            'has_attendance_map' => str_contains($content1, 'attendance-map'),
            'has_ViewEntry' => str_contains($content1, 'ViewEntry::make'),
            'has_infolist' => str_contains($content1, 'public static function infolist'),
        ];
    } else {
        $results['MyAttendanceResource'] = ['exists' => false];
    }

    // 2. Check attendance-map.blade.php
    $file2 = resource_path('views/filament/infolists/attendance-map.blade.php');
    if (file_exists($file2)) {
        $content2 = file_get_contents($file2);
        $results['attendance-map.blade'] = [
            'exists' => true,
            'size' => filesize($file2),
            'modified' => date('Y-m-d H:i:s', filemtime($file2)),
            'has_google_map' => str_contains($content2, 'google-map'),
            'first_100_chars' => substr($content2, 0, 100),
        ];
    } else {
        $results['attendance-map.blade'] = ['exists' => false];
    }

    // 3. Check google-map.blade.php component
    $file3 = resource_path('views/components/google-map.blade.php');
    if (file_exists($file3)) {
        $content3 = file_get_contents($file3);
        $results['google-map.blade'] = [
            'exists' => true,
            'size' => filesize($file3),
            'modified' => date('Y-m-d H:i:s', filemtime($file3)),
            'has_google_maps_api' => str_contains($content3, 'maps.googleapis.com'),
        ];
    } else {
        $results['google-map.blade'] = ['exists' => false];
    }

    // 4. Check ViewMyAttendance page (correct filename)
    $file4 = app_path('Filament/Employee/Resources/MyAttendanceResource/Pages/ViewMyAttendance.php');
    if (file_exists($file4)) {
        $results['ViewMyAttendance'] = [
            'exists' => true,
            'size' => filesize($file4),
            'modified' => date('Y-m-d H:i:s', filemtime($file4)),
        ];
    } else {
        $results['ViewMyAttendance'] = ['exists' => false];
    }

    // 5. List all files in Pages directory
    $pagesDir = app_path('Filament/Employee/Resources/MyAttendanceResource/Pages');
    if (is_dir($pagesDir)) {
        $files = scandir($pagesDir);
        $results['Pages_directory'] = array_values(array_diff($files, ['.', '..']));
    } else {
        $results['Pages_directory'] = 'directory not found - THIS IS THE PROBLEM!';
    }

    // 5. List all files in views/filament/infolists/
    $infolistsDir = resource_path('views/filament/infolists');
    if (is_dir($infolistsDir)) {
        $files = scandir($infolistsDir);
        $results['infolists_directory'] = array_values(array_diff($files, ['.', '..']));
    } else {
        $results['infolists_directory'] = 'directory not found';
    }

    // 6. List all files in views/components/
    $componentsDir = resource_path('views/components');
    if (is_dir($componentsDir)) {
        $files = scandir($componentsDir);
        $results['components_directory'] = array_values(array_diff($files, ['.', '..']));
    } else {
        $results['components_directory'] = 'directory not found';
    }

    return response()->json($results, 200, [], JSON_PRETTY_PRINT);
});

// Force restart - HAPUS SETELAH DIGUNAKAN
Route::get('/force-restart-xyz123', function () {
    $results = [];

    // 1. Clear all Laravel caches
    \Illuminate\Support\Facades\Artisan::call('optimize:clear');
    $results[] = 'optimize:clear done';

    \Illuminate\Support\Facades\Artisan::call('cache:clear');
    $results[] = 'cache:clear done';

    \Illuminate\Support\Facades\Artisan::call('config:clear');
    $results[] = 'config:clear done';

    \Illuminate\Support\Facades\Artisan::call('route:clear');
    $results[] = 'route:clear done';

    \Illuminate\Support\Facades\Artisan::call('view:clear');
    $results[] = 'view:clear done';

    \Illuminate\Support\Facades\Artisan::call('event:clear');
    $results[] = 'event:clear done';

    // 2. Clear Filament cache
    try {
        \Illuminate\Support\Facades\Artisan::call('filament:clear-cached-components');
        $results[] = 'filament:clear-cached-components done';
    } catch (\Exception $e) {
        $results[] = 'filament cache: ' . $e->getMessage();
    }

    // 3. Clear bootstrap cache files
    $bootstrapCacheFiles = glob(base_path('bootstrap/cache/*.php'));
    foreach ($bootstrapCacheFiles as $cacheFile) {
        if (basename($cacheFile) !== '.gitignore') {
            @unlink($cacheFile);
            $results[] = 'deleted: bootstrap/cache/' . basename($cacheFile);
        }
    }

    // 4. Clear storage framework cache
    $storageCacheDirs = [
        storage_path('framework/cache/data'),
        storage_path('framework/views'),
    ];
    foreach ($storageCacheDirs as $dir) {
        if (is_dir($dir)) {
            $files = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
                \RecursiveIteratorIterator::CHILD_FIRST
            );
            $count = 0;
            foreach ($files as $fileinfo) {
                if ($fileinfo->isFile() && $fileinfo->getFilename() !== '.gitignore') {
                    @unlink($fileinfo->getRealPath());
                    $count++;
                }
            }
            $results[] = "cleared $count files from " . basename($dir);
        }
    }

    // 5. OPcache full reset
    if (function_exists('opcache_reset')) {
        opcache_reset();
        $results[] = 'opcache_reset done';
    }

    // 6. Touch autoload to trigger composer dump
    $autoload = base_path('vendor/autoload.php');
    if (file_exists($autoload)) {
        touch($autoload);
        $results[] = 'touched vendor/autoload.php';
    }

    return response()->json([
        'status' => 'Cache fully cleared',
        'timestamp' => now()->toDateTimeString(),
        'results' => $results,
        'next_steps' => [
            '1. Hard refresh browser (Ctrl+Shift+R atau Cmd+Shift+R)',
            '2. Clear browser cache',
            '3. Jika masih tidak berhasil, mungkin ada cache di level hosting/CDN',
        ]
    ]);
});

// Debug attendance data - HAPUS SETELAH DIGUNAKAN
Route::get('/debug-attendance-xyz123/{id}', function ($id) {
    $attendance = \App\Models\Attendance::find($id);

    if (!$attendance) {
        return response()->json(['error' => 'Attendance not found']);
    }

    return response()->json([
        'id' => $attendance->id,
        'date' => $attendance->date,
        'check_in_latitude' => $attendance->check_in_latitude,
        'check_in_longitude' => $attendance->check_in_longitude,
        'check_in_address' => $attendance->check_in_address,
        'check_out_latitude' => $attendance->check_out_latitude,
        'check_out_longitude' => $attendance->check_out_longitude,
        'has_location_data' => ($attendance->check_in_latitude && $attendance->check_in_longitude),
    ]);
});

// Debug locations - HAPUS SETELAH DIGUNAKAN (HTML dengan link clickable)
Route::get('/debug-locations-xyz123', function () {
    $locations = \App\Models\Location::query()
        ->where('is_active', true)
        ->orderBy('company_id')
        ->orderBy('name')
        ->get();

    $html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Debug Locations</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 13px; }
        th { background: #4a5568; color: white; }
        tr:nth-child(even) { background: #f9f9f9; }
        tr:hover { background: #f1f1f1; }
        a { color: #3182ce; text-decoration: none; }
        a:hover { text-decoration: underline; }
        .badge { padding: 2px 8px; border-radius: 4px; font-size: 11px; }
        .primary { background: #48bb78; color: white; }
        .trip { background: #ed8936; color: white; }
        h1 { color: #2d3748; }
        .coords { font-family: monospace; font-size: 12px; }
    </style>
    </head><body>';
    $html .= '<h1>Daftar Lokasi (' . $locations->count() . ')</h1>';
    $html .= '<table><tr><th>ID</th><th>Nama</th><th>Type</th><th>Category</th><th>Koordinat</th><th>Cek di Maps</th><th>Alamat</th><th>Flags</th><th>Aksi</th></tr>';

    foreach ($locations as $loc) {
        $mapsLink = ($loc->latitude && $loc->longitude)
            ? "https://www.google.com/maps?q={$loc->latitude},{$loc->longitude}"
            : null;
        $flags = [];
        if ($loc->is_primary) $flags[] = '<span class="badge primary">Primary</span>';
        if ($loc->allow_business_trip) $flags[] = '<span class="badge trip">Dinas</span>';

        $html .= '<tr>';
        $html .= '<td>' . $loc->id . '</td>';
        $html .= '<td><strong>' . e($loc->name) . '</strong></td>';
        $html .= '<td>' . e($loc->type) . '</td>';
        $html .= '<td>' . e($loc->category) . '</td>';
        $html .= '<td class="coords">' . ($loc->latitude ?? '-') . ', ' . ($loc->longitude ?? '-') . '</td>';
        $html .= '<td>' . ($mapsLink ? '<a href="' . $mapsLink . '" target="_blank">🗺️ Buka Maps</a>' : '-') . '</td>';
        $html .= '<td>' . e(\Illuminate\Support\Str::limit($loc->address, 50)) . '</td>';
        $html .= '<td>' . implode(' ', $flags) . '</td>';
        $html .= '<td><a href="/update-location-xyz123/' . $loc->id . '" style="color:#ed8936;">✏️ Edit</a></td>';
        $html .= '</tr>';
    }

    $html .= '</table></body></html>';
    return response($html);
});

// Debug Surat Tugas - HAPUS SETELAH DIGUNAKAN (HTML dengan link clickable)
Route::get('/debug-surat-tugas-xyz123', function () {
    $suratTugas = \App\Models\SuratTugas::query()
        ->where('is_active', true)
        ->with(['location:id,name,latitude,longitude,address'])
        ->orderBy('tanggal_mulai', 'desc')
        ->get();

    $html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Debug Surat Tugas</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 13px; }
        th { background: #4a5568; color: white; }
        tr:nth-child(even) { background: #f9f9f9; }
        tr:hover { background: #f1f1f1; }
        a { color: #3182ce; text-decoration: none; }
        a:hover { text-decoration: underline; }
        .badge { padding: 2px 8px; border-radius: 4px; font-size: 11px; }
        .db { background: #48bb78; color: white; }
        .custom { background: #ed8936; color: white; }
        h1 { color: #2d3748; }
        .coords { font-family: monospace; font-size: 12px; }
    </style>
    </head><body>';
    $html .= '<h1>Daftar Surat Tugas Aktif (' . $suratTugas->count() . ')</h1>';
    $html .= '<table><tr><th>ID</th><th>No ST</th><th>Periode</th><th>Lokasi</th><th>Sumber</th><th>Koordinat</th><th>Cek di Maps</th><th>Users</th><th>Aksi</th></tr>';

    foreach ($suratTugas as $st) {
        $finalLat = $st->location ? $st->location->latitude : $st->custom_latitude;
        $finalLon = $st->location ? $st->location->longitude : $st->custom_longitude;
        $locationName = $st->location ? $st->location->name : $st->custom_location_name;
        $source = $st->location_id ? '<span class="badge db">Database</span>' : '<span class="badge custom">Custom</span>';

        $mapsLink = ($finalLat && $finalLon)
            ? "https://www.google.com/maps?q={$finalLat},{$finalLon}"
            : null;

        $periode = ($st->tanggal_mulai ? $st->tanggal_mulai->format('d M') : '-') . ' - ' .
                   ($st->tanggal_selesai ? $st->tanggal_selesai->format('d M Y') : '-');

        $html .= '<tr>';
        $html .= '<td>' . $st->id . '</td>';
        $html .= '<td>' . e($st->no_st ?? '-') . '</td>';
        $html .= '<td>' . $periode . '</td>';
        $html .= '<td><strong>' . e($locationName ?? '-') . '</strong></td>';
        $html .= '<td>' . $source . '</td>';
        $html .= '<td class="coords">' . ($finalLat ?? '-') . ', ' . ($finalLon ?? '-') . '</td>';
        $html .= '<td>' . ($mapsLink ? '<a href="' . $mapsLink . '" target="_blank">🗺️ Buka Maps</a>' : '-') . '</td>';
        $html .= '<td>' . $st->users()->count() . '</td>';
        $html .= '<td><a href="/update-st-xyz123/' . $st->id . '" style="color:#ed8936;">✏️ Edit</a></td>';
        $html .= '</tr>';
    }

    $html .= '</table></body></html>';
    return response($html);
});

// Update koordinat lokasi - HAPUS SETELAH DIGUNAKAN
Route::get('/update-location-xyz123/{id}', function ($id, \Illuminate\Http\Request $request) {
    $location = \App\Models\Location::find($id);
    if (!$location) {
        return response()->json(['error' => 'Location not found'], 404);
    }

    // Jika ada parameter lat dan lon, update
    if ($request->has('lat') && $request->has('lon')) {
        $location->latitude = $request->input('lat');
        $location->longitude = $request->input('lon');
        if ($request->has('address')) {
            $location->address = $request->input('address');
        }
        $location->save();

        return response()->json([
            'success' => true,
            'message' => "Location '{$location->name}' updated",
            'new_coords' => [
                'latitude' => $location->latitude,
                'longitude' => $location->longitude,
            ],
            'maps_link' => "https://www.google.com/maps?q={$location->latitude},{$location->longitude}",
        ]);
    }

    // Tampilkan form HTML
    $mapsLink = ($location->latitude && $location->longitude)
        ? "https://www.google.com/maps?q={$location->latitude},{$location->longitude}"
        : "https://www.google.com/maps/search/" . urlencode($location->name);

    $searchLink = "https://www.google.com/maps/search/" . urlencode("BPKP Perwakilan " . $location->province);

    return response("<!DOCTYPE html><html><head><meta charset='utf-8'><title>Update {$location->name}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; max-width: 800px; }
        .info { background: #f0f0f0; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .info h2 { margin-top: 0; }
        .field { margin: 15px 0; }
        label { display: block; font-weight: bold; margin-bottom: 5px; }
        input[type=text] { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 12px 24px; font-size: 16px; background: #4299e1; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #3182ce; }
        a { color: #3182ce; }
        .maps-btn { display: inline-block; padding: 10px 20px; background: #48bb78; color: white; text-decoration: none; border-radius: 4px; margin: 5px 0; }
        .maps-btn:hover { background: #38a169; }
        .warning { background: #fed7d7; padding: 10px; border-radius: 4px; margin: 10px 0; }
        .current { color: #718096; font-family: monospace; }
    </style>
    </head><body>
    <h1>Update Koordinat Lokasi</h1>

    <div class='info'>
        <h2>{$location->name}</h2>
        <p><strong>ID:</strong> {$location->id}</p>
        <p><strong>Type:</strong> {$location->type}</p>
        <p><strong>Province:</strong> {$location->province}</p>
        <p><strong>Alamat saat ini:</strong> {$location->address}</p>
        <p><strong>Koordinat saat ini:</strong> <span class='current'>{$location->latitude}, {$location->longitude}</span></p>
    </div>

    <h3>Langkah 1: Cari lokasi yang benar di Google Maps</h3>
    <a href='{$searchLink}' target='_blank' class='maps-btn'>🔍 Cari di Google Maps</a>
    <a href='{$mapsLink}' target='_blank' class='maps-btn'>📍 Lihat Koordinat Saat Ini</a>

    <div class='warning'>
        <strong>Cara mendapatkan koordinat:</strong><br>
        1. Buka Google Maps dan cari lokasi BPKP yang benar<br>
        2. Klik kanan pada marker/lokasi<br>
        3. Klik koordinat yang muncul di menu (akan disalin otomatis)<br>
        4. Paste di form di bawah (format: -6.12345, 106.12345)
    </div>

    <h3>Langkah 2: Input koordinat baru</h3>
    <form method='GET'>
        <div class='field'>
            <label>Latitude:</label>
            <input type='text' name='lat' value='{$location->latitude}' placeholder='-6.12345' required>
        </div>
        <div class='field'>
            <label>Longitude:</label>
            <input type='text' name='lon' value='{$location->longitude}' placeholder='106.12345' required>
        </div>
        <div class='field'>
            <label>Alamat (opsional):</label>
            <input type='text' name='address' value='{$location->address}' placeholder='Jl. ...'>
        </div>
        <button type='submit'>💾 Update Koordinat</button>
    </form>

    <br><br>
    <a href='/debug-locations-xyz123'>← Kembali ke Daftar Lokasi</a>
    </body></html>", 200, ['Content-Type' => 'text/html']);
});

// Update koordinat Surat Tugas - HAPUS SETELAH DIGUNAKAN
Route::get('/update-st-xyz123/{id}', function ($id, \Illuminate\Http\Request $request) {
    $st = \App\Models\SuratTugas::find($id);
    if (!$st) {
        return response()->json(['error' => 'Surat Tugas not found'], 404);
    }

    // Jika ada parameter lat dan lon, update custom coordinates
    if ($request->has('lat') && $request->has('lon')) {
        $st->custom_latitude = $request->input('lat');
        $st->custom_longitude = $request->input('lon');
        if ($request->has('location_name')) {
            $st->custom_location_name = $request->input('location_name');
        }
        if ($request->has('address')) {
            $st->custom_address = $request->input('address');
        }
        // Clear location_id jika menggunakan custom
        if ($request->has('use_custom') && $request->input('use_custom') == '1') {
            $st->location_id = null;
        }
        $st->save();

        return response()->json([
            'success' => true,
            'message' => "Surat Tugas '{$st->no_st}' updated",
            'new_coords' => [
                'latitude' => $st->custom_latitude,
                'longitude' => $st->custom_longitude,
            ],
            'maps_link' => "https://www.google.com/maps?q={$st->custom_latitude},{$st->custom_longitude}",
        ]);
    }

    // Get current location info
    $currentLat = $st->location ? $st->location->latitude : $st->custom_latitude;
    $currentLon = $st->location ? $st->location->longitude : $st->custom_longitude;
    $currentName = $st->location ? $st->location->name : $st->custom_location_name;

    $mapsLink = ($currentLat && $currentLon)
        ? "https://www.google.com/maps?q={$currentLat},{$currentLon}"
        : "#";

    return response("<!DOCTYPE html><html><head><meta charset='utf-8'><title>Update ST {$st->no_st}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; max-width: 800px; }
        .info { background: #f0f0f0; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .field { margin: 15px 0; }
        label { display: block; font-weight: bold; margin-bottom: 5px; }
        input[type=text] { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 12px 24px; font-size: 16px; background: #4299e1; color: white; border: none; border-radius: 4px; cursor: pointer; }
        a { color: #3182ce; }
        .maps-btn { display: inline-block; padding: 10px 20px; background: #48bb78; color: white; text-decoration: none; border-radius: 4px; }
        .current { color: #718096; font-family: monospace; }
        .warning { background: #fefcbf; padding: 10px; border-radius: 4px; margin: 10px 0; }
    </style>
    </head><body>
    <h1>Update Koordinat Surat Tugas</h1>

    <div class='info'>
        <h2>No. ST: {$st->no_st}</h2>
        <p><strong>ID:</strong> {$st->id}</p>
        <p><strong>Lokasi:</strong> {$currentName}</p>
        <p><strong>Sumber:</strong> " . ($st->location_id ? 'Database (Location ID: ' . $st->location_id . ')' : 'Custom') . "</p>
        <p><strong>Koordinat saat ini:</strong> <span class='current'>{$currentLat}, {$currentLon}</span></p>
    </div>

    " . ($st->location_id ? "<div class='warning'><strong>Catatan:</strong> ST ini menggunakan lokasi dari database. Jika Anda update di sini, koordinat custom akan digunakan.</div>" : "") . "

    <a href='{$mapsLink}' target='_blank' class='maps-btn'>📍 Lihat di Google Maps</a>

    <h3>Update Koordinat Custom</h3>
    <form method='GET'>
        <input type='hidden' name='use_custom' value='1'>
        <div class='field'>
            <label>Nama Lokasi:</label>
            <input type='text' name='location_name' value='" . e($st->custom_location_name ?? $currentName) . "'>
        </div>
        <div class='field'>
            <label>Latitude:</label>
            <input type='text' name='lat' value='{$st->custom_latitude}' placeholder='-6.12345' required>
        </div>
        <div class='field'>
            <label>Longitude:</label>
            <input type='text' name='lon' value='{$st->custom_longitude}' placeholder='106.12345' required>
        </div>
        <div class='field'>
            <label>Alamat:</label>
            <input type='text' name='address' value='" . e($st->custom_address) . "'>
        </div>
        <button type='submit'>💾 Update Koordinat</button>
    </form>

    <br><br>
    <a href='/debug-surat-tugas-xyz123'>← Kembali ke Daftar ST</a>
    </body></html>", 200, ['Content-Type' => 'text/html']);
});

// Employee Export Routes (requires authentication)
Route::middleware(['auth'])->prefix('employee')->name('employee.')->group(function () {
    Route::get('/export/attendance', [ExportController::class, 'exportAttendance'])->name('export.attendance');
    Route::get('/export/activity', [ExportController::class, 'exportActivity'])->name('export.activity');
    Route::get('/export/download', [ExportController::class, 'downloadFile'])->name('export.download');

    // Update attendance coordinates
    Route::post('/my-attendances/{record}/update-coordinates', function ($record) {
        $page = new \App\Filament\Employee\Resources\MyAttendanceResource\Pages\ViewMyAttendance();
        return $page->updateCoordinates(request(), \App\Models\Attendance::findOrFail($record));
    })->name('my-attendances.update-coordinates');
});

// Admin routes for update coordinates and export download
Route::middleware(['auth'])->prefix('admin')->name('admin.')->group(function () {
    Route::post('/attendances/{record}/update-coordinates', function ($record) {
        $page = new \App\Filament\Resources\AttendanceResource\Pages\ViewAttendance();
        return $page->updateCoordinates(request(), \App\Models\Attendance::findOrFail($record));
    })->name('attendances.update-coordinates');

    // Export download route for admin
    Route::get('/export/download', function (\Illuminate\Http\Request $request) {
        $filename = $request->get('file');

        if (!$filename) {
            abort(400, 'Filename is required');
        }

        // Sanitize filename to prevent directory traversal
        $filename = basename($filename);

        $fullPath = storage_path('app/exports/' . $filename);

        if (!file_exists($fullPath)) {
            abort(404, 'File not found');
        }

        // Determine content type based on extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        $contentType = match ($extension) {
            'csv' => 'text/csv',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xls' => 'application/vnd.ms-excel',
            default => 'application/octet-stream',
        };

        return response()->download($fullPath, $filename, [
            'Content-Type' => $contentType,
        ])->deleteFileAfterSend(true);
    })->name('export.download');
});
