
<?php
use App\Http\Controllers\KecamatanController;
use App\Http\Controllers\KampungController;
use App\Http\Controllers\RtrwController;
use App\Http\Controllers\ActivityLogController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PenerbitanSKPTController;
use App\Http\Controllers\PenerbitanSpmptController;
use App\Http\Controllers\PeninjauanController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\SKPTController;
use App\Http\Controllers\SpSiptController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Artisan;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/clear-cache', function () {
    Artisan::call('optimize:clear');
    return "Cache cleared successfully";
})->middleware(['auth', 'permission:clear_cache']);

Route::get('/', function () {
    return redirect()->route('login');
});

Auth::routes();
Route::post('/skpt/cek', [SKPTController::class, 'cekByRegistrasi'])->name('skpt.cek');
// ================================
// AUTHENTICATED ROUTES
// ================================
Route::group(['middleware' => ['auth', 'verified']], function () {

    // ================================
    // HOME / DASHBOARD
    // ================================
    Route::get('/home', [HomeController::class, 'index'])->name('home');
    Route::post('/filter-skpt', [HomeController::class, 'filterSkpt'])->name('filter.skpt.home');

    // ================================
    // KECAMATAN ROUTES
    // ================================
    Route::resource('kecamatan', KecamatanController::class)->names([
        'index'   => 'kecamatan.index',
        'create'  => 'kecamatan.create',
        'store'   => 'kecamatan.store',
        'show'    => 'kecamatan.show',
        'edit'    => 'kecamatan.edit',
        'update'  => 'kecamatan.update',
        'destroy' => 'kecamatan.destroy',
    ]);
    // -> middleware diatur di __construct() controller

    // ================================
    // KAMPUNG ROUTES
    // ================================
    Route::resource('kampung', KampungController::class)->names([
        'index'   => 'kampung.index',
        'create'  => 'kampung.create',
        'store'   => 'kampung.store',
        'show'    => 'kampung.show',
        'edit'    => 'kampung.edit',
        'update'  => 'kampung.update',
        'destroy' => 'kampung.destroy',
    ]);
    // -> middleware diatur di __construct() controller

    // ================================
    // RTRW ROUTES
    // ================================
    Route::resource('rtrw', RtrwController::class)->names([
        'index'   => 'rtrw.index',
        'create'  => 'rtrw.create',
        'store'   => 'rtrw.store',
        'show'    => 'rtrw.show',
        'edit'    => 'rtrw.edit',
        'update'  => 'rtrw.update',
        'destroy' => 'rtrw.destroy',
    ]);
    // -> middleware diatur di __construct() controller

    Route::get('api/rtrw/all', [RtrwController::class, 'apiAll'])
        ->middleware('permission:rtrw.view')
        ->name('rtrw.api.all');

    // ================================
    // ACTIVITY LOG ROUTES
    // ================================
    Route::prefix('activity-logs')->middleware('permission:activity-log.view')->group(function () {
        Route::get('/', [ActivityLogController::class, 'index'])->name('activity-logs.index');
        Route::get('/{activityLog}', [ActivityLogController::class, 'show'])->name('activity-logs.show');
        Route::get('-stats', [ActivityLogController::class, 'stats'])->name('activity-logs.stats');

        Route::get('-export', [ActivityLogController::class, 'export'])
            ->middleware('permission:activity-log.export')
            ->name('activity-logs.export');

        Route::delete('-clear', [ActivityLogController::class, 'clear'])
            ->middleware('permission:activity-log.clear')
            ->name('activity-logs.clear');
    });

    // ================================
    // SP-SIPT ROUTES
    // ================================
    Route::prefix('sp-sipt')->name('sp-sipt.')->group(function () {

        // Dashboard & Statistics
        Route::get('/dashboard', [SpSiptController::class, 'dashboard'])
            ->middleware('permission:sp-sipt.view')
            ->name('dashboard');

        Route::get('/statistics', [SpSiptController::class, 'getStatistics'])
            ->middleware('permission:sp-sipt.view')
            ->name('statistics');

        // Map View
        Route::get('/map', [SpSiptController::class, 'map'])
            ->middleware('permission:sp-sipt.view')
            ->name('map');

        // Reports
        Route::get('/report', [SpSiptController::class, 'report'])
            ->middleware('permission:sp-sipt.view')
            ->name('report');

        Route::post('/report/generate', [SpSiptController::class, 'generateReport'])
            ->middleware('permission:sp-sipt.view')
            ->name('report.generate');

        // Import/Export
        Route::get('/export/excel', [SpSiptController::class, 'exportExcel'])
            ->middleware('permission:sp-sipt.view')
            ->name('export.excel');

        Route::get('/export/template', [SpSiptController::class, 'downloadTemplate'])
            ->middleware('permission:sp-sipt.view')
            ->name('export.template');

        Route::post('/import', [SpSiptController::class, 'import'])
            ->middleware('permission:sp-sipt.create')
            ->name('import');

        // Search & Autocomplete
        Route::get('/search', [SpSiptController::class, 'search'])
            ->middleware('permission:sp-sipt.view')
            ->name('search');

        Route::get('/kelurahan', [SpSiptController::class, 'getKelurahan'])
            ->middleware('permission:sp-sipt.view')
            ->name('kelurahan');

        Route::get('/kecamatan', [SpSiptController::class, 'getKecamatan'])
            ->middleware('permission:sp-sipt.view')
            ->name('kecamatan');

        // Main CRUD Routes
        Route::get('/', [SpSiptController::class, 'index'])
            ->middleware('permission:sp-sipt.view')
            ->name('index');

        Route::get('/create', [SpSiptController::class, 'create'])
            ->middleware('permission:sp-sipt.create')
            ->name('create');

        Route::post('/', [SpSiptController::class, 'store'])
            ->middleware('permission:sp-sipt.create')
            ->name('store');

        Route::get('/{sp_sipt}', [SpSiptController::class, 'show'])
            ->middleware('permission:sp-sipt.view')
            ->name('show');

        Route::get('/{sp_sipt}/edit', [SpSiptController::class, 'edit'])
            ->middleware('permission:sp-sipt.edit')
            ->name('edit');

        Route::post('/{sp_sipt}', [SpSiptController::class, 'update'])
            ->middleware('permission:sp-sipt.edit')
            ->name('update');

        Route::delete('/{sp_sipt}', [SpSiptController::class, 'destroy'])
            ->middleware('permission:sp-sipt.delete')
            ->name('destroy');

        // Additional Actions for Specific SP-SIPT
        Route::prefix('{sp_sipt}')->group(function () {

            Route::get('/detail', [SpSiptController::class, 'getDetail'])
                ->middleware('permission:sp-sipt.view')
                ->name('detail');

            // Status Management
            Route::post('/status', [SpSiptController::class, 'updateStatus'])
                ->middleware('permission:sp-sipt.update-status')
                ->name('updateStatus');

            Route::post('/update-status-ajax', [SpSiptController::class, 'updateStatusAjax'])
                ->middleware('permission:sp-sipt.update-status')
                ->name('updateStatusAjax');

            // Print & Export
            Route::get('/print', [SpSiptController::class, 'print'])
                ->middleware('permission:sp-sipt.print')
                ->name('print');

            Route::get('/pdf', [SpSiptController::class, 'exportPdf'])
                ->middleware('permission:sp-sipt.print')
                ->name('pdf');

            Route::get('/export-pdf', [SpSiptController::class, 'exportPdf'])
                ->middleware('permission:sp-sipt.print')
                ->name('exportPdf');

            Route::get('/preview', [SpSiptController::class, 'preview'])
                ->middleware('permission:sp-sipt.preview')
                ->name('preview');

            // Download Document
            Route::get('/download/{documentType?}', [SpSiptController::class, 'downloadDocument'])
                ->middleware('permission:sp-sipt.view')
                ->name('downloadDocument');

            // Send Email
            Route::post('/send-email', [SpSiptController::class, 'sendEmail'])
                ->middleware('permission:sp-sipt.update-status')
                ->name('sendEmail');

            // Activity Log
            Route::get('/activity', [SpSiptController::class, 'activityLog'])
                ->middleware('permission:sp-sipt.view')
                ->name('activity');

            // Duplicate
            Route::post('/duplicate', [SpSiptController::class, 'duplicate'])
                ->middleware('permission:sp-sipt.create')
                ->name('duplicate');

            // Catatan Management
            Route::prefix('catatan')->name('catatan.')->group(function () {
                Route::post('/', [SpSiptController::class, 'storeCatatan'])
                    ->middleware('permission:sp-sipt.edit')
                    ->name('store');
            });

            // Jadwal Management
            Route::prefix('jadwal')->name('jadwal.')->group(function () {
                Route::post('/', [SpSiptController::class, 'storeJadwal'])
                    ->middleware('permission:sp-sipt.edit')
                    ->name('store');

                Route::put('/{jadwal}', [SpSiptController::class, 'updateJadwal'])
                    ->middleware('permission:sp-sipt.edit')
                    ->name('update');
            });

            // Dokumen Management
            Route::prefix('dokumen')->name('dokumen.')->group(function () {
                Route::delete('/{dokumen}', [SpSiptController::class, 'destroyDokumen'])
                    ->middleware('permission:sp-sipt.delete')
                    ->name('destroy');
            });
        });

        // Dokumen delete route (outside sp_sipt prefix)
        Route::delete('dokumen/{id}', [SpSiptController::class, 'deleteDokumen'])
            ->middleware('permission:sp-sipt.delete')
            ->name('dokumen.delete');

        // Trash Management (Soft Deletes) - Superadmin only
        Route::prefix('trash')->name('trash.')->middleware('role:superadmin')->group(function () {
            Route::post('/{id}/restore', [SpSiptController::class, 'restore'])->name('restore');
            Route::delete('/{id}/force', [SpSiptController::class, 'forceDestroy'])->name('force');
        });
    });

    // ================================
    // SKPT ROUTES
    // ================================
    Route::prefix('skpt')->group(function () {

        // API Endpoints
        Route::get('/table-data', [SKPTController::class, 'getTableData'])
            ->middleware('permission:skpt.view')
            ->name('skpt.getTableData');

        Route::get('/total-count', [SKPTController::class, 'getTotalCount'])
            ->middleware('permission:skpt.view')
            ->name('skpt.getTotalCount');

        Route::get('/polygon-data', [SKPTController::class, 'getPolygonData'])
            ->middleware('permission:skpt.view')
            ->name('skpt.getPolygonData');

        Route::get('/detail-data', [SKPTController::class, 'getDetailData'])
            ->middleware('permission:skpt.view')
            ->name('skpt.getDetailData');

        Route::post('/filter', [SKPTController::class, 'filterSkpt'])
            ->middleware('permission:skpt.view')
            ->name('filter.skpt');
    });

    Route::resource('skpt', SKPTController::class)->parameters([
        'skpt' => 'skpt'
    ])->names([
        'index'   => 'skpt.index',
        'create'  => 'skpt.create',
        'store'   => 'skpt.store',
        'show'    => 'skpt.show',
        'edit'    => 'skpt.edit',
        'update'  => 'skpt.update',
        'destroy' => 'skpt.destroy',
    ]);
    // -> middleware diatur di __construct() controller

    // SKPT Document Routes
    Route::prefix('skpt/{skpt}')->group(function () {

        Route::post('/documents/{document}/upload', [SKPTController::class, 'uploadDocument'])
            ->middleware('permission:skpt.upload-document')
            ->name('skpt.documents.upload');

        Route::post('/documents/{document}/verify', [SKPTController::class, 'verifyDocument'])
            ->middleware('permission:skpt.verify-document')
            ->name('skpt.documents.verify');

        Route::get('/documents/{document}/download', [SKPTController::class, 'downloadDocument'])
            ->middleware('permission:skpt.view')
            ->name('skpt.documents.download');

        Route::post('/additional-documents/upload', [SKPTController::class, 'uploadAdditionalDocument'])
            ->middleware('permission:skpt.upload-document')
            ->name('skpt.additional-documents.upload');

        Route::post('/additional-documents/{additional_document}/verify', [SKPTController::class, 'verifyAdditionalDocument'])
            ->middleware('permission:skpt.verify-document')
            ->name('skpt.additional-documents.verify');

        Route::get('/additional-documents/{additional_document}/download', [SKPTController::class, 'downloadAdditionalDocument'])
            ->middleware('permission:skpt.view')
            ->name('skpt.additional-documents.download');

        Route::delete('/additional-documents/{additional_document}', [SKPTController::class, 'deleteAdditionalDocument'])
            ->middleware('permission:skpt.delete')
            ->name('skpt.additional-documents.destroy');

        Route::post('update-status', [SKPTController::class, 'updateStatus'])
            ->middleware('permission:skpt.update-status')
            ->name('skpt.updateStatus');
    });

    // ================================
    // PENINJAUAN ROUTES
    // ================================
    Route::prefix('peninjauan')->name('peninjauan.')->group(function () {
    // Route update status_verifikasi BeritaAcaraPeninjauan (AJAX)

        // Route update status dokumen berita acara (AJAX)
        Route::post('/{id}/update-dokumen-status', [PeninjauanController::class, 'updateDokumenStatus'])
            ->middleware('permission:peninjauan.edit')
            ->middleware('permission:peninjauan.update-status');
        // Route download PDF dokumen berita acara
         Route::post('ba/update-verifikasi-status', [PeninjauanController::class, 'updateVerifikasiStatus'])
        ->middleware('permission:peninjauan.edit')
        ->name('update_verifikasi_status');
        Route::get('/{id}/berita-acara-list', [PeninjauanController::class, 'beritaAcaraList'])->middleware('permission:peninjauan.view')->name('beritaAcaraList');

        Route::get('/{id}/download-pdf', [PeninjauanController::class, 'downloadPdf'])
            ->middleware('permission:peninjauan.print')
            ->name('download_pdf');

        Route::get('/', [PeninjauanController::class, 'index'])
            ->middleware('permission:peninjauan.view')
            ->name('index');

        Route::get('/create', [PeninjauanController::class, 'create'])
            ->middleware('permission:peninjauan.create')
            ->name('create');

        Route::post('/', [PeninjauanController::class, 'store'])
            ->middleware('permission:peninjauan.create')
            ->name('store');

        Route::get('/{peninjauan}', [PeninjauanController::class, 'show'])
            ->middleware('permission:peninjauan.view')
            ->name('show');

        Route::get('/{peninjauan}/edit', [PeninjauanController::class, 'edit'])
            ->middleware('permission:peninjauan.edit')
            ->name('edit');

        Route::post('/{peninjauan}', [PeninjauanController::class, 'update'])
            ->middleware('permission:peninjauan.edit')
            ->name('update');

        Route::delete('/{peninjauan}', [PeninjauanController::class, 'destroy'])
            ->middleware('permission:peninjauan.delete')
            ->name('destroy');

        Route::get('/{peninjauan}/restore', [PeninjauanController::class, 'restore'])
            ->middleware('permission:peninjauan.delete')
            ->name('restore');

        Route::get('/{peninjauan}/export-pdf', [PeninjauanController::class, 'exportPdf'])
            ->middleware('permission:peninjauan.print')
            ->name('exportPdf');

        Route::post('/update-status/{id}', [PeninjauanController::class, 'updateStatus'])
            ->middleware('permission:peninjauan.update-status')
            ->name('updateStatus');
    });

    // ================================
    // PENERBITAN SKPT ROUTES
    // ================================
    Route::prefix('penerbitan-skpt')->name('penerbitan-skpt.')->group(function () {

        Route::get('/', [PenerbitanSKPTController::class, 'index'])
            ->middleware('permission:penerbitan-skpt.view')
            ->name('index');

        Route::get('/{id}', [PenerbitanSKPTController::class, 'show'])
            ->middleware('permission:penerbitan-skpt.view')
            ->name('show');

        Route::get('/{id}/print', [PenerbitanSKPTController::class, 'printSkpt'])
            ->middleware('permission:penerbitan-skpt.print')
            ->name('print');

        Route::get('/{id}/preview', [PenerbitanSKPTController::class, 'preview'])
            ->middleware('permission:penerbitan-skpt.view')
            ->name('preview');

        Route::post('/{id}/verify', [PenerbitanSKPTController::class, 'verifyDocument'])
            ->middleware('permission:penerbitan-skpt.verify')
            ->name('verify');

        Route::post('/{id}/finalize', [PenerbitanSKPTController::class, 'finalizeDocument'])
            ->middleware('permission:penerbitan-skpt.finalize')
            ->name('finalize');

        Route::get('/{id}/verification-history', [PenerbitanSKPTController::class, 'getVerificationHistory'])
            ->middleware('permission:penerbitan-skpt.view')
            ->name('verification-history');

        Route::patch('/{id}/status', [PenerbitanSKPTController::class, 'updateDocumentStatus'])
            ->middleware('permission:penerbitan-skpt.verify')
            ->name('update-status');
    });

    // ================================
    // PENERBITAN SPMPT ROUTES
    // ================================
    Route::prefix('penerbitan-spmpt')->name('penerbitan-spmpt.')->group(function () {

        Route::get('/', [PenerbitanSpmptController::class, 'index'])
            ->middleware('permission:penerbitan-spmpt.view')
            ->name('index');

        Route::get('/{id}', [PenerbitanSpmptController::class, 'show'])
            ->middleware('permission:penerbitan-spmpt.view')
            ->name('show');

        Route::get('/{id}/print', [PenerbitanSpmptController::class, 'print'])
            ->middleware('permission:penerbitan-spmpt.print')
            ->name('print');

        Route::get('/{id}/preview', [PenerbitanSpmptController::class, 'preview'])
            ->middleware('permission:penerbitan-spmpt.view')
            ->name('preview');

        Route::post('/{id}/verify', [PenerbitanSpmptController::class, 'verifyDocument'])
            ->middleware('permission:penerbitan-spmpt.verify')
            ->name('verify');

        Route::post('/{id}/finalize', [PenerbitanSpmptController::class, 'finalizeDocument'])
            ->middleware('permission:penerbitan-spmpt.finalize')
            ->name('finalize');

        Route::get('/{id}/verification-history', [PenerbitanSpmptController::class, 'getVerificationHistory'])
            ->middleware('permission:penerbitan-spmpt.view')
            ->name('verification-history');

        Route::patch('/{id}/status', [PenerbitanSpmptController::class, 'updateDocumentStatus'])
            ->middleware('permission:penerbitan-spmpt.verify')
            ->name('update-status');
    });

    // ================================
    // USER MANAGEMENT ROUTES (Admin/Superadmin only)
    // ================================
    Route::prefix('users')->name('users.')->group(function () {
        Route::get('/', [UserController::class, 'index'])
            ->middleware('permission:user.view')
            ->name('index');

        Route::get('/create', [UserController::class, 'create'])
            ->middleware('permission:user.create')
            ->name('create');

        Route::post('/', [UserController::class, 'store'])
            ->middleware('permission:user.create')
            ->name('store');

        Route::get('/{user}', [UserController::class, 'show'])
            ->middleware('permission:user.view')
            ->name('show');

        Route::get('/{user}/edit', [UserController::class, 'edit'])
            ->middleware('permission:user.edit')
            ->name('edit');

        Route::put('/{user}', [UserController::class, 'update'])
            ->middleware('permission:user.edit')
            ->name('update');

        Route::delete('/{user}', [UserController::class, 'destroy'])
            ->middleware('permission:user.delete')
            ->name('destroy');
    });

    // ================================
    // USER PROFILE ROUTES (All authenticated users)
    // ================================
    Route::get('user/profile/{user}', [UserController::class, 'showEditProfile'])
        ->name('user.profile');

    Route::put('user/profile/{user}', [UserController::class, 'editProfile'])
        ->name('user.profile.update');

    // ================================
    // ROLE & PERMISSION MANAGEMENT ROUTES (Superadmin only)
    // ================================
    Route::middleware(['role:superadmin'])->prefix('roles')->name('roles.')->group(function () {
        Route::get('/', [RoleController::class, 'index'])->name('index');
        Route::get('/create', [RoleController::class, 'create'])->name('create');
        Route::post('/', [RoleController::class, 'store'])->name('store');
        Route::get('/{role}', [RoleController::class, 'show'])->name('show');
        Route::get('/{role}/edit', [RoleController::class, 'edit'])->name('edit');
        Route::put('/{role}', [RoleController::class, 'update'])->name('update');
        Route::delete('/{role}', [RoleController::class, 'destroy'])->name('destroy');

        // Permission management for role
        Route::get('/{role}/permissions', [RoleController::class, 'permissions'])->name('permissions');
        Route::post('/{role}/permissions', [RoleController::class, 'updatePermissions'])->name('update-permissions');
        Route::put('/{role}/permissions', [RoleController::class, 'syncPermissions'])->name('sync-permissions');
    });

});
