
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

date_default_timezone_set('Asia/Riyadh');
require __DIR__ . '/../app/bootstrap.php';

// Default route
$r = $_GET['r'] ?? 'dashboard/index';

// Normalize route
$r = trim($r);
$r = ltrim($r, '/');

// Parse route into controller/action
[$ctrl, $action] = array_pad(explode('/', $r, 2), 2, 'index');

// Allow only safe characters (security hardening)
$ctrl   = preg_replace('/[^a-z0-9_]/i', '', $ctrl);
$action = preg_replace('/[^a-z0-9_]/i', '', $action);

// Controller map
$map = [
  'auth'      => __DIR__ . '/../app/controllers/AuthController.php',
  'dashboard' => __DIR__ . '/../app/controllers/DashboardController.php',
  'contacts'  => __DIR__ . '/../app/controllers/ContactsController.php',
  'leads'     => __DIR__ . '/../app/controllers/LeadsController.php',
  'opps'      => __DIR__ . '/../app/controllers/OpportunitiesController.php',
  'reports'   => __DIR__ . '/../app/controllers/ReportsController.php',
  'admin' => __DIR__ . '/../app/controllers/AdminController.php',
];

// 404 if controller is unknown
if (!isset($map[$ctrl])) {
  http_response_code(404);
  echo "Not found";
  exit;
}

// Load controller file
require $map[$ctrl];

// Build controller class name
$class = ucfirst($ctrl) . 'Controller';

// Instantiate controller
if (!class_exists($class)) {
  http_response_code(500);
  echo "Controller class not found";
  exit;
}

$controller = new $class($pdo, $config);

// Disallow calling magic/private style methods
if ($action === '' || str_starts_with($action, '__')) {
  http_response_code(404);
  echo "Not found";
  exit;
}

// Ensure method exists and is callable
if (!method_exists($controller, $action) || !is_callable([$controller, $action])) {
  http_response_code(404);
  echo "Not found";
  exit;
}

// Execute action
$controller->$action();