<?php

declare(strict_types=1);

use App\Enums\UserTypes;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Admin\AdminConsoleController;
use App\Http\Controllers\Admin\ApiTokenController;
use App\Http\Controllers\Admin\LandingPageController;
use App\Http\Controllers\Admin\SystemSettingsController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Barangay\BlotterController;
use App\Http\Controllers\Barangay\BlotterHearingController;
use App\Http\Controllers\Barangay\BudgetController;
use App\Http\Controllers\Barangay\ReportsController;
use App\Http\Controllers\Barangay\DocumentRequestController;
use App\Http\Controllers\Barangay\HouseholdController;
use App\Http\Controllers\Barangay\ProjectController;
use App\Http\Controllers\Barangay\RequestTypeController;
use App\Http\Controllers\Barangay\ResidentController;
use App\Http\Controllers\ChapterController;
use App\Http\Controllers\FileController;
use App\Http\Controllers\Payment\QRPHController;
use App\Http\Controllers\PwaManifestController;
use App\Http\Controllers\Support\AnnouncementController;
use App\Http\Controllers\Support\Inertia;
use App\Http\Controllers\Support\SSEController;
use App\Http\Controllers\Support\VueRouteMap;
use App\Models\User;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Redis;
use Hypervel\Support\Facades\Response;
use Hypervel\Support\Facades\Route;

VueRouteMap::registerRoutes();

// ─────────────────────────────────────────────────────────────────────────────
// Health
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/health', function () {
    $checks = [];
    $allOk  = true;

    try {
        \Hypervel\Support\Facades\DB::select('SELECT 1');
        $checks['db'] = 'ok';
    } catch (\Throwable $e) {
        $checks['db'] = 'fail: ' . $e->getMessage();
        $allOk = false;
    }

    try {
        Redis::ping();
        $checks['redis'] = 'ok';
    } catch (\Throwable $e) {
        $checks['redis'] = 'fail: ' . $e->getMessage();
        $allOk = false;
    }

    return $allOk ? 'OK' : response()->json(['status' => 'degraded', 'checks' => $checks], 503);
});

Route::get('/manifest.json', [PwaManifestController::class, 'manifest']);

// ─────────────────────────────────────────────────────────────────────────────
// Auth
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/login', function (\Hypervel\Http\Request $request) {
    if (Auth::check() && !$request->has('logged_out')) return redirect('/');
    $page = Inertia::render('Auth.Login', []);
    return view('layouts.application-layout', compact('page'));
}, ['middleware' => 'web']);

Route::post('/post/loginnow', [LoginController::class, 'authenticate'], ['middleware' => 'web']);
Route::get('/session/extend', [LoginController::class, 'extendcurrentSession'], ['middleware' => 'auth']);

Route::get('/get/isloggedin', function () {
    if (Auth::check()) {
        $user = Auth::user();
        if (!$user || !$user->active) {
            Auth::logout();
            session()?->flush();
            return Response::json(['isloggedin' => false]);
        }
        $hashkey = $user->hashkey ?? null;
        if ($hashkey && Redis::get("forced_logout:{$hashkey}")) {
            Redis::del("forced_logout:{$hashkey}");
            Auth::logout();
            session()?->flush();
            return Response::json(['isloggedin' => false]);
        }
    }
    return Response::json(['isloggedin' => Auth::check()]);
}, ['middleware' => 'web']);

Route::get('/get/user/acct-type', function () {
    return Response::json(['acct_type' => Auth::user()->acct_type]);
}, ['middleware' => 'auth']);

Route::get('/logout', function () {
    Auth::logout();
    session()?->flush();
    return redirect('/login?logged_out=1');
}, ['middleware' => 'auth']);

Route::get('/go/logoutnow', function () {
    Auth::logout();
    session()?->flush();
    return redirect('/login?logged_out=1');
}, ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// SSE
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/sse/stream', [SSEController::class, 'stream'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Home / Dashboard
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/home-data', function () {
    $user = Auth::user();

    $stats = [
        'total_users'        => User::count(),
        'active_users'       => User::where('active', true)->count(),
        'total_residents'    => \Hypervel\Support\Facades\DB::table('barangay_residents')->where('is_active', true)->count(),
        'total_households'   => \Hypervel\Support\Facades\DB::table('barangay_households')->where('is_active', true)->count(),
        'open_blotters'      => \Hypervel\Support\Facades\DB::table('barangay_blotters')->whereIn('status', ['FILED', 'FOR_HEARING'])->count(),
        'pending_documents'  => \Hypervel\Support\Facades\DB::table('barangay_document_requests')->whereIn('status', ['PENDING_PAYMENT', 'PROCESSING'])->count(),
        'total_projects'     => \Hypervel\Support\Facades\DB::table('barangay_projects')->count(),
        'ongoing_projects'   => \Hypervel\Support\Facades\DB::table('barangay_projects')->where('status', 'ONGOING')->count(),
    ];

    return Response::json(['props' => ['user' => $user, 'stats' => $stats]]);
}, ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// File Serving
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/RequestData/File/{hash}', fn (string $hash) => FileController::viewFilebyFileListHash($hash), ['middleware' => 'auth']);
Route::post('/RequestData/File/Upload/{category}', fn (\Hypervel\Http\Request $r, string $category) => FileController::UploadFilefromRequest($r, $category), ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Announcements
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/announcements/latest', [AnnouncementController::class, 'latest']);
Route::get('/announcements', [AnnouncementController::class, 'index'], ['middleware' => 'auth']);
Route::post('/announcements/create', [AnnouncementController::class, 'store'], ['middleware' => 'auth']);
Route::post('/announcements/update', [AnnouncementController::class, 'update'], ['middleware' => 'auth']);
Route::post('/announcements/delete', [AnnouncementController::class, 'destroy'], ['middleware' => 'auth']);
Route::post('/announcements/toggle', [AnnouncementController::class, 'toggleStatus'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// System Settings
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/admin/settings', [SystemSettingsController::class, 'index'], ['middleware' => 'auth']);
Route::post('/admin/settings/update', [SystemSettingsController::class, 'update'], ['middleware' => 'auth']);
Route::post('/admin/settings/logo/upload', [SystemSettingsController::class, 'uploadLogo'], ['middleware' => 'auth']);
Route::get('/admin/settings/public', [SystemSettingsController::class, 'publicSettings']);

// ─────────────────────────────────────────────────────────────────────────────
// Landing Pages
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/admin/landing-pages', [LandingPageController::class, 'index'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/create', [LandingPageController::class, 'store'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/update', [LandingPageController::class, 'update'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/activate', [LandingPageController::class, 'activate'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/delete', [LandingPageController::class, 'destroy'], ['middleware' => 'auth']);
Route::get('/public/landing-page', [LandingPageController::class, 'active']);

// ─────────────────────────────────────────────────────────────────────────────
// Admin Console
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/admin/console/stats', [AdminConsoleController::class, 'getSystemStats'], ['middleware' => 'auth']);
Route::get('/admin/console/logs', [AdminConsoleController::class, 'getLogs'], ['middleware' => 'auth']);
Route::get('/admin/console/table-logs', [AdminConsoleController::class, 'getTableLogs'], ['middleware' => 'auth']);
Route::post('/admin/console/query', [AdminConsoleController::class, 'runQuery'], ['middleware' => 'auth']);
Route::post('/admin/console/maintenance', [AdminConsoleController::class, 'setMaintenanceMode'], ['middleware' => 'auth']);
Route::post('/admin/console/message', [AdminConsoleController::class, 'setGlobalMessage'], ['middleware' => 'auth']);
Route::post('/admin/console/cache/clear', [AdminConsoleController::class, 'clearCache'], ['middleware' => 'auth']);
Route::post('/admin/console/backup', [AdminConsoleController::class, 'backupDatabase'], ['middleware' => 'auth']);
Route::get('/admin/console/backups', [AdminConsoleController::class, 'listBackups'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// API Tokens
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/admin/tokens', [ApiTokenController::class, 'index'], ['middleware' => 'auth']);
Route::get('/admin/tokens/catalog', [ApiTokenController::class, 'catalog'], ['middleware' => 'auth']);
Route::post('/admin/tokens/create', [ApiTokenController::class, 'store'], ['middleware' => 'auth']);
Route::post('/admin/tokens/revoke', [ApiTokenController::class, 'revoke'], ['middleware' => 'auth']);
Route::post('/admin/tokens/delete', [ApiTokenController::class, 'destroy'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// User Management
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/admin/users', [UserController::class, 'index'], ['middleware' => 'auth']);
Route::post('/admin/users/show', [UserController::class, 'show'], ['middleware' => 'auth']);
Route::post('/admin/users/create', [UserController::class, 'store'], ['middleware' => 'auth']);
Route::post('/admin/users/update', [UserController::class, 'update'], ['middleware' => 'auth']);
Route::post('/admin/users/set-active', [UserController::class, 'setActive'], ['middleware' => 'auth']);
Route::post('/admin/users/change-password', [UserController::class, 'changePassword'], ['middleware' => 'auth']);
Route::post('/admin/users/force-logout', [UserController::class, 'forceLogout'], ['middleware' => 'auth']);
Route::get('/admin/users/account-types', [UserController::class, 'accountTypes'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Chapters / Geography Hierarchy
// ─────────────────────────────────────────────────────────────────────────────

Route::post('/Chapters/Hierarchy', [ChapterController::class, 'hierarchy'], ['middleware' => 'auth']);
Route::post('/Chapters/MapData', [ChapterController::class, 'mapData'], ['middleware' => 'auth']);
Route::post('/Chapters/Members', [ChapterController::class, 'members'], ['middleware' => 'auth']);
Route::post('/Chapters/Member/Assign', [ChapterController::class, 'assignMember'], ['middleware' => 'auth']);
Route::post('/Chapters/Member/Remove', [ChapterController::class, 'removeMember'], ['middleware' => 'auth']);
Route::get('/Chapters/Positions', [ChapterController::class, 'positions'], ['middleware' => 'auth']);
Route::post('/Chapters/Create', [ChapterController::class, 'createChapter'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// QR PH Payment
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/payment/qrph', [QRPHController::class, 'getQrCode'], ['middleware' => 'auth']);
Route::post('/payment/qrph/set', [QRPHController::class, 'setQrCode'], ['middleware' => 'auth']);
Route::post('/payment/qrph/decode', [QRPHController::class, 'decode'], ['middleware' => 'auth']);
Route::post('/payment/qrph/remove', [QRPHController::class, 'removeQrCode'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Document Request Types
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/request-types', [RequestTypeController::class, 'active']);
Route::get('/admin/request-types', [RequestTypeController::class, 'index'], ['middleware' => 'auth']);
Route::post('/admin/request-types/create', [RequestTypeController::class, 'store'], ['middleware' => 'auth']);
Route::post('/admin/request-types/update', [RequestTypeController::class, 'update'], ['middleware' => 'auth']);
Route::post('/admin/request-types/toggle', [RequestTypeController::class, 'toggleActive'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Document Requests
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/documents/my', [DocumentRequestController::class, 'myRequests'], ['middleware' => 'auth']);
Route::post('/documents/submit', [DocumentRequestController::class, 'store'], ['middleware' => 'auth']);
Route::post('/documents/cancel', [DocumentRequestController::class, 'cancel'], ['middleware' => 'auth']);
Route::get('/admin/documents', [DocumentRequestController::class, 'index'], ['middleware' => 'auth']);
Route::post('/admin/documents/show', [DocumentRequestController::class, 'show'], ['middleware' => 'auth']);
Route::post('/admin/documents/status', [DocumentRequestController::class, 'updateStatus'], ['middleware' => 'auth']);
Route::post('/admin/documents/confirm-payment', [DocumentRequestController::class, 'confirmPayment'], ['middleware' => 'auth']);
Route::post('/admin/documents/mark-ready', [DocumentRequestController::class, 'markReady'], ['middleware' => 'auth']);
Route::post('/admin/documents/mark-claimed', [DocumentRequestController::class, 'markClaimed'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Residents
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/residents', [ResidentController::class, 'index'], ['middleware' => 'auth']);
Route::post('/residents/show', [ResidentController::class, 'show'], ['middleware' => 'auth']);
Route::post('/residents/create', [ResidentController::class, 'store'], ['middleware' => 'auth']);
Route::post('/residents/update', [ResidentController::class, 'update'], ['middleware' => 'auth']);
Route::post('/residents/set-active', [ResidentController::class, 'setActive'], ['middleware' => 'auth']);
Route::get('/residents/search', [ResidentController::class, 'search'], ['middleware' => 'auth']);
Route::get('/residents/puroks', [ResidentController::class, 'puroks'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Households
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/households', [HouseholdController::class, 'index'], ['middleware' => 'auth']);
Route::post('/households/show', [HouseholdController::class, 'show'], ['middleware' => 'auth']);
Route::post('/households/create', [HouseholdController::class, 'store'], ['middleware' => 'auth']);
Route::post('/households/update', [HouseholdController::class, 'update'], ['middleware' => 'auth']);
Route::post('/households/members/add', [HouseholdController::class, 'addMember'], ['middleware' => 'auth']);
Route::post('/households/members/remove', [HouseholdController::class, 'removeMember'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Blotters
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/blotters', [BlotterController::class, 'index'], ['middleware' => 'auth']);
Route::post('/blotters/show', [BlotterController::class, 'show'], ['middleware' => 'auth']);
Route::post('/blotters/create', [BlotterController::class, 'store'], ['middleware' => 'auth']);
Route::post('/blotters/status', [BlotterController::class, 'updateStatus'], ['middleware' => 'auth']);
Route::post('/blotters/assign-officer', [BlotterController::class, 'assignOfficer'], ['middleware' => 'auth']);
Route::get('/blotters/status-options', [BlotterController::class, 'statusOptions'], ['middleware' => 'auth']);
Route::post('/blotters/hearings', [BlotterHearingController::class, 'index'], ['middleware' => 'auth']);
Route::post('/blotters/hearings/schedule', [BlotterHearingController::class, 'schedule'], ['middleware' => 'auth']);
Route::post('/blotters/hearings/update', [BlotterHearingController::class, 'update'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Projects
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/projects', [ProjectController::class, 'index'], ['middleware' => 'auth']);
Route::post('/projects/show', [ProjectController::class, 'show'], ['middleware' => 'auth']);
Route::post('/projects/create', [ProjectController::class, 'store'], ['middleware' => 'auth']);
Route::post('/projects/update', [ProjectController::class, 'update'], ['middleware' => 'auth']);
Route::post('/projects/status', [ProjectController::class, 'updateStatus'], ['middleware' => 'auth']);
Route::get('/projects/summary', [ProjectController::class, 'summary'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Budget & Finance
// ─────────────────────────────────────────────────────────────────────────────

Route::get('/budget', [BudgetController::class, 'index'], ['middleware' => 'auth']);
Route::get('/budget/summary', [BudgetController::class, 'summary'], ['middleware' => 'auth']);
Route::get('/budget/fiscal-years', [BudgetController::class, 'fiscalYears'], ['middleware' => 'auth']);
Route::post('/budget/create', [BudgetController::class, 'store'], ['middleware' => 'auth']);
Route::post('/budget/update', [BudgetController::class, 'update'], ['middleware' => 'auth']);
Route::post('/budget/delete', [BudgetController::class, 'destroy'], ['middleware' => 'auth']);

// ─────────────────────────────────────────────────────────────────────────────
// Reports
// ─────────────────────────────────────────────────────────────────────────────

Route::post('/reports/generate', [ReportsController::class, 'generate'], ['middleware' => 'auth']);
