<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once __DIR__ . '/app/config/config.php';
    require_once __DIR__ . '/app/includes/session.php';
    require_once __DIR__ . '/app/includes/db_connect.php';

    if (!isset($pdo) || !$pdo instanceof PDO) {
        http_response_code(503);
        $errorMessage = "Kesalahan Kritis: Tidak dapat terhubung ke database.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $errorMessage .= " Periksa detail koneksi di 'app/config/database.php', pastikan server database berjalan, dan cek log error PHP."; }
        echo "<!DOCTYPE html><html><head><title>Database Error</title><style>body{font-family:sans-serif; background-color:#f8d7da; color:#721c24; padding:20px;}</style></head><body><h1>Kesalahan Koneksi Database</h1><p>" . htmlspecialchars($errorMessage) . "</p><p><i>Silakan periksa file log error PHP server Anda untuk detail lebih lanjut.</i></p></body></html>";
        exit;
    }

    $appSettings = [];
    try {
        $stmtSettings = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('app_name', 'app_logo', 'gemini_api_key')");
        $dbSettings = $stmtSettings->fetchAll(PDO::FETCH_KEY_PAIR);
        $appSettings['app_name'] = $dbSettings['app_name'] ?? 'SMM Panel';
        $appSettings['app_logo'] = $dbSettings['app_logo'] ?? null;
        $appSettings['gemini_api_key'] = $dbSettings['gemini_api_key'] ?? null;

        if (!empty($appSettings['app_logo']) && !filter_var($appSettings['app_logo'], FILTER_VALIDATE_URL)) {
             $appSettings['app_logo_url'] = base_url('uploads/logo/' . $appSettings['app_logo']);
        } else {
             $appSettings['app_logo_url'] = $appSettings['app_logo'];
        }
    } catch (\PDOException $e) {
        error_log("Error fetching global settings: " . $e->getMessage());
        $appSettings['app_name'] = 'SMM Panel Error';
        $appSettings['app_logo'] = null;
        $appSettings['app_logo_url'] = null;
        $appSettings['gemini_api_key'] = null;
    }
    require_once __DIR__ . '/app/lib/Auth.php';
    require_once __DIR__ . '/app/includes/functions.php';

    $basePath = parse_url(BASE_URL, PHP_URL_PATH);
    $requestUri = $_SERVER['REQUEST_URI'];
    $requestPath = '/';
    if (($queryStringPos = strpos($requestUri, '?')) !== false) {
        $requestUri = substr($requestUri, 0, $queryStringPos);
    }
    if ($basePath && $basePath !== '/' && strpos($requestUri, $basePath) === 0) {
        $requestPath = substr($requestUri, strlen($basePath));
    } elseif ($requestUri !== '/') {
        $requestPath = $requestUri;
    }
    $requestPath = trim($requestPath, '/');
    if (empty($requestPath)) {
        $requestPath = '/';
    }
    $route = $requestPath;
    $requestMethod = $_SERVER['REQUEST_METHOD'];

    if ($route === 'payment/callback/paydisini') {
        require_once APP_DIR . '/callbacks/paydisini_handler.php';
        exit;
    }

    $cronScript = $_GET['cron'] ?? null;
    if ($cronScript) {
        if (!isset($pdo) || !$pdo instanceof PDO) { die("Error: Koneksi DB tidak tersedia untuk script cron."); }
        if (preg_match('/^[a-zA-Z0-9_-]+$/', $cronScript)) {
            $cronFile = APP_DIR . '/cron/' . $cronScript . '.php';
            if (file_exists($cronFile)) {
                header('Content-Type: text/html; charset=utf-8');
                echo "<!DOCTYPE html><html><head><title>Cron Runner: " . htmlspecialchars($cronScript) . "</title>";
                echo "<style>body { font-family: sans-serif; background-color: #f4f4f4; margin: 0; padding: 15px; } pre { background-color: #fff; border: 1px solid #ccc; padding: 10px; white-space: pre-wrap; word-wrap: break-word; }</style>";
                echo "</head><body>";
                echo "<h2>Menjalankan Script: " . htmlspecialchars($cronScript) . "</h2>";
                require_once $cronFile;
                echo "<hr><p>Eksekusi Selesai.</p>";
                echo "</body></html>";
            } else {
                http_response_code(404);
                echo "Error: Script cron '<code>" . htmlspecialchars($cronScript) . "</code>' tidak ditemukan.";
            }
        } else {
            http_response_code(400);
            echo "Error: Nama script cron tidak valid.";
        }
        exit;
    }

    if ($route === '/' && !Auth::isLoggedIn()) { redirect(base_url('login')); }
    if ($route === '/' && Auth::isLoggedIn()) { redirect(base_url('dashboard')); }

    // Definisi Handler AJAX
    $ajaxLoginHandler = HANDLER_DIR . '/ajax/login_handler.php';
    $ajaxRegisterHandler = HANDLER_DIR . '/ajax/register_handler.php';
    $ajaxGetCategoriesHandler = HANDLER_DIR . '/ajax/get_categories.php';
    $ajaxGetServicesHandler = HANDLER_DIR . '/ajax/get_services_by_category.php';
    $ajaxGetServiceDetailsHandler = HANDLER_DIR . '/ajax/get_service_details.php';
    $ajaxPlaceOrderHandler = HANDLER_DIR . '/ajax/place_order.php';
    $ajaxGetOrderHistoryHandler = HANDLER_DIR . '/ajax/get_order_history.php';
    $ajaxGetOrderReportHandler = HANDLER_DIR . '/ajax/get_order_report.php';
    $ajaxGetServicesListHandler = HANDLER_DIR . '/ajax/get_services_list.php';
    $ajaxGetDepositMethodsHandler = HANDLER_DIR . '/ajax/get_deposit_methods.php';
    $ajaxRequestDepositHandler = HANDLER_DIR . '/ajax/request_deposit.php';
    $ajaxGetDepositHistoryHandler = HANDLER_DIR . '/ajax/get_deposit_history.php';
    $ajaxGetDepositReportHandler = HANDLER_DIR . '/ajax/get_deposit_report.php';
    $ajaxGetDepositStatusHandler = HANDLER_DIR . '/ajax/get_status_deposit.php';
    $ajaxGetBalanceHistoryHandler = HANDLER_DIR . '/ajax/get_balance_history.php';
    $ajaxGetTicketsListHandler = HANDLER_DIR . '/ajax/get_tickets_list.php';
    $ajaxCreateTicketHandler = HANDLER_DIR . '/ajax/create_ticket.php';
    $ajaxGetTicketDetailsHandler = HANDLER_DIR . '/ajax/get_ticket_details.php';
    $ajaxReplyTicketHandler = HANDLER_DIR . '/ajax/reply_ticket.php';
    $ajaxCloseTicketHandler = HANDLER_DIR . '/ajax/close_ticket.php';
    $ajaxUpdateProfileSettingsHandler = HANDLER_DIR . '/ajax/update_profile_settings.php';
    $ajaxGetLatestInformationHandler = HANDLER_DIR . '/ajax/get_latest_information.php';
    $ajaxGetAdminUsersHandler = HANDLER_DIR . '/ajax/get_admin_users.php';
    $ajaxAdminDeleteUserHandler = HANDLER_DIR . '/ajax/admin/delete_user.php';
    $ajaxAdminUpdateUserHandler = HANDLER_DIR . '/ajax/admin/update_user.php';
    $ajaxAdminAddUserHandler = HANDLER_DIR . '/ajax/admin/add_user.php';
    $ajaxAdminLoginAsUserHandler = HANDLER_DIR . '/ajax/admin/login_as_user.php';
    $ajaxAdminGetOrdersHandler = HANDLER_DIR . '/ajax/admin/get_admin_orders.php';
    $ajaxAdminUpdateOrderHandler = HANDLER_DIR . '/ajax/admin/update_order.php';
    $ajaxAdminGetInformationsHandler = HANDLER_DIR . '/ajax/admin/get_admin_informations.php';
    $ajaxAdminAddInformationHandler = HANDLER_DIR . '/ajax/admin/add_information.php';
    $ajaxAdminUpdateInformationHandler = HANDLER_DIR . '/ajax/admin/update_information.php';
    $ajaxAdminDeleteInformationHandler = HANDLER_DIR . '/ajax/admin/delete_information.php';
    $ajaxAdminGetTicketsHandler = HANDLER_DIR . '/ajax/admin/get_admin_tickets.php';
    $ajaxAdminGetCategoriesHandler = HANDLER_DIR . '/ajax/admin/get_admin_categories.php';
    $ajaxAdminAddCategoryHandler = HANDLER_DIR . '/ajax/admin/add_category.php';
    $ajaxAdminUpdateCategoryHandler = HANDLER_DIR . '/ajax/admin/update_category.php';
    $ajaxAdminDeleteCategoryHandler = HANDLER_DIR . '/ajax/admin/delete_category.php';
    $ajaxAdminGetServicesHandler = HANDLER_DIR . '/ajax/admin/get_admin_services.php';
    $ajaxAdminAddServiceHandler = HANDLER_DIR . '/ajax/admin/add_service.php';
    $ajaxAdminUpdateServiceHandler = HANDLER_DIR . '/ajax/admin/update_service.php';
    $ajaxAdminDeleteServiceHandler = HANDLER_DIR . '/ajax/admin/delete_service.php';
    $ajaxAdminGetWebsiteSettingsHandler = HANDLER_DIR . '/ajax/admin/get_website_settings.php';
    $ajaxAdminUpdateWebsiteSettingsHandler = HANDLER_DIR . '/ajax/admin/update_website_settings.php';
    $ajaxAdminGetProvidersHandler = HANDLER_DIR . '/ajax/admin/get_admin_providers.php';
    $ajaxAdminAddProviderHandler = HANDLER_DIR . '/ajax/admin/add_provider.php';
    $ajaxAdminUpdateProviderHandler = HANDLER_DIR . '/ajax/admin/update_provider.php';
    $ajaxAdminDeleteProviderHandler = HANDLER_DIR . '/ajax/admin/delete_provider.php';
    $ajaxAdminGetDepositsHandler = HANDLER_DIR . '/ajax/admin/get_admin_deposits.php';
    $ajaxAdminUpdateDepositHandler = HANDLER_DIR . '/ajax/admin/update_deposit.php';
    $ajaxAdminGetBalanceLogsHandler = HANDLER_DIR . '/ajax/admin/get_admin_balance_logs.php';
    $ajaxAdminGetLoginLogsHandler = HANDLER_DIR . '/ajax/admin/get_admin_login_logs.php'; // Handler baru
    $ajaxGetAiResponseHandler = HANDLER_DIR . '/ajax/get_ai_response.php';
    $ajaxValidateUserOrderHandler = HANDLER_DIR . '/ajax/validate_user_order.php';
    $ajaxCreateTicketFromChatHandler = HANDLER_DIR . '/ajax/create_ticket_from_chat.php';
    $apiHandlerPath = HANDLER_DIR . '/api.php';


    if (strpos($route, 'ajax/') === 0) {
        if (!isset($pdo) || !$pdo instanceof PDO) {
            http_response_code(503);
            echo json_encode(['success'=>false,'errors'=>['general'=>'Koneksi DB tidak tersedia.']]);
            exit;
        }
        $handlerPath = null;
        $isAdminAjaxRoute = strpos($route, 'ajax/admin/') === 0;

        if ($isAdminAjaxRoute && (!Auth::isLoggedIn() || ($_SESSION['user_role'] !== 'admin' && !isset($_SESSION['original_admin_id'])))) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Akses ditolak. Hanya admin.']);
            exit;
        }

        if ($requestMethod === 'POST') {
            if ($route === 'ajax/login') { $handlerPath = $ajaxLoginHandler; }
            elseif ($route === 'ajax/register') { $handlerPath = $ajaxRegisterHandler; }
            elseif ($route === 'ajax/place_order') { $handlerPath = $ajaxPlaceOrderHandler; }
            elseif ($route === 'ajax/request_deposit') { $handlerPath = $ajaxRequestDepositHandler; }
            elseif ($route === 'ajax/create_ticket') { $handlerPath = $ajaxCreateTicketHandler; }
            elseif ($route === 'ajax/reply_ticket') { $handlerPath = $ajaxReplyTicketHandler; }
            elseif ($route === 'ajax/close_ticket') { $handlerPath = $ajaxCloseTicketHandler; }
            elseif ($route === 'ajax/update_profile_settings') { $handlerPath = $ajaxUpdateProfileSettingsHandler; }
            elseif ($route === 'ajax/admin/delete_user') { $handlerPath = $ajaxAdminDeleteUserHandler; }
            elseif ($route === 'ajax/admin/update_user') { $handlerPath = $ajaxAdminUpdateUserHandler; }
            elseif ($route === 'ajax/admin/add_user') { $handlerPath = $ajaxAdminAddUserHandler; }
            elseif ($route === 'ajax/admin/login_as_user') { $handlerPath = $ajaxAdminLoginAsUserHandler; }
            elseif ($route === 'ajax/admin/update_order') { $handlerPath = $ajaxAdminUpdateOrderHandler; }
            elseif ($route === 'ajax/admin/add_information') { $handlerPath = $ajaxAdminAddInformationHandler; }
            elseif ($route === 'ajax/admin/update_information') { $handlerPath = $ajaxAdminUpdateInformationHandler; }
            elseif ($route === 'ajax/admin/delete_information') { $handlerPath = $ajaxAdminDeleteInformationHandler; }
            elseif ($route === 'ajax/admin/add_category') { $handlerPath = $ajaxAdminAddCategoryHandler; }
            elseif ($route === 'ajax/admin/update_category') { $handlerPath = $ajaxAdminUpdateCategoryHandler; }
            elseif ($route === 'ajax/admin/delete_category') { $handlerPath = $ajaxAdminDeleteCategoryHandler; }
            elseif ($route === 'ajax/admin/add_service') { $handlerPath = $ajaxAdminAddServiceHandler; }
            elseif ($route === 'ajax/admin/update_service') { $handlerPath = $ajaxAdminUpdateServiceHandler; }
            elseif ($route === 'ajax/admin/delete_service') { $handlerPath = $ajaxAdminDeleteServiceHandler; }
            elseif ($route === 'ajax/admin/update_website_settings') { $handlerPath = $ajaxAdminUpdateWebsiteSettingsHandler; }
            elseif ($route === 'ajax/admin/add_provider') { $handlerPath = $ajaxAdminAddProviderHandler; }
            elseif ($route === 'ajax/admin/update_provider') { $handlerPath = $ajaxAdminUpdateProviderHandler; }
            elseif ($route === 'ajax/admin/delete_provider') { $handlerPath = $ajaxAdminDeleteProviderHandler; }
            elseif ($route === 'ajax/admin/update_deposit') { $handlerPath = $ajaxAdminUpdateDepositHandler; }
            elseif ($route === 'ajax/create_ticket_from_chat') { $handlerPath = $ajaxCreateTicketFromChatHandler; }
            elseif ($route === 'ajax/get_ai_response') { $handlerPath = $ajaxGetAiResponseHandler; }


        } elseif ($requestMethod === 'GET') {
            if ($route === 'ajax/get_categories') { $handlerPath = $ajaxGetCategoriesHandler; }
            elseif ($route === 'ajax/get_services_by_category') { $handlerPath = $ajaxGetServicesHandler; }
            elseif ($route === 'ajax/get_service_details') { $handlerPath = $ajaxGetServiceDetailsHandler; }
            elseif ($route === 'ajax/get_order_history') { $handlerPath = $ajaxGetOrderHistoryHandler; }
            elseif ($route === 'ajax/get_order_report') { $handlerPath = $ajaxGetOrderReportHandler; }
            elseif ($route === 'ajax/get_services_list') { $handlerPath = $ajaxGetServicesListHandler; }
            elseif ($route === 'ajax/get_deposit_methods') { $handlerPath = $ajaxGetDepositMethodsHandler; }
            elseif ($route === 'ajax/get_deposit_history') { $handlerPath = $ajaxGetDepositHistoryHandler; }
            elseif ($route === 'ajax/get_deposit_report') { $handlerPath = $ajaxGetDepositReportHandler; }
            elseif ($route === 'ajax/get_deposit_status') { $handlerPath = $ajaxGetDepositStatusHandler; }
            elseif ($route === 'ajax/get_balance_history') { $handlerPath = $ajaxGetBalanceHistoryHandler; }
            elseif ($route === 'ajax/get_latest_information') { $handlerPath = $ajaxGetLatestInformationHandler; }
            elseif ($route === 'ajax/get_tickets_list') { $handlerPath = $ajaxGetTicketsListHandler; }
            elseif ($route === 'ajax/get_ticket_details') { $handlerPath = $ajaxGetTicketDetailsHandler; }
            elseif ($route === 'ajax/validate_user_order') { $handlerPath = $ajaxValidateUserOrderHandler; }
            elseif ($route === 'ajax/get_admin_users') { $handlerPath = $ajaxGetAdminUsersHandler; }
            elseif ($route === 'ajax/admin/get_admin_orders') { $handlerPath = $ajaxAdminGetOrdersHandler; }
            elseif ($route === 'ajax/admin/get_admin_informations') { $handlerPath = $ajaxAdminGetInformationsHandler; }
            elseif ($route === 'ajax/admin/get_admin_tickets') { $handlerPath = $ajaxAdminGetTicketsHandler; }
            elseif ($route === 'ajax/admin/get_admin_categories') { $handlerPath = $ajaxAdminGetCategoriesHandler; }
            elseif ($route === 'ajax/admin/get_admin_services') { $handlerPath = $ajaxAdminGetServicesHandler; }
            elseif ($route === 'ajax/admin/get_website_settings') { $handlerPath = $ajaxAdminGetWebsiteSettingsHandler; }
            elseif ($route === 'ajax/admin/get_admin_providers') { $handlerPath = $ajaxAdminGetProvidersHandler; }
            elseif ($route === 'ajax/admin/get_admin_deposits') { $handlerPath = $ajaxAdminGetDepositsHandler; }
            elseif ($route === 'ajax/admin/get_admin_balance_logs') { $handlerPath = $ajaxAdminGetBalanceLogsHandler; }
            elseif ($route === 'ajax/admin/get_admin_login_logs') { $handlerPath = $ajaxAdminGetLoginLogsHandler; } // Rute baru
        }

        if ($handlerPath && file_exists($handlerPath)) {
            require_once $handlerPath;
        } else {
            error_log("AJAX Handler Not Found. Route: '{$route}', Method: '{$requestMethod}', Calculated Path: '{$handlerPath}'");
            header('Content-Type: application/json');
            http_response_code(404);
            echo json_encode(['success' => false, 'errors' => ['general' => 'AJAX endpoint not found.'], 'debug_route' => $route, 'debug_path' => $handlerPath]);
        }
        exit;
    }

    elseif (strpos($route, 'api/v1/') === 0) {
        if (file_exists($apiHandlerPath)) {
            require_once $apiHandlerPath;
        } else {
            header('Content-Type: application/json');
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'API handler tidak ditemukan.']);
        }
        exit;
    }

    if ($route === 'return_to_admin') {
        if (Auth::isLoggedIn() && isset($_SESSION['is_impersonating']) && $_SESSION['is_impersonating'] === true && isset($_SESSION['original_admin_id'])) {
            $originalAdminId = $_SESSION['original_admin_id'];
            log_login_activity($pdo, $originalAdminId, $_SESSION['original_admin_username'] ?? 'admin_user', 'admin_impersonate_end'); // Log akhir impersonasi

            session_unset();
            session_destroy();
            session_start();
            session_regenerate_id(true);

            $auth = new Auth($pdo);
            $adminUser = $auth->getUserById($originalAdminId);
            if ($adminUser) {
                $_SESSION['user_id'] = $adminUser['id'];
                $_SESSION['username'] = $adminUser['username'];
                $_SESSION['user_role'] = $adminUser['role'];
                $_SESSION['user_email'] = $adminUser['email'];
                $_SESSION['user_fullname'] = $adminUser['full_name'];
                $_SESSION['user_phone'] = $adminUser['phone_number'];
                $_SESSION['is_logged_in'] = true;
            } else {
                Auth::logout();
                redirect(base_url('login?error=admin_recovery_failed'));
            }
        } else {
            redirect(base_url('dashboard'));
        }
        redirect(base_url('admin/users'));
        exit;
    }

    if ($route === 'logout') { Auth::logout(); redirect(base_url('login')); }

    $layoutFile = TEMPLATE_DIR . '/layouts/main.php';
    $contentView = null;
    $pageTitle = $appSettings['app_name'] ?? 'SMM Panel';
    $isAdminPage = false;

    // Variabel-variabel untuk halaman (bisa di-override oleh halaman spesifik)
    $searchQuery = ''; $statusFilter = 'all'; $limit = 10;
    $statusOptions = [ 'all' => 'Semua Status', 'pending' => 'Pending', 'processing' => 'Processing', 'in progress' => 'In Progress', 'success' => 'Success', 'error' => 'Error', 'partial' => 'Partial', 'canceled' => 'Canceled', ];
    $sortColumnOptions = ['o.created_at' => 'Tanggal', 'o.id' => 'ID Pesanan', 's.name' => 'Layanan', 'o.price' => 'Harga', 'o.quantity' => 'Jumlah', 'o.status' => 'Status'];
    $sortTypeOptions = ['DESC' => 'Terbaru/Tertinggi', 'ASC' => 'Terlama/Terendah'];
    $searchColumnOptions = ['o.id' => 'ID Pesanan', 'o.target' => 'Target', 's.name' => 'Nama Layanan'];
    $serviceSortColumnOptions = ['s.name' => 'Nama Layanan', 's.price_per_1000' => 'Harga', 'c.name' => 'Kategori', 's.id' => 'ID Layanan'];
    $serviceSortTypeOptions = ['ASC' => 'A-Z / Termurah', 'DESC' => 'Z-A / Termahal'];
    $paymentTypes = [ 'virtual_account' => 'Virtual Account', 'e_wallet' => 'E-Wallet', 'bank_transfer' => 'Transfer Bank', 'retail_outlet' => 'Gerai Retail', 'pulsa' => 'Pulsa Transfer' ];
    $userBalance = 0;
    $ticketId = null;
    $depositUniqueCode = null;
    $deposit = null;

    if (Auth::isLoggedIn() && isset($_SESSION['user_id'])) {
        try {
            $stmtBal = $pdo->prepare("SELECT balance FROM users WHERE id = :uid");
            $stmtBal->bindParam(':uid', $_SESSION['user_id'], PDO::PARAM_INT);
            $stmtBal->execute();
            $userBalance = $stmtBal->fetchColumn();
            if ($userBalance === false) $userBalance = 0;
        } catch (\PDOException $e) { error_log("Error fetching user balance in index.php: " . $e->getMessage()); $userBalance = 0; }
    }

    function requireAdmin() {
        if (!Auth::isLoggedIn() || ($_SESSION['user_role'] !== 'admin' && !isset($_SESSION['original_admin_id']))) {
            redirect(base_url('dashboard?error=forbidden'));
        }
    }

    if ($requestMethod === 'GET') {
        if (preg_match('#^deposit/invoice/([a-zA-Z0-9\-]+)$#', $route, $matches)) {
            if (!Auth::isLoggedIn()) { redirect(base_url('login')); }
            $depositUniqueCode = $matches[1];
            $depositData = null;
            try {
                $stmtDep = $pdo->prepare("
                    SELECT d.*, dm.name as method_name, dm.logo_url as method_logo, dm.type as method_type
                    FROM deposits d
                    JOIN deposit_methods dm ON d.deposit_method_id = dm.id
                    WHERE d.paydisini_unique_code = :unique_code AND d.user_id = :user_id
                    LIMIT 1
                ");
                $stmtDep->bindParam(':unique_code', $depositUniqueCode);
                $stmtDep->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
                $stmtDep->execute();
                $depositData = $stmtDep->fetch(PDO::FETCH_ASSOC);

                if ($depositData && !empty($depositData['payment_details'])) {
                     $depositData['payment_details_array'] = json_decode($depositData['payment_details'], true);
                     if (json_last_error() !== JSON_ERROR_NONE) {
                         $depositData['payment_details_array'] = null;
                         error_log("JSON Decode Error for deposit details, ID: " . $depositData['id']);
                     }
                 } elseif ($depositData) {
                      $depositData['payment_details_array'] = null;
                 }

            } catch (\PDOException $e) {
                error_log("Error fetching deposit invoice data: " . $e->getMessage());
            }

            if ($depositData) {
                $pageTitle = 'Invoice Deposit #' . htmlspecialchars($depositData['deposit_id']);
                $layoutFile = TEMPLATE_DIR . '/layouts/admin.php';
                $contentView = TEMPLATE_DIR . '/deposit/invoice.php';
                $deposit = $depositData;
            } else {
                 set_flash_message('deposit_history_error', 'Invoice deposit tidak ditemukan atau bukan milik Anda.', 'error');
                 redirect(base_url('deposit/history'));
            }
        }
        elseif (preg_match('#^tickets/view/([a-zA-Z0-9\-]+)$#', $route, $matches)) {
            if (!Auth::isLoggedIn()) { redirect(base_url('login')); }
            $ticketId = $matches[1];
            $pageTitle = 'Lihat Tiket';
            $layoutFile = TEMPLATE_DIR . '/layouts/admin.php';
            $contentView = TEMPLATE_DIR . '/tickets/view.php';
        }

        elseif ($route === 'api-docs') {
            if (!Auth::isLoggedIn()) { redirect(base_url('login')); }
            $pageTitle = 'Dokumentasi API';
            $layoutFile = TEMPLATE_DIR . '/layouts/admin.php';
            $contentView = TEMPLATE_DIR . '/api_docs.php';
        }

        elseif (strpos($route, 'admin/') === 0) {
            requireAdmin();
            $isAdminPage = true;
            $layoutFile = TEMPLATE_DIR . '/layouts/admin.php';

            $adminRoute = substr($route, strlen('admin/'));
            switch ($adminRoute) {
                case 'dashboard': $pageTitle = 'Admin Dashboard'; $contentView = TEMPLATE_DIR . '/admin/dashboard.php'; break;
                case 'users': $pageTitle = 'Kelola Pengguna'; $contentView = TEMPLATE_DIR . '/admin/manage_users.php'; break;
                case 'orders': $pageTitle = 'Kelola Pesanan'; $contentView = TEMPLATE_DIR . '/admin/manage_orders.php'; break;
                case 'deposits': $pageTitle = 'Kelola Deposit'; $contentView = TEMPLATE_DIR . '/admin/manage_deposits.php'; break;
                case 'balance-logs': $pageTitle = 'Mutasi Saldo'; $contentView = TEMPLATE_DIR . '/admin/manage_balance_logs.php'; break;
                case 'login-logs': $pageTitle = 'Log Masuk'; $contentView = TEMPLATE_DIR . '/admin/manage_login_logs.php'; break; // Rute baru
                case 'informations': $pageTitle = 'Kelola Informasi'; $contentView = TEMPLATE_DIR . '/admin/manage_informations.php'; break;
                case 'tickets': $pageTitle = 'Kelola Tiket'; $contentView = TEMPLATE_DIR . '/admin/manage_tickets.php'; break;
                case 'categories': $pageTitle = 'Kelola Kategori'; $contentView = TEMPLATE_DIR . '/admin/manage_categories.php'; break;
                case 'services': $pageTitle = 'Kelola Layanan'; $contentView = TEMPLATE_DIR . '/admin/manage_services.php'; break;
                case 'settings': $pageTitle = 'Pengaturan Website'; $contentView = TEMPLATE_DIR . '/admin/settings.php'; break;
                case 'providers': $pageTitle = 'Kelola Provider'; $contentView = TEMPLATE_DIR . '/admin/manage_providers.php'; break;
                default: redirect(base_url('admin/dashboard?error=notfound')); break;
            }
        }
        else {
            switch ($route) {
                case 'login': if (Auth::isLoggedIn()) { redirect(base_url('dashboard')); } $pageTitle = 'Login'; $layoutFile = TEMPLATE_DIR . '/layouts/auth.php'; $contentView = TEMPLATE_DIR . '/login.php'; break;
                case 'register': if (Auth::isLoggedIn()) { redirect(base_url('dashboard')); } $pageTitle = 'Registrasi'; $layoutFile = TEMPLATE_DIR . '/layouts/auth.php'; $contentView = TEMPLATE_DIR . '/register.php'; break;
                case 'dashboard': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Dashboard'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/admin/dashboard.php'; break;
                case 'order/create': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Buat Pesanan Baru'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/order/create.php'; break;
                case 'order/history': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Riwayat Pesanan'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/order/history.php'; $searchQuery = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? ''; $statusFilter = $_GET['status'] ?? 'all'; $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 10]]); break;
                case 'order/report': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Laporan Pesanan'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/order/report.php'; break;
                case 'services': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Daftar Layanan'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/services/index.php'; $searchQuery = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? ''; $serviceSortBy = $_GET['sort_by'] ?? 's.name'; $serviceSortType = $_GET['sort_type'] ?? 'ASC'; break;
                case 'deposit/new': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Deposit Baru'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/deposit/new.php'; break;
                case 'deposit/history': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Riwayat Deposit'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/deposit/history.php'; break;
                case 'deposit/report': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Laporan Deposit'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/deposit/report.php'; break;
                case 'balance/history': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Mutasi Saldo'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/balance/history.php'; break;
                case 'tickets': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Daftar Tiket'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/tickets/index.php'; break;
                case 'tickets/create': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Buat Tiket Baru'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/tickets/create.php'; break;
                case 'profile/settings': if (!Auth::isLoggedIn()) { redirect(base_url('login')); } $pageTitle = 'Pengaturan Akun'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/profile/settings.php'; break;
                case 'information': $pageTitle = 'Informasi'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/information.php'; break;
                case 'api-docs': $pageTitle = 'Dokumentasi API'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/api_docs.php'; break;
                case 'sitemap/contact': $pageTitle = 'Kontak'; $layoutFile = TEMPLATE_DIR . '/layouts/admin.php'; $contentView = TEMPLATE_DIR . '/sitemap/contact.php'; break;
                case 'home': $pageTitle = 'Beranda'; $layoutFile = TEMPLATE_DIR . '/layouts/main.php'; $contentView = TEMPLATE_DIR . '/home.php'; break;
                default:
                    $contentView = null;
                    break;
            }
        }
    }
    elseif (!in_array($requestMethod, ['POST', 'GET'])) {
        http_response_code(405);
        $contentView = null;
    }

    if ($contentView && file_exists($contentView) && file_exists($layoutFile)) {
        require_once $layoutFile;
    } elseif ($requestMethod === 'GET') {
        http_response_code(404);
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) {
            if (!$contentView) { echo "Error 404: Route '<code>" . htmlspecialchars($route) . "</code>' tidak terdefinisi atau tidak ditemukan."; }
            elseif (!file_exists($layoutFile)) { echo "Error 404: Layout file tidak ditemukan: <code>" . htmlspecialchars($layoutFile) . "</code>."; }
            elseif (!file_exists($contentView)) { echo "Error 404: Content view file tidak ditemukan: <code>" . htmlspecialchars($contentView ?? 'N/A') . "</code>."; }
            else { echo "Error 404: Halaman tidak ditemukan."; }
        } else {
            $pageTitle = "404 Not Found";
            $layoutFile = TEMPLATE_DIR . '/layouts/main.php';
            $contentView = TEMPLATE_DIR . '/errors/404.php';
            if(file_exists($contentView) && file_exists($layoutFile)) {
                require_once $layoutFile;
            } else {
                echo "Error 404: Halaman tidak ditemukan.";
            }
        }
    }

?>
