<?php
/**
 * Router Principal - MontaLoja SaaS
 * Detecta subdominio OU dominio personalizado e roteia para a loja correta
 */

require_once __DIR__ . '/includes/env_loader.php';
loadEnv(__DIR__ . '/.env');

// Obter o host da requisicao
$host = $_SERVER['HTTP_HOST'] ?? '';
$host = strtolower(preg_replace('/:\d+$/', '', $host)); // Remove porta se existir
$baseDomain = getenv('SYSTEM_DOMAIN') ?: 'tiuoficial.com.br';

// Se SYSTEM_DOMAIN contem path (ex: localhost/Duolead), pegar apenas o host
if (strpos($baseDomain, '/') !== false) {
    $baseDomain = explode('/', $baseDomain)[0];
}

// Variaveis para identificacao da loja
$subdomain = null;
$customDomain = null;
$isCustomDomain = false;
$customDomainClean = null;

// ============================================
// DETECCAO DE DOMINIO PERSONALIZADO
// Se o host NAO contem duolead.com.br nem localhost, eh um dominio custom
// ============================================
$isLocalhostSubdomain = strpos($host, '.localhost') !== false;

if (strpos($host, $baseDomain) === false && !$isLocalhostSubdomain) {
    // Nao eh um subdominio do duolead.com.br nem .localhost
    // Verificar se eh um dominio personalizado cadastrado
    $customDomain = $host;
    
    // Remover www. se presente para buscar no banco
    $customDomainClean = preg_replace('/^www\./', '', $customDomain);
    $isCustomDomain = true;
} else {
    // Eh um subdominio do duolead.com.br ou .localhost
    // Extrair subdominio
    if ($isLocalhostSubdomain) {
        $subdomain = str_replace('.localhost', '', $host);
    } elseif (strpos($host, '.' . $baseDomain) !== false) {
        $subdomain = str_replace('.' . $baseDomain, '', $host);
    }
    
    if (isset($subdomain)) {
        $subdomain = strtolower(trim($subdomain));

        // Ignorar www ou vazio ou app ou localhost
        if ($subdomain === 'www' || $subdomain === '' || $subdomain === 'app' || $subdomain === 'localhost') {
            $subdomain = null;
        }
    }
}

// Se nao houver subdominio nem dominio custom, mostrar pagina principal
if (!$subdomain && !$isCustomDomain) {
    $requestUri = $_SERVER['REQUEST_URI'] ?? '/';

    if ($requestUri === '/' || $requestUri === '') {
        header('Location: /pages/landing.php');
        exit;
    }

    return false;
}

// Conectar ao banco e buscar a loja
require_once __DIR__ . '/includes/config.php';
$pdo = getDB();

$store = null;

if ($isCustomDomain && $customDomainClean) {
    // ============================================
    // BUSCAR POR DOMINIO PERSONALIZADO
    // Busca tanto com www quanto sem www
    // ============================================
    $stmt = $pdo->prepare("
        SELECT s.*, p.name as plan_name, p.features
        FROM stores s
        LEFT JOIN plans p ON s.plan_id = p.id
        WHERE (
            s.custom_domain = ? 
            OR s.custom_domain = ?
            OR s.custom_domain = ?
            OR s.custom_domain = ?
        )
        AND s.domain_type = 'custom'
        AND s.is_active = 1 
        AND s.deleted_at IS NULL
        LIMIT 1
    ");
    $stmt->execute([
        $customDomainClean,
        'www.' . $customDomainClean,
        $customDomain,
        preg_replace('/^www\./', '', $customDomain)
    ]);
    $store = $stmt->fetch(PDO::FETCH_ASSOC);
    
} elseif ($subdomain) {
    // ============================================
    // BUSCAR POR SUBDOMINIO
    // ============================================
    $stmt = $pdo->prepare("
        SELECT s.*, p.name as plan_name, p.features
        FROM stores s
        LEFT JOIN plans p ON s.plan_id = p.id
        WHERE s.subdomain = ? AND s.is_active = 1 AND s.deleted_at IS NULL
    ");
    $stmt->execute([$subdomain]);
    $store = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Se loja nao existe, mostrar erro 404
if (!$store) {
    header('HTTP/1.0 404 Not Found');
    include __DIR__ . '/pages/store-not-found.php';
    exit;
}

// Verificar status da loja (trial expirado, cancelado, etc)
$storeStatus = $store['status'];
if ($storeStatus === 'suspended' || $storeStatus === 'cancelled') {
    include __DIR__ . '/pages/store-suspended.php';
    exit;
}

// Verificar se trial expirou
if ($storeStatus === 'trial' && $store['trial_ends_at']) {
    $trialEnd = new DateTime($store['trial_ends_at']);
    $now = new DateTime();
    if ($now > $trialEnd) {
        include __DIR__ . '/pages/trial-expired.php';
        exit;
    }
}

// Definir variaveis globais da loja para usar nas paginas
define('STORE_ID', $store['id']);
define('STORE_NAME', $store['name']);
define('STORE_SLUG', $store['slug']);
define('STORE_SUBDOMAIN', $store['subdomain']);
define('STORE_TYPE', $store['type']);
define('STORE_PLAN', $store['plan_id']);
define('STORE_WHATSAPP', $store['whatsapp_number']);
define('STORE_EMAIL', $store['email']);
define('STORE_PRIMARY_COLOR', $store['primary_color'] ?? '#CCA43B');
define('STORE_LOGO', $store['logo_url'] ?? '');
define('STORE_BANNER', $store['banner_url'] ?? '');
define('STORE_STATUS', $store['status']);
define('STORE_CUSTOM_DOMAIN', $store['custom_domain'] ?? '');
define('STORE_IS_CUSTOM_DOMAIN', $isCustomDomain);

// Passar objeto da loja para a sessao
$_SESSION['current_store'] = $store;

// Rotear para a pagina da loja
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($requestUri, PHP_URL_PATH);

// Mapeamento de rotas da loja
$storeRoutes = [
    '/' => '/pages/storefront/home.php',
    '/home' => '/pages/storefront/home.php',
    '/servicos' => '/pages/storefront/services.php',
    '/services' => '/pages/storefront/services.php',
    '/agendar' => '/pages/storefront/booking.php',
    '/booking' => '/pages/storefront/booking.php',
    '/contato' => '/pages/storefront/contact.php',
    '/contact' => '/pages/storefront/contact.php',
    '/sobre' => '/pages/storefront/about.php',
    '/about' => '/pages/storefront/about.php',
    '/produtos' => '/pages/storefront/templates/retail/modern/produtos.php',
    '/products' => '/pages/storefront/templates/retail/modern/produtos.php',
    '/carrinho' => '/pages/storefront/cart.php',
    '/cart' => '/pages/storefront/cart.php',
    '/checkout' => '/pages/storefront/templates/retail/modern/checkout.php',
    '/favoritos' => '/pages/storefront/templates/retail/modern/favoritos.php',
    '/entrar' => '/pages/storefront/templates/retail/modern/login.php',
    '/login' => '/pages/storefront/templates/retail/modern/login.php',
    '/registrar' => '/pages/storefront/templates/retail/modern/registrar.php',
    '/registro' => '/pages/storefront/templates/retail/modern/registrar.php',
    '/minha-conta' => '/pages/storefront/templates/retail/modern/minha-conta.php',
    '/meus-pedidos' => '/pages/storefront/templates/retail/modern/meus-pedidos.php',
    '/meus-enderecos' => '/pages/storefront/templates/retail/modern/meus-enderecos.php',
    '/meus-dados' => '/pages/storefront/templates/retail/modern/meus-dados.php',
    '/alterar-senha' => '/pages/storefront/templates/retail/modern/alterar-senha.php',
    '/sair' => '/pages/storefront/templates/retail/modern/logout.php',
    '/logout' => '/pages/storefront/templates/retail/modern/logout.php',
];

// Verificar se rota existe
$routeFile = $storeRoutes[$path] ?? null;


// Rotas dinamicas (com parametros)
if (!$routeFile) {
    // /produto/{id}
    if (preg_match('#^/produto/(\d+)$#', $path, $matches)) {
        $_GET['id'] = $matches[1];
        $routeFile = '/pages/storefront/templates/retail/modern/produto.php';
    }
    // /pagina/{slug} - Paginas personalizadas
    elseif (preg_match('#^/pagina/([a-z0-9-]+)$#i', $path, $matches)) {
        $_GET['slug'] = $matches[1];
        $routeFile = '/pages/storefront/templates/retail/modern/pagina.php';
    }
    // /pedido/{id}
    elseif (preg_match('#^/pedido/(\d+)$#', $path, $matches)) {
        $_GET['id'] = $matches[1];
        $routeFile = '/pages/storefront/templates/retail/modern/pedido.php';
    }
    // /meu-pedido/{token} - Consulta por token único (guests)
    elseif (preg_match('#^/meu-pedido/([a-f0-9]{32})$#i', $path, $matches)) {
        $token = $matches[1];
        $routeFile = '/pages/storefront/templates/retail/modern/meu-pedido.php';
    }
}


if ($routeFile && file_exists(__DIR__ . $routeFile)) {
    include __DIR__ . $routeFile;
} else {
    // Pagina padrao da loja (home)
    include __DIR__ . '/pages/storefront/home.php';
}
exit;
