<?php
namespace App\Core;

class App
{
    protected $routes = [];

    public function __construct()
    {
        $this->defineRoutes();
    }

    protected function defineRoutes()
    {
        // Format: 'METHOD|uri' => [ControllerClass::class, 'method']

        // Authentication
        $this->routes['GET|/']                    = [\App\Controllers\AuthController::class, 'loginForm'];
        $this->routes['GET|/login']               = [\App\Controllers\AuthController::class, 'loginForm'];
        $this->routes['POST|/login']              = [\App\Controllers\AuthController::class, 'login'];
        $this->routes['GET|/logout']              = [\App\Controllers\AuthController::class, 'logout'];

        // Dashboard
        $this->routes['GET|/dashboard']           = [\App\Controllers\DashboardController::class, 'index'];

        // Clients
        $this->routes['GET|/clients']             = [\App\Controllers\ClientController::class, 'index'];
        $this->routes['GET|/clients/create']      = [\App\Controllers\ClientController::class, 'create'];
        $this->routes['POST|/clients']            = [\App\Controllers\ClientController::class, 'store'];
        $this->routes['GET|/clients/(\d+)/deposit']   = [\App\Controllers\ClientController::class, 'depositForm'];
        $this->routes['POST|/clients/(\d+)/deposit']  = [\App\Controllers\ClientController::class, 'deposit'];
        $this->routes['GET|/clients/(\d+)/transaction']   = [\App\Controllers\ClientController::class, 'transactionForm'];
        $this->routes['POST|/clients/(\d+)/transaction']  = [\App\Controllers\ClientController::class, 'transaction'];
        $this->routes['GET|/clients/(\d+)/overdraft']     = [\App\Controllers\ClientController::class, 'overdraftForm'];
        $this->routes['POST|/clients/(\d+)/overdraft']    = [\App\Controllers\ClientController::class, 'updateOverdraft'];
        $this->routes['GET|/clients/(\d+)/statement/pdf']  = [\App\Controllers\ClientController::class, 'statementPdf'];
        $this->routes['GET|/clients/(\d+)/statement/excel'] = [\App\Controllers\ClientController::class, 'statementExcel'];

        // Forex
        $this->routes['GET|/forex/trades']               = [\App\Controllers\ForexController::class, 'index'];
        $this->routes['GET|/forex/trades/create']        = [\App\Controllers\ForexController::class, 'createForm'];
        $this->routes['POST|/forex/trades']              = [\App\Controllers\ForexController::class, 'store'];
        $this->routes['GET|/forex/profit-loss']          = [\App\Controllers\ForexController::class, 'profitLoss'];

        // Rent
        $this->routes['GET|/rent/properties']            = [\App\Controllers\RentController::class, 'properties'];
        $this->routes['GET|/rent/properties/create']     = [\App\Controllers\RentController::class, 'createPropertyForm'];
        $this->routes['POST|/rent/properties']           = [\App\Controllers\RentController::class, 'storeProperty'];
        $this->routes['GET|/rent/payments']              = [\App\Controllers\RentController::class, 'payments'];
        $this->routes['GET|/rent/payments/create']       = [\App\Controllers\RentController::class, 'createPaymentForm'];
        $this->routes['POST|/rent/payments']             = [\App\Controllers\RentController::class, 'storePayment'];

        // Daily Float
        $this->routes['GET|/daily-float']                = [\App\Controllers\DailyFloatController::class, 'index'];
        $this->routes['GET|/daily-float/create']         = [\App\Controllers\DailyFloatController::class, 'createForm'];
        $this->routes['POST|/daily-float']               = [\App\Controllers\DailyFloatController::class, 'store'];
// Reports
$this->routes['GET|/reports']                        = [\App\Controllers\ReportController::class, 'index'];
$this->routes['GET|/reports/client-transactions']    = [\App\Controllers\ReportController::class, 'clientTransactions'];
$this->routes['GET|/reports/forex-summary']          = [\App\Controllers\ReportController::class, 'forexSummary'];
$this->routes['GET|/reports/rent']                   = [\App\Controllers\ReportController::class, 'rentReport'];
     // Report exports
$this->routes['GET|/reports/client-transactions/pdf']  = [\App\Controllers\ReportController::class, 'exportPdf'];
$this->routes['GET|/reports/client-transactions/excel'] = [\App\Controllers\ReportController::class, 'exportExcel']; 
// Client Portal (no auth middleware – controllers handle their own auth)
$this->routes['GET|/client/login']           = [\App\Controllers\ClientAuthController::class, 'loginForm'];
$this->routes['POST|/client/login']          = [\App\Controllers\ClientAuthController::class, 'login'];
$this->routes['GET|/client/logout']          = [\App\Controllers\ClientAuthController::class, 'logout'];
$this->routes['GET|/client/dashboard']       = [\App\Controllers\ClientPortalController::class, 'dashboard'];
$this->routes['GET|/client/transactions']    = [\App\Controllers\ClientPortalController::class, 'transactions'];
$this->routes['GET|/client/statement/pdf']   = [\App\Controllers\ClientPortalController::class, 'statementPdf'];
// M‑Pesa
        $this->routes['GET|/mpesa']                      = [\App\Controllers\MpesaController::class, 'index'];
        $this->routes['GET|/mpesa/upload']               = [\App\Controllers\MpesaController::class, 'uploadForm'];
        $this->routes['POST|/mpesa/upload']              = [\App\Controllers\MpesaController::class, 'upload'];
        $this->routes['GET|/mpesa/match/(\d+)']          = [\App\Controllers\MpesaController::class, 'match'];
        // User Management
$this->routes['GET|/users']                    = [\App\Controllers\UserController::class, 'index'];
$this->routes['GET|/users/create']             = [\App\Controllers\UserController::class, 'createForm'];
$this->routes['POST|/users']                   = [\App\Controllers\UserController::class, 'store'];
$this->routes['GET|/users/edit/(\d+)']         = [\App\Controllers\UserController::class, 'editForm'];
$this->routes['POST|/users/update/(\d+)']      = [\App\Controllers\UserController::class, 'update'];
$this->routes['GET|/users/delete/(\d+)']       = [\App\Controllers\UserController::class, 'delete'];
// Global transaction recording
$this->routes['GET|/clients/transaction/create']  = [\App\Controllers\ClientController::class, 'createTransactionForm'];
$this->routes['POST|/clients/transaction']        = [\App\Controllers\ClientController::class, 'storeTransaction'];



$this->routes['POST|/api/staff/login']         = [\App\Controllers\ApiController::class, 'staffLogin'];
$this->routes['POST|/api/client/login']        = [\App\Controllers\ApiController::class, 'clientLogin'];
$this->routes['GET|/api/client/statement']     = [\App\Controllers\ApiController::class, 'clientStatement'];
// etc.

// Settings
$this->routes['GET|/settings']                 = [\App\Controllers\SettingsController::class, 'index'];
$this->routes['POST|/settings/save']           = [\App\Controllers\SettingsController::class, 'save'];
    }

    /**
     * Normalize the request URI by removing the base path (subdirectory)
     */
    protected function normalizeUri(string $uri): string
    {
        // Get the script name (e.g., /malsat/public/index.php)
        $scriptName = $_SERVER['SCRIPT_NAME'];
        // Get the directory name (e.g., /malsat/public)
        $basePath = dirname($scriptName);

        // If the URI starts with the base path, strip it
        if ($basePath !== '/' && $basePath !== '\\' && strpos($uri, $basePath) === 0) {
            $uri = substr($uri, strlen($basePath));
        }

        // Remove trailing slash for consistency
        $uri = rtrim($uri, '/');
        if ($uri === '') {
            $uri = '/';
        }

        return $uri;
    }

    public function run()
    {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/';
        $method = $_SERVER['REQUEST_METHOD'];

        // Normalize URI for subdirectories like /malsat/public
        $uri = $this->normalizeUri($uri);

        // Debug output (remove in production)
        // echo "Normalized URI: " . htmlspecialchars($uri) . "<br>";

        foreach ($this->routes as $key => $handler) {
            list($routeMethod, $routePattern) = explode('|', $key);
            if ($method !== $routeMethod) {
                continue;
            }

            $pattern = '#^' . $routePattern . '$#';
            if (preg_match($pattern, $uri, $matches)) {
                array_shift($matches); // Remove full match
                $controllerClass = $handler[0];
                $methodName = $handler[1];

                // Check if controller class exists
                if (!class_exists($controllerClass)) {
                    http_response_code(500);
                    echo "Controller class not found: " . htmlspecialchars($controllerClass);
                    return;
                }

                $controller = new $controllerClass();
                call_user_func_array([$controller, $methodName], $matches);
                return;
            }
        }

        http_response_code(404);
        echo "404 Not Found<br>";
        // Debug: show available routes (remove in production)
        // echo "Available routes: <pre>" . print_r(array_keys($this->routes), true) . "</pre>";
    }
}