<?php
declare(strict_types=1);

/**
 * Public shop catalog for native apps.
 * GET /api/catalog.php?tenant={slug}  (slug also comes from the hostname)
 */
require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/media.php';

$tenantSlug = tenant_param();
if ($tenantSlug !== '') {
    $_GET['tenant'] = $tenantSlug;
}

$tenant = resolve_tenant_from_host();
if (!$tenant) {
    json_response(['ok' => false, 'error' => 'Shop not found'], 404);
}
$tenantId = (int) $tenant['id'];

function catalog_absolute_url(string $url): string
{
    $url = trim($url);
    if ($url === '' || preg_match('#^https?://#i', $url)) {
        return $url;
    }
    $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
    $host = (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
    return ($https ? 'https' : 'http') . '://' . $host . '/' . ltrim($url, '/');
}

function catalog_pick(array $row, array $keys, mixed $default = ''): mixed
{
    foreach ($keys as $k) {
        if (array_key_exists($k, $row) && $row[$k] !== null && $row[$k] !== '') {
            return $row[$k];
        }
    }
    return $default;
}

$page = [];
try {
    $ps = db()->prepare('SELECT * FROM page_settings WHERE tenant_id = ?');
    $ps->execute([$tenantId]);
    $page = $ps->fetch() ?: [];
} catch (Throwable $e) {
    $page = [];
}

$services = [];
try {
    $stmt = db()->prepare('SELECT * FROM services WHERE tenant_id = ? ORDER BY display_order, id');
    $stmt->execute([$tenantId]);
    foreach ($stmt->fetchAll() as $sv) {
        $img = (string) catalog_pick($sv, ['image_url', 'image_path'], '');
        $services[] = [
            'id' => (int) $sv['id'],
            'name' => (string) $sv['name'],
            'description' => (string) ($sv['description'] ?? ''),
            'duration_minutes' => (int) catalog_pick($sv, ['duration_minutes'], 0),
            'price' => (float) $sv['price'],
            'image_url' => catalog_absolute_url(media_public_url($img) ?: $img),
        ];
    }
} catch (Throwable $e) {
    json_response(['ok' => false, 'error' => 'Services query failed: ' . $e->getMessage()], 500);
}

$staff = [];
try {
    $stmt = db()->prepare('SELECT * FROM staff_barbers WHERE tenant_id = ? ORDER BY name');
    $stmt->execute([$tenantId]);
    foreach ($stmt->fetchAll() as $b) {
        $img = (string) catalog_pick($b, ['profile_image_url', 'photo_url', 'image_url'], '');
        $staff[] = [
            'id' => (int) $b['id'],
            'name' => (string) $b['name'],
            'title' => (string) catalog_pick($b, ['title'], ''),
            'bio' => (string) catalog_pick($b, ['bio'], ''),
            'specialties' => (string) catalog_pick($b, ['specialties'], ''),
            'image_url' => catalog_absolute_url(media_public_url($img) ?: $img),
        ];
    }
} catch (Throwable $e) {
    $staff = [];
}

$styles = [];
try {
    $stmt = db()->prepare('SELECT * FROM style_gallery WHERE tenant_id = ? ORDER BY display_order, id');
    $stmt->execute([$tenantId]);
    foreach ($stmt->fetchAll() as $g) {
        $img = (string) catalog_pick($g, ['image_url', 'image_path'], '');
        $styles[] = [
            'id' => (int) $g['id'],
            'name' => (string) catalog_pick($g, ['style_name', 'name'], ''),
            'category' => (string) catalog_pick($g, ['category_tag', 'category'], ''),
            'linked_service_id' => (int) catalog_pick($g, ['linked_service_id', 'service_id'], 0),
            'image_url' => catalog_absolute_url(media_public_url($img) ?: $img),
        ];
    }
} catch (Throwable $e) {
    $styles = [];
}

$products = [];
try {
    $stmt = db()->prepare('SELECT * FROM products WHERE tenant_id = ? AND is_active = 1 ORDER BY display_order, id');
    $stmt->execute([$tenantId]);
    foreach ($stmt->fetchAll() as $p) {
        $img = (string) catalog_pick($p, ['image_path', 'image_url'], '');
        $products[] = [
            'id' => (int) $p['id'],
            'name' => (string) $p['name'],
            'slug' => (string) ($p['slug'] ?? ''),
            'description' => (string) catalog_pick($p, ['short_description', 'description'], ''),
            'price' => (float) $p['price'],
            'image_url' => catalog_absolute_url(media_public_url($img) ?: $img),
        ];
    }
} catch (Throwable $e) {
    $products = [];
}

$hero = (string) catalog_pick($page, ['hero_media_path', 'hero_image'], '');
$business = shop_company_name($page, $tenant);

json_response([
    'ok' => true,
    'tenant' => [
        'id' => $tenantId,
        'slug' => (string) ($tenant['subdomain'] ?? $tenantSlug),
        'name' => shop_company_name($page, $tenant),
        'business_name' => $business,
        'primary_color' => (string) catalog_pick($tenant, ['primary_color'], '#1a1a1a'),
        'secondary_color' => (string) catalog_pick($tenant, ['secondary_color'], '#c9a227'),
        'phone' => (string) ($page['phone'] ?? ''),
        'address' => (string) ($page['address'] ?? ''),
        'hero_headline' => shop_title_here($page),
        'hero_subheadline' => (string) catalog_pick($page, ['hero_subheadline', 'hero_subtitle'], ''),
        'hero_image_url' => catalog_absolute_url(media_public_url($hero) ?: $hero),
        'announcement' => !empty($page['announcement_enabled']) ? (string) ($page['announcement_text'] ?? '') : '',
        'cta_text' => (string) catalog_pick($page, ['cta_text', 'book_cta'], 'Book Now'),
    ],
    'services' => $services,
    'staff' => $staff,
    'styles' => $styles,
    'products' => $products,
]);
