<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
// Load database and environment bootstrapper
require_once dirname(__DIR__) . '/app/db.php';

// Parse URL
$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$request_method = $_SERVER['REQUEST_METHOD'];

// Public channel surfaces (webhooks + public web chat + public business page) don't use PHP sessions.
$is_public_channel = strpos($request_uri, '/agent/') === 0
    || $request_uri === '/chat'
    || strpos($request_uri, '/n/') === 0
    || $request_uri === '/webhook/meta'
    || $request_uri === '/webhook/stripe'
    || $request_uri === '/sitemap.xml'
    || $request_uri === '/directorio'
    || strpos($request_uri, '/directorio/') === 0
    || (bool)preg_match('#^/(ni|hn|sv|us)(/|$)#', $request_uri);

if (!$is_public_channel && session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_only_cookies', 1);
    $is_secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
                 (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
    if ($is_secure) {
        ini_set('session.cookie_secure', 1);
    }
    session_start();
}

// Vale Admin (super-admin) — prefix routing, dispatched by the admin controller.
if ($request_uri === '/admin' || strpos($request_uri, '/admin/') === 0) {
    require_once dirname(__DIR__) . '/app/controllers/admin.php';
    exit;
}

// Página pública del negocio (cliente final): /n/{slug}.
if (strpos($request_uri, '/n/') === 0) {
    require_once dirname(__DIR__) . '/app/controllers/public_page.php';
    exit;
}

// Directorio público + sitemap (sin sesión).
// Incluye las rutas country-scoped /ni, /hn, /sv, /us y las legacy /directorio/*.
if ($request_uri === '/sitemap.xml'
    || $request_uri === '/directorio'
    || strpos($request_uri, '/directorio/') === 0
    || preg_match('#^/(ni|hn|sv|us)(/|$)#', $request_uri)) {
    require_once dirname(__DIR__) . '/app/controllers/directorio.php';
    exit;
}

// Expediente de cliente: /clientes/{id}
if (preg_match('#^/clientes/(\d+)$#', $request_uri, $m)) {
    $_GET['contact_id'] = (int) $m[1];
    require_once dirname(__DIR__) . '/app/controllers/cliente_perfil.php';
    exit;
}

// Route the request
switch ($request_uri) {
    case '/':
    case '/inicio':
    case '/dashboard':
    case '/dashboard/chat':
        if (isset($_SESSION['user_id'])) {
            require_once dirname(__DIR__) . '/app/controllers/dashboard.php';
            exit;
        }
        require dirname(__DIR__) . '/app/views/landing.php';
        break;

    case '/agent/whatsapp':
        if ($request_method !== 'POST') {
            http_response_code(405);
            echo 'Method Not Allowed';
            exit;
        }
        require_once dirname(__DIR__) . '/app/controllers/agent.php';
        break;

    case '/webhook/meta':
        // Meta Cloud API: GET para verificación del webhook, POST para mensajes.
        require_once dirname(__DIR__) . '/app/controllers/agent_meta.php';
        break;

    case '/agent/web':
        // Controller handles POST + OPTIONS (CORS preflight) itself.
        require_once dirname(__DIR__) . '/app/controllers/agent_web.php';
        break;

    case '/chat':
        // Public full-page web chat for a tenant (resolved by ?key=).
        require_once dirname(__DIR__) . '/app/controllers/chat.php';
        break;

    case '/empezar':
        require_once dirname(__DIR__) . '/app/controllers/wizard.php';
        break;

    case '/login':
    case '/logout':
        require_once dirname(__DIR__) . '/app/controllers/login.php';
        break;

    case '/auth/google':
    case '/auth/google/calendar':
    case '/auth/google/callback':
        require_once dirname(__DIR__) . '/app/controllers/google_auth.php';
        break;

    case '/inbox':
    case '/mensajes':
        require_once dirname(__DIR__) . '/app/controllers/inbox.php';
        break;

    case '/agenda':
        require_once dirname(__DIR__) . '/app/controllers/agenda.php';
        break;

    case '/leads':
    case '/clientes':
        require_once dirname(__DIR__) . '/app/controllers/leads.php';
        break;

    case '/negocio':
    case '/negocio/chat':
    case '/negocio/upload':
        require_once dirname(__DIR__) . '/app/controllers/negocio.php';
        break;

    case '/onboarding':
    case '/onboarding/message':
        require_once dirname(__DIR__) . '/app/controllers/onboarding.php';
        break;

    case '/ajustes':
        require_once dirname(__DIR__) . '/app/controllers/settings.php';
        break;

    // ── Billing ───────────────────────────────────────────────────────────────
    case '/billing':
    case '/billing/checkout':
    case '/billing/success':
    case '/billing/cash':
        require_once dirname(__DIR__) . '/app/controllers/billing.php';
        break;

    case '/webhook/stripe':
        // Raw body — sin sesión, sin buffer de salida.
        require_once dirname(__DIR__) . '/app/controllers/billing_webhook.php';
        break;

    // ── Seller ────────────────────────────────────────────────────────────────
    case '/seller':
    case '/seller/recursos':
    case '/seller/tenants':
    case '/seller/commissions':
    case '/seller/activate':
        require_once dirname(__DIR__) . '/app/controllers/seller.php';
        break;

    case '/data-deletion':
    case '/data-deletion/status':
        require_once dirname(__DIR__) . '/app/controllers/data_deletion.php';
        break;

    case '/privacy':
    case '/politica-de-privacidad':
        require dirname(__DIR__) . '/app/views/privacy.php';
        break;

    case '/terms':
    case '/terminos':
        require dirname(__DIR__) . '/app/views/terms.php';
        break;

    default:
        http_response_code(404);
        echo '404 Not Found';
        exit;
}
