<?php

// index.php - PARTE 1

// Inicia la sesión al principio de todo
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Define la ruta física raíz del proyecto
define('ROOT_PATH', dirname(__DIR__)); 

// ! ================== CONFIGURACIÓN CLAVE ==================
// ! 1. DEFINE AQUÍ MANUALMENTE EL SUBDIRECTORIO DE TU PROYECTO
// ! Para tu XAMPP local, debe ser: '/romarqtech_backend'
// ! Cuando lo subas a tu hosting, cámbialo por: '' (una cadena vacía)
define('BASE_URL', '');// ! ========================================================

// 2. Carga los helpers DESPUÉS de definir la constante
require_once ROOT_PATH . '/helpers.php';

/* Configuración de errores / entorno */
$isDevelopment = ($_SERVER['SERVER_NAME'] === 'localhost' || strpos($_SERVER['SERVER_ADDR'], '127.0.0.1') === 0);
if ($isDevelopment) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', 0);
    error_reporting(0);
}


$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Si BASE_URL está definido y no está vacío (estamos en un subdirectorio como XAMPP)
if (BASE_URL && BASE_URL !== '/' && strpos($requestUri, BASE_URL) === 0) {
    // Quita el subdirectorio de la URL para obtener la ruta limpia
    $route = substr($requestUri, strlen(BASE_URL));
} else {
    // Si estamos en la raíz (hosting), la ruta es la URL misma
    $route = $requestUri;
}

// Quita las barras de los extremos para normalizar la ruta
$route = trim($route, '/');
$requestMethod = $_SERVER['REQUEST_METHOD'];

$allowedOrigins = [
    'http://localhost:5173',
    'https://tu-dominio-en-produccion.com',
    'https://www.tu-dominio-en-produccion.com'
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Responder a la petición pre-vuelo (preflight) de los navegadores
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Decide si la ruta es para la API (JSON) o para una página normal (HTML)
$isApiRoute = (strpos($route, 'api/') === 0);
if ($isApiRoute) {
    header('Content-Type: application/json; charset=utf-8');
} else {
    header('Content-Type: text/html; charset=utf-8');
}

// Database connection for controllers
$databaseConfig = require ROOT_PATH . '/config/database.php';
$dsn = 'mysql:host=' . $databaseConfig['host'] . ';dbname=' . $databaseConfig['database'] . ';charset=' . $databaseConfig['charset'];
try {
    $db = new PDO($dsn, $databaseConfig['username'], $databaseConfig['password']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Include controllers
require_once ROOT_PATH . '/app/controllers/AuthController.php';
require_once ROOT_PATH . '/app/controllers/SettingsController.php';
require_once ROOT_PATH . '/app/controllers/ServiceController.php';
require_once ROOT_PATH . '/app/controllers/ProductController.php';
require_once ROOT_PATH . '/app/controllers/ProjectController.php';
require_once ROOT_PATH . '/app/controllers/TestimonialController.php';
require_once ROOT_PATH . '/app/controllers/FaqController.php';
require_once ROOT_PATH . '/app/controllers/TeamMemberController.php';
require_once ROOT_PATH . '/app/controllers/ClientController.php';
require_once ROOT_PATH . '/app/controllers/RecognitionController.php';
require_once ROOT_PATH . '/app/controllers/IndustryController.php';
require_once ROOT_PATH . '/app/controllers/PlanController.php';
require_once ROOT_PATH . '/app/controllers/CareerController.php';
require_once ROOT_PATH . '/app/controllers/PageController.php';
require_once ROOT_PATH . '/app/controllers/TechStackController.php';
require_once ROOT_PATH . '/app/controllers/ApiController.php';
require_once ROOT_PATH . '/app/controllers/DifferentiatorController.php';
require_once ROOT_PATH . '/app/controllers/MethodologyStepController.php';

$authController = new AuthController($db);
$settingsController = new SettingsController($db);
$serviceController = new ServiceController($db);
$productController = new ProductController($db);
$projectController = new ProjectController($db);
$testimonialController = new TestimonialController($db);
$faqController = new FaqController($db);
$teamMemberController = new TeamMemberController($db);
$clientController = new ClientController($db);
$recognitionController = new RecognitionController($db);
$industryController = new IndustryController($db);
$planController = new PlanController($db);
$careerController = new CareerController($db);
$pageController = new PageController($db);
$techStackController = new TechStackController($db);
$differentiatorController = new DifferentiatorController($db);
$apiController = new ApiController($db);
$methodologyStepController = new MethodologyStepController($db);
switch ($route) {
    case '':
        echo json_encode(["message" => "Welcome to the ROMARQTECH Backend!"]);
        break;

    case 'login':
        if ($requestMethod === 'GET') $authController->showLoginForm();
        elseif ($requestMethod === 'POST') $authController->login();
        break;

    case 'logout':
        $authController->logout();
        break;

    case 'admin/dashboard':
        if (!isset($_SESSION['user_id'])) redirect('login');
        ob_start();
        require_once ROOT_PATH . '/app/views/admin/dashboard.php';
        $content = ob_get_clean();
        $pageTitle = "Dashboard";
        require_once ROOT_PATH . '/app/views/admin/layout.php';
        break;

    case 'admin/settings':
        $settingsController->edit();
        break;
        
    // --- CRUDs COMPLETOS ---
    case 'admin/services': $serviceController->index(); break;
    case 'admin/services/create': $serviceController->create(); break;
    case 'admin/services/edit': $serviceController->edit(); break;
    case 'admin/services/delete': $serviceController->delete(); break;

    case 'admin/products': $productController->index(); break;
    case 'admin/products/create': $productController->create(); break;
    case 'admin/products/edit': $productController->edit(); break;
    case 'admin/products/delete': $productController->delete(); break;

    case 'admin/projects': $projectController->index(); break;
    case 'admin/projects/create': $projectController->create(); break;
    case 'admin/projects/edit': $projectController->edit(); break;
    case 'admin/projects/delete': $projectController->delete(); break;
    
    // ... (Y así sucesivamente para todos tus otros CRUDs) ...

    case 'admin/testimonials': $testimonialController->index(); break;
    case 'admin/testimonials/create': $testimonialController->create(); break;
    case 'admin/testimonials/edit': $testimonialController->edit(); break;
    case 'admin/testimonials/delete': $testimonialController->delete(); break;

    case 'admin/faqs': $faqController->index(); break;
    case 'admin/faqs/create': $faqController->create(); break;
    case 'admin/faqs/edit': $faqController->edit(); break;
    case 'admin/faqs/delete': $faqController->delete(); break;

    case 'admin/team_members': $teamMemberController->index(); break;
    case 'admin/team_members/create': $teamMemberController->create(); break;
    case 'admin/team_members/edit': $teamMemberController->edit(); break;
    case 'admin/team_members/delete': $teamMemberController->delete(); break;

    case 'admin/clients': $clientController->index(); break;
    case 'admin/clients/create': $clientController->create(); break;
    case 'admin/clients/edit': $clientController->edit(); break;
    case 'admin/clients/delete': $clientController->delete(); break;

    case 'admin/recognitions': $recognitionController->index(); break;
    case 'admin/recognitions/create': $recognitionController->create(); break;
    case 'admin/recognitions/edit': $recognitionController->edit(); break;
    case 'admin/recognitions/delete': $recognitionController->delete(); break;

    case 'admin/industries': $industryController->index(); break;
    case 'admin/industries/create': $industryController->create(); break;
    case 'admin/industries/edit': $industryController->edit(); break;
    case 'admin/industries/delete': $industryController->delete(); break;

    case 'admin/plans': $planController->index(); break;
    case 'admin/plans/create': $planController->create(); break;
    case 'admin/plans/edit': $planController->edit(); break;
    case 'admin/plans/delete': $planController->delete(); break;

    case 'admin/careers': $careerController->index(); break;
    case 'admin/careers/create': $careerController->create(); break;
    case 'admin/careers/edit': $careerController->edit(); break;
    case 'admin/careers/delete': $careerController->delete(); break;
        
    case 'admin/pages': $pageController->index(); break;
    case 'admin/pages/edit': $pageController->edit(); break;
        
    case 'admin/tech_stack': $techStackController->index(); break;
    case 'admin/tech_stack/create': $techStackController->create(); break;
    case 'admin/tech_stack/edit': $techStackController->edit(); break;
    case 'admin/tech_stack/delete': $techStackController->delete(); break;
     case 'admin/differentiators':
        $differentiatorController->index();
        break;
    case 'admin/differentiators/create':
        $differentiatorController->create();
        break;
    case 'admin/differentiators/edit':
        $differentiatorController->edit();
        break;
    case 'admin/differentiators/delete':
        $differentiatorController->delete();
        break;

        case 'admin/methodology_steps': $methodologyStepController->index(); break;
case 'admin/methodology_steps/create': $methodologyStepController->create(); break;
case 'admin/methodology_steps/edit': $methodologyStepController->edit(); break;
case 'admin/methodology_steps/delete': $methodologyStepController->delete(); break;
case 'api/brochure':
        $apiController->getBrochureData();
        break;
    // --- RUTA DE LA API ---
    case 'api/data':
        $apiController->getAllData();
        break;

    default:
        http_response_code(404);
        echo "404 Not Found. Ruta no reconocida: '" . htmlspecialchars($route) . "'";
        break;
}