<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }

$uri  = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$slug = '';
if (preg_match('#^/n/([a-z0-9\-]+)$#', $uri, $m)) {
    $slug = $m[1];
}

$db     = DB::connect();
$tenant = null;

if ($slug !== '') {
    $stmt = $db->prepare(
        "SELECT id, name, web_public_key, profile_kind, business_type, rubro, especialidad,
                public_slug, descripcion, descripcion_dir_en AS descripcion_en,
                telefono, direccion, plan, google_calendar_connected,
                whatsapp_number, ciudad, country, timezone,
                logo_url, banner_url, color_primario, color_acento, color_texto_cta
         FROM tenants WHERE public_slug = :s AND onboarding_status = 'live' AND deleted_at IS NULL LIMIT 1"
    );
    $stmt->execute([':s' => $slug]);
    $tenant = $stmt->fetch();
}

if (!$tenant) {
    http_response_code(404);
    require dirname(__DIR__) . '/views/directorio/404.php';
    exit;
}

$tid = (int)$tenant['id'];

// Servicios
$stmt = $db->prepare(
    "SELECT id, name, duration_min, price_min, price_max, description
     FROM services WHERE tenant_id = :t AND active = 1 ORDER BY id"
);
$stmt->execute([':t' => $tid]);
$services = $stmt->fetchAll();

// Vale config (greeting, hours, locale, calendar_id)
$stmt = $db->prepare("SELECT greeting, hours_json, default_locale, calendar_id FROM vale_config WHERE tenant_id = :t LIMIT 1");
$stmt->execute([':t' => $tid]);
$valeConfig = $stmt->fetch() ?: [];

$greeting = $valeConfig['greeting'] ?? '';
$locale   = $valeConfig['default_locale'] ?? 'es';

// Horarios
$horasTexto = '';
if (!empty($valeConfig['hours_json'])) {
    $decoded = json_decode($valeConfig['hours_json'], true);
    $horasTexto = is_array($decoded) ? ($decoded['texto'] ?? '') : '';
}

// Staff (puede no existir la tabla)
$staff = [];
try {
    $stmt = $db->prepare("SELECT nombre, rol FROM staff WHERE tenant_id = :t AND activo = 1 ORDER BY id LIMIT 20");
    $stmt->execute([':t' => $tid]);
    $staff = $stmt->fetchAll();
} catch (Throwable $e) { /* tabla aún no migrada */ }

// Indicador abierto/cerrado (heurística simple con el texto de horarios)
$isOpen = null; // null = no se puede determinar
if ($horasTexto) {
    $isOpen = publicPageIsOpen($horasTexto);
}

function publicPageIsOpen(string $text): ?bool {
    // Intenta detectar si "hoy" está en el horario, de forma muy conservadora.
    $dow  = (int)date('w'); // 0=Dom..6=Sáb
    $hour = (float)date('H') + (float)date('i') / 60;
    $text = mb_strtolower($text);

    // Si dice "cerrado" sin contexto de día, asumimos no aplica
    if (preg_match('/cerrado\s*(todo|siempre)/u', $text)) return false;

    // Buscar rango de horas en el texto — muy básico
    // Patrón: "9am-6pm", "9-18", "09:00-18:00"
    if (preg_match('/(\d{1,2})(?::00|am|h)?\s*[-–]\s*(\d{1,2})(?::00|pm|h)?/u', $text, $m)) {
        $open  = (int)$m[1];
        $close = (int)$m[2];
        if ($close < $open) $close += 12; // e.g. 9am-6pm → 9-18
        if ($hour >= $open && $hour < $close) return true;
        return false;
    }
    return null; // no se pudo parsear
}

require dirname(__DIR__) . '/views/public_page.php';
