<?php
/**
 * SGAccount Router
 * -------------------------------------------------------------
 * Central routing for all views and controllers
 * PHP 8.1.31 | AdminLTE 3.2 | SGAccount (Home Renovation Accounting)
 * -------------------------------------------------------------
 */

declare(strict_types=1);

// ===============================================================
// 🧩 GLOBAL INCLUDES
// ===============================================================
require_once __DIR__ . '/../app/Config/config.php';
require_once __DIR__ . '/../app/Config/functions.php';

// ===============================================================
// ⚙️ AUTOLOADER (Controllers + Models)
// ===============================================================
spl_autoload_register(function (string $class): void {
    $paths = [
        __DIR__ . "/../app/Controllers/{$class}.php",
        __DIR__ . "/../app/Models/{$class}.php",
    ];
    foreach ($paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            return;
        }
    }
});

// ===============================================================
// 🧭 ROUTE NORMALIZATION
// ===============================================================
$page = strtolower(trim($_GET['page'] ?? 'dashboard', '/ '));
$page = str_replace(['.php', '..'], '', $page);

// ===============================================================
// 🔐 AUTHENTICATION CONTROL
// ===============================================================
$publicRoutes = ['login', 'register-admin'];
if (!in_array($page, $publicRoutes, true) && !is_logged_in()) {
    header('Location: router.php?page=login');
    exit;
}

// ===============================================================
// 🗂️ ROUTE MAP (Controllers + Views)
// ===============================================================
$routes = [

    // 🔓 Public Pages
    'login'           => __DIR__ . '/../app/Views/login.php',
    'register-admin'  => __DIR__ . '/../app/Views/register-admin.php',

    // 🧭 Core Modules
    'dashboard'       => DashboardController::class,
    'users'           => UsersController::class,
    'company'         => CompanyController::class,

    // 🧮 Accounting Core
    'coa'             => CoaController::class,
    'journal'         => JournalController::class,

    // 💰 Accounts Receivable
    'ar'              => ArController::class,
    'ar-view'         => ['ArController', 'viewInvoice'],
    'customers'       => CustomerController::class,
    // 💰 Company 
    'company-view'    => ['CompanyController', 'view'],

    // 🧾 Accounts Payable
    'ap'              => ApController::class,
    'ap-view'         => ['ApController', 'printPayment'],
    'vendors'         => VendorController::class,

    // 🏦 Bank & Cash Management (Phase 15)
    'bank'            => BankController::class,
    'bank-view'       => ['BankController', 'index'],

    // 💹 GST (Phase 16 placeholder)
    'gst'             => GstController::class,
    'gst-reports'     => ['GstController', 'reports'],

    // 📊 Financial Reports
    'trial-balance'   => ['ReportsController', 'trialBalance'],
    'profit-loss'     => ['ReportsController', 'profitLoss'],
    'balance-sheet'   => ['ReportsController', 'balanceSheet'],
    'cashflow'        => ['ReportsController', 'cashFlow'],
    'ledger'          => GeneralLedgerController::class,

    // 📁 Report Index Page
    'reports'         => __DIR__ . '/../app/Views/reports/index.php',

    // ⚙️ Utility / System Views
    'analytics'       => __DIR__ . '/../app/Views/analytics/index.php',
    'backup'          => __DIR__ . '/../app/Views/backup/index.php',
    'settings'        => __DIR__ . '/../app/Views/settings/index.php',
    'audit'           => __DIR__ . '/../app/Views/audit/index.php',
    'notifications'   => __DIR__ . '/../app/Views/notifications/index.php',
    'push'            => __DIR__ . '/../app/Views/push/index.php',
    'mailtest'        => __DIR__ . '/../app/Views/mailtest/index.php',

    // 🚪 Logout
    'logout'          => file_exists(__DIR__ . '/logout.php')
                        ? __DIR__ . '/logout.php'
                        : __DIR__ . '/../app/Views/logout.php',
];

// ===============================================================
// 🚦 ROUTE HANDLER (MVC ENABLED)
// ===============================================================
if (isset($routes[$page])) {
    $target = $routes[$page];

    // Case 1: Controller + Method (e.g. ['ReportsController','trialBalance'])
    if (is_array($target) && class_exists($target[0])) {
        [$controllerClass, $method] = $target;
        $controller = new $controllerClass();
        if (method_exists($controller, $method)) {
            $controller->$method();
            exit;
        }
    }

    // Case 2: Controller class (index default)
    if (is_string($target) && class_exists($target)) {
        $controller = new $target();
        if (method_exists($controller, 'index')) {
            $controller->index();
            exit;
        }
    }

    // Case 3: Direct view
    if (is_string($target) && file_exists($target)) {
        require $target;
        exit;
    }

    // 404 fallback for misconfig
    http_response_code(404);
    require __DIR__ . '/../app/Views/errors/404.php';
    exit;
}

// ===============================================================
// 📄 PDF GENERATION HANDLER
// ===============================================================
if ($page === 'pdf') {
    require_once __DIR__ . '/../app/Controllers/PdfController.php';
    $controller = new PdfController();
    $controller->generate($_GET['type'] ?? '');
    exit;
}

// ===============================================================
// 🚫 404 HANDLER (Final Fallback)
// ===============================================================
http_response_code(404);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404 Not Found | SGAccount</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
<style>
  body {
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
    background:#f4f6f9;
  }
  .card {
    max-width:480px;
    text-align:center;
    padding:40px;
    border-radius:12px;
    background:white;
    box-shadow:0 0 25px rgba(0,0,0,0.08);
  }
  .card h1 {
    font-size:4rem;
    margin-bottom:15px;
  }
</style>
</head>
<body>
<div class="card">
  <h1 class="text-danger"><i class="fas fa-exclamation-triangle"></i> 404</h1>
  <p class="lead mb-3">Oops! The page you requested was not found.</p>
  <a href="router.php?page=dashboard" class="btn btn-primary">
    <i class="fas fa-home mr-2"></i>Return to Dashboard
  </a>
</div>
</body>
</html>
