<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

function app_origin(): string
{
    $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
    $host = (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
    return ($https ? 'https' : 'http') . '://' . $host;
}

function current_tenant_id(): int
{
    $tenant = resolve_tenant_from_host();
    if ($tenant) {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
        $_SESSION['tenant_id'] = (int) $tenant['id'];
        return (int) $tenant['id'];
    }
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    return (int) ($_SESSION['tenant_id'] ?? 0);
}

function tenant_param(?array $tenant = null): string
{
    $fromRequest = strtolower(trim((string) ($_GET['tenant'] ?? $_POST['tenant'] ?? '')));
    if ($fromRequest !== '') {
        return $fromRequest;
    }
    $tenant = $tenant ?? resolve_tenant_from_host();
    return strtolower((string) ($tenant['subdomain'] ?? ''));
}

function tenant_qs(?array $tenant = null): string
{
    $slug = tenant_param($tenant);
    return $slug === '' ? '' : ('?tenant=' . rawurlencode($slug));
}

function require_admin(): void
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    if (empty($_SESSION['admin_logged_in'])) {
        header('Location: ' . APP_BASE . '/admin/login.php');
        exit;
    }
    $tenant = resolve_tenant_from_host();
    if ($tenant) {
        $_SESSION['tenant_id'] = (int) $tenant['id'];
    }
}

function get_tenant(?int $id = null): ?array
{
    $id = $id ?? current_tenant_id();
    $stmt = db()->prepare('SELECT * FROM tenants WHERE id = ? LIMIT 1');
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    return $row ?: null;
}

function resolve_tenant_from_host(): ?array
{
    $host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
    $host = preg_replace('/:\d+$/', '', $host) ?? $host;

    // Custom domain (client-owned domain on your GoDaddy)
    $stmt = db()->prepare('SELECT * FROM tenants WHERE custom_domain = ? LIMIT 1');
    $stmt->execute([$host]);
    $row = $stmt->fetch();
    if ($row) {
        return $row;
    }

    // Explicit ?tenant= still works on localhost
    $sub = strtolower(trim((string) ($_GET['tenant'] ?? $_POST['tenant'] ?? '')));
    $sub = $sub !== '' ? $sub : null;

    // {slug}.barber-shop.us  (demo.barber-shop.us → demo)
    // Skip bare apex / www — those are platform marketing, not shop tenants
    $platformApex = [
        'barber-shop.us', 'www.barber-shop.us',
        'barbers.dev', 'www.barbers.dev',
        'localhost', '127.0.0.1', '10.0.2.2',
    ];
    if (!$sub && !in_array($host, $platformApex, true)
        && preg_match('/^([a-z0-9-]+)\.(.+)$/', $host, $m)
        && $m[1] !== 'www'
    ) {
        $sub = $m[1];
    }

    if ($sub) {
        $stmt = db()->prepare('SELECT * FROM tenants WHERE subdomain = ? LIMIT 1');
        $stmt->execute([$sub]);
        $row = $stmt->fetch();
        if ($row) {
            return $row;
        }
    }

    // Fallback: first tenant (local / misconfigured host)
    $stmt = db()->query('SELECT * FROM tenants ORDER BY id ASC LIMIT 1');
    return $stmt->fetch() ?: null;
}

function shop_placeholder_name(string $value, string $fallback = 'Company Name Here'): string
{
    $value = trim($value);
    $stale = [
        '',
        'classic cuts demo',
        'classic cuts',
        'barbershop demo',
        'your barbershop demo',
    ];
    if ($value === '' || in_array(strtolower($value), $stale, true)) {
        return $fallback;
    }
    return $value;
}

function shop_company_name(?array $page = null, ?array $tenant = null): string
{
    $page = $page ?? [];
    $tenant = $tenant ?? [];
    $fromPage = trim((string) ($page['business_name'] ?? ''));
    $fromTenant = trim((string) ($tenant['name'] ?? ''));
    return shop_placeholder_name($fromPage !== '' ? $fromPage : $fromTenant);
}

function shop_title_here(?array $page = null): string
{
    $page = $page ?? [];
    $title = trim((string) ($page['hero_headline'] ?? ''));
    return $title !== '' ? $title : 'Title Here';
}

/** Build an app-absolute path using APP_BASE ('' on demo root, '<?= APP_BASE ?: '/' ?>' locally). */
function app_path(string $path = ''): string
{
    $path = '/' . ltrim($path, '/');
    if ($path === '/') {
        return APP_BASE === '' ? '/' : APP_BASE . '/';
    }
    return (APP_BASE === '' ? '' : APP_BASE) . $path;
}

function font_pairing_css(string $key): array
{
    $presets = [
        'modern_sans' => [
            'label' => 'Modern Sans',
            'heading' => "'DM Sans', system-ui, sans-serif",
            'body' => "'Inter', system-ui, sans-serif",
            'import' => 'https://fonts.googleapis.com/css2?family=DM+Sans:wght@500;700&family=Inter:wght@400;500;600&display=swap',
        ],
        'classic_serif' => [
            'label' => 'Classic Serif',
            'heading' => "'Playfair Display', Georgia, serif",
            'body' => "'Source Sans 3', system-ui, sans-serif",
            'import' => 'https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Source+Sans+3:wght@400;600&display=swap',
        ],
        'bold_display' => [
            'label' => 'Bold Display',
            'heading' => "'Bebas Neue', Impact, sans-serif",
            'body' => "'Nunito Sans', system-ui, sans-serif",
            'import' => 'https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Nunito+Sans:wght@400;600;700&display=swap',
        ],
        'editorial' => [
            'label' => 'Editorial',
            'heading' => "'Cormorant Garamond', Georgia, serif",
            'body' => "'Work Sans', system-ui, sans-serif",
            'import' => 'https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@600;700&family=Work+Sans:wght@400;500;600&display=swap',
        ],
        'clean_tech' => [
            'label' => 'Clean Tech',
            'heading' => "'Space Grotesk', system-ui, sans-serif",
            'body' => "'IBM Plex Sans', system-ui, sans-serif",
            'import' => 'https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=Space+Grotesk:wght@500;700&display=swap',
        ],
    ];

    return $presets[$key] ?? $presets['modern_sans'];
}
