<?php
/**
 * Serve Site Builder assets directly from the site's document root.
 *
 * This is a standalone file that does NOT use auto-prepend.php.
 * Assets in a site's docroot are public files -- no auth needed.
 * This acts as a simple proxy for when the domain isn't pointed to the server yet.
 *
 * Usage: /api/serve-asset.php?site_id=1&filename=image.png
 */

// No session, no auth -- just serve the file
$siteId   = intval($_GET['site_id'] ?? 0);
$filename = basename($_GET['filename'] ?? '');

if ($siteId <= 0 || empty($filename)) {
    http_response_code(400);
    exit;
}

// Minimal DB connection to resolve the docroot path
$mycnf = @file_get_contents('/root/.my.cnf');
$password = '';
if ($mycnf && preg_match('/password\s*=\s*(.+)/', $mycnf, $m)) {
    $password = trim($m[1]);
}

try {
    $pdo = new PDO('mysql:host=127.0.0.1;port=3306;dbname=whp;charset=utf8mb4', 'root', $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 5,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    exit;
}

$stmt = $pdo->prepare("
    SELECT s.username, sd.fqdn, d.domain_name, ct.base_image
    FROM whp.sites s
    JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
    JOIN whp.domains d ON sd.domain_id = d.id
    JOIN whp.container_types ct ON s.container_type_id = ct.id
    WHERE s.id = :site_id
");
$stmt->execute([':site_id' => $siteId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    http_response_code(404);
    exit;
}

$fqdn = $row['fqdn'] ?: $row['domain_name'];
// Wildcard domains (*.example.com) are stored on disk as wildcard.example.com
$dirName = (strpos($fqdn, '*.') === 0) ? 'wildcard.' . substr($fqdn, 2) : $fqdn;
$baseDir = '/docker/users/' . $row['username'] . '/' . $dirName;
$image = $row['base_image'] ?? '';
$isPhp = (strpos($image, '/cac:') !== false || strpos($image, '/cac-fpm:') !== false);
$docroot = $isPhp ? ($baseDir . '/public_html/') : ($baseDir . '/');

// Look in staging area first (for editor use), then fall back to docroot assets (published)
$filePath = $docroot . '.site-builder/assets/' . $filename;
if (!file_exists($filePath)) {
    $filePath = $docroot . 'assets/' . $filename;
}

if (!file_exists($filePath)) {
    http_response_code(404);
    exit;
}

$mime = mime_content_type($filePath) ?: 'application/octet-stream';
$size = filesize($filePath);

header('Content-Type: ' . $mime);
header('Content-Length: ' . $size);
header('Cache-Control: public, max-age=86400');
readfile($filePath);
