<?php
/**
 * api-sites.php — SUBSPACE Site-Scoped Aggregate Queries
 *
 * Read-heavy endpoints for the public site:
 * - GET /site/{slug}/structure  — Full page tree with component instances
 * - GET /site/{slug}/page/{slug} — Single page with all instances + content
 */

$db_host = 'localhost';
$db_name = getenv('SUBSPACE_DB_NAME') ?: 'subspace_2026';
$db_user = getenv('SUBSPACE_DB_USER') ?: 'data';
$db_pass = getenv('SUBSPACE_DB_PASS') ?: 'ncc1701D';
$hmac_secret = trim(file_get_contents('/var/www/storage/subspace/.hmac-secret'));

try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'OPTIONS') { http_response_code(200); exit; }
if ($method !== 'GET') { http_response_code(405); echo json_encode(['error' => 'GET only']); exit; }

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
preg_match('#^/(subspace_[a-z0-9]+)/#', $uri, $_base);
$api_base = '/' . ($_base[1] ?? 'subspace_2026');
$path = preg_replace('#^/subspace_[a-z0-9]+/api-sites\.php/?#', '', $uri);
$path = trim($path, '/');

// GET /site/{slug}/structure
if (preg_match('#^site/([a-z0-9-]+)/structure$#', $path, $m)) {
    $site_slug = $m[1];

    require_once __DIR__ . '/subspace-audit.php';
    subspace_audit($pdo, subspace_identity(), 'site_read', 'sites', $site_slug, 200, null);
    $stmt = $pdo->prepare('SELECT id, slug, name, domain, description FROM sites WHERE slug = ? AND status = "active"');
    $stmt->execute([$site_slug]);
    $site = $stmt->fetch();
    if (!$site) { http_response_code(404); echo json_encode(['error' => 'Site not found']); exit; }

    // Get all visible pages
    $stmt = $pdo->prepare('SELECT id, slug, title, route, sort_order FROM pages WHERE site_id = ? AND visible = 1 ORDER BY sort_order');
    $stmt->execute([$site['id']]);
    $pages = $stmt->fetchAll();

    // For each page, get component instances
    foreach ($pages as &$page) {
        $stmt = $pdo->prepare('
            SELECT pc.sort_order, pc.visible, ci.id as instance_id, ci.name, ci.config, ci.status,
                   ct.slug as component_type, ct.label as component_label
            FROM page_components pc
            JOIN component_instances ci ON ci.id = pc.instance_id
            JOIN component_types ct ON ct.id = ci.component_type_id
            WHERE pc.page_id = ? AND pc.visible = 1 AND ci.status = "active"
            ORDER BY pc.sort_order
        ');
        $stmt->execute([$page['id']]);
        $components = $stmt->fetchAll();
        foreach ($components as &$c) {
            $c['config'] = json_decode($c['config'], true);
        }
        $page['components'] = $components;
    }

    echo json_encode(['site' => $site, 'pages' => $pages]);
    exit;
}

// GET /site/{slug}/page/{page_slug}
if (preg_match('#^site/([a-z0-9-]+)/page/([a-z0-9-]+)$#', $path, $m)) {
    $site_slug = $m[1];
    $page_slug = $m[2];

    $stmt = $pdo->prepare('SELECT id FROM sites WHERE slug = ? AND status = "active"');
    $stmt->execute([$site_slug]);
    $site = $stmt->fetch();
    if (!$site) { http_response_code(404); echo json_encode(['error' => 'Site not found']); exit; }

    require_once __DIR__ . '/subspace-audit.php';
    subspace_audit($pdo, subspace_identity(), 'page_read', 'pages', $site_slug . '/' . $page_slug, 200, null);
    $stmt = $pdo->prepare('SELECT id, slug, title, route FROM pages WHERE site_id = ? AND slug = ? AND visible = 1');
    $stmt->execute([$site['id'], $page_slug]);
    $page = $stmt->fetch();
    if (!$page) { http_response_code(404); echo json_encode(['error' => 'Page not found']); exit; }

    // Get instances with content
    $stmt = $pdo->prepare('
        SELECT pc.sort_order, ci.id as instance_id, ci.name, ci.config, ci.status,
               ct.slug as component_type, ct.label as component_label
        FROM page_components pc
        JOIN component_instances ci ON ci.id = pc.instance_id
        JOIN component_types ct ON ct.id = ci.component_type_id
        WHERE pc.page_id = ? AND pc.visible = 1 AND ci.status = "active"
        ORDER BY pc.sort_order
    ');
    $stmt->execute([$page['id']]);
    $components = $stmt->fetchAll();

    $allowed_tables = ['artists', 'gallery_items', 'posts', 'faqs', 'testimonials', 'carousel_slides', 'content_blocks', 'media'];

    foreach ($components as &$c) {
        $c['config'] = json_decode($c['config'], true);

        // Get content items for this instance
        $stmt2 = $pdo->prepare('SELECT content_type, content_id, sort_order FROM instance_content WHERE instance_id = ? ORDER BY sort_order');
        $stmt2->execute([$c['instance_id']]);
        $content_refs = $stmt2->fetchAll();

        $content = [];
        foreach ($content_refs as $ref) {
            if (!in_array($ref['content_type'], $allowed_tables)) continue;
            $stmt3 = $pdo->prepare("SELECT * FROM `{$ref['content_type']}` WHERE id = ? AND visibility = 'public'");
            $stmt3->execute([$ref['content_id']]);
            $item = $stmt3->fetch();
            if ($item) {
                $item['_type'] = $ref['content_type'];
                $item['_sort'] = $ref['sort_order'];
                // Generate signed URL for media items
                if ($ref['content_type'] === 'media' && isset($item['slug'], $item['signature'])) {
                    $ext = pathinfo($item['filename'], PATHINFO_EXTENSION);
                    $item['public_url'] = "$api_base/img/p/{$item['slug']}-{$item['signature']}.$ext";
                }
                $content[] = $item;
            }
        }
        $c['content'] = $content;
    }

    echo json_encode(['page' => $page, 'components' => $components]);
    exit;
}

http_response_code(404);
echo json_encode(['error' => 'Not found', 'path' => $path]);
