<?php
/**
 * Site Builder - GrapesJS Editor Auth Wrapper
 *
 * Authenticates the user, validates site ownership, injects WHP_CONFIG
 * into the editor HTML, and serves the page.
 */

// AUTH_USER is defined by auto-prepend.php via .user.ini
if (!defined('AUTH_USER')) {
    header('Location: /?login_required=1');
    exit;
}

// site_id is required
$site_id = isset($_GET['site_id']) ? (int)$_GET['site_id'] : 0;
if ($site_id <= 0) {
    header('Location: /?page=site-builder');
    exit;
}

// Database connection
require_once(__DIR__ . '/../libs/mysqlmgmt.php');
$MySQLMgmt = new mysqlmgmt();
$pdo = $MySQLMgmt->getMySQLConnection();

// Start session for CSRF token
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Validate user owns this site and get site info
$stmt = $pdo->prepare('
    SELECT s.id, s.site_name, s.username, sd.fqdn
    FROM whp.sites s
    JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
    WHERE s.id = :site_id
');
$stmt->execute(['site_id' => $site_id]);
$site = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$site) {
    header('Location: /?page=site-builder&error=site_not_found');
    exit;
}

// Authorization check: must be site owner or root
if ($site['username'] !== AUTH_USER && AUTH_USER !== 'root') {
    header('Location: /?page=site-builder&error=access_denied');
    exit;
}

// Build config object for the frontend
$config = [
    'user'       => AUTH_USER,
    'apiUrl'     => '/api/site-builder.php',
    'csrfToken'  => $_SESSION['csrf_token'] ?? '',
    'siteId'     => (int)$site['id'],
    'siteDomain' => $site['fqdn'],
    'siteName'   => $site['site_name'],
    'backUrl'    => '/?page=site-builder',
    'isRoot'     => (AUTH_USER === 'root'),
];

$json_config = json_encode($config, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

// Read the editor HTML file
$editor_path = __DIR__ . '/editor.html';
if (!file_exists($editor_path)) {
    http_response_code(500);
    echo 'Editor file not found. Please ensure editor.html is present in the site-builder directory.';
    exit;
}

$editor_html = file_get_contents($editor_path);

// Inject WHP_CONFIG script before the closing </head> tag
$config_script = "<script>window.WHP_CONFIG = {$json_config};</script>";
$editor_html = str_replace('</head>', $config_script . "\n</head>", $editor_html);

// Output the page
echo $editor_html;
