<?php
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');

require_once 'templates/data.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'publish') {
    // Sanitize and retrieve POST data
    $title = htmlspecialchars($_POST['title'] ?? 'Your Awesome Ebook Title');
    $description = htmlspecialchars($_POST['description'] ?? 'A compelling description...');
    $imageUrl = filter_var($_POST['imageUrl'] ?? '', FILTER_VALIDATE_URL) ?: 'https://images.pexels.com/photos/1907785/pexels-photo-1907785.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1';
    $ctaText = htmlspecialchars($_POST['ctaText'] ?? 'Download Now');
    $ctaUrl = filter_var($_POST['ctaUrl'] ?? '', FILTER_VALIDATE_URL);
    $showCtaButton = isset($_POST['showCtaButton']);
    $checkoutHtml = $_POST['checkoutHtml'] ?? '';

    // Fetch CSS for inlining
    $cssContent = file_get_contents('assets/css/custom.css');

    // Prepare image for embedding or linking
    $imageFilename = basename(parse_url($imageUrl, PHP_URL_PATH));
    if (empty($imageFilename)) {
        $imageFilename = 'featured-image.jpg';
    }

    // Generate the final HTML content from the selected template structure
    $templateId = (int)($_POST['template_id'] ?? 1);
    $selectedTemplate = null;
    foreach ($templates as $t) {
        if ($t['id'] === $templateId) {
            $selectedTemplate = $t;
            break;
        }
    }

    $templateHtml = $selectedTemplate ? file_get_contents($selectedTemplate['file']) : '<div class="row align-items-center"><div class="col-md-6"><img id="previewImage" src="' . $imageUrl . '" class="img-fluid rounded shadow-sm" alt="Ebook Cover"></div><div class="col-md-6"><h1 id="previewTitle" class="display-5 fw-bold mt-4 mt-md-0">' . $title . '</h1><p id="previewDescription" class="lead fs-4">' . $description . '</p><div id="previewCtaContainer">' . $checkoutHtml . '</div></div></div>';
    $templateDom = new DOMDocument();
    // Wrap the template HTML in a single root element to ensure proper parsing
    @$templateDom->loadHTML('<div>' . $templateHtml . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

    // Remove the back button before publishing
    $backButton = $templateDom->getElementById('back-to-templates-btn');
    if ($backButton) {
        $backButton->parentNode->removeChild($backButton);
    }

    $imgTag = $templateDom->getElementById('previewImage');
    if ($imgTag) $imgTag->setAttribute('src', $imageUrl);

    $titleTag = $templateDom->getElementById('previewTitle');
    if ($titleTag) $titleTag->nodeValue = $title;

    $descTag = $templateDom->getElementById('previewDescription');
    if ($descTag) $descTag->nodeValue = $description;

    $ctaContainer = $templateDom->getElementById('previewCtaContainer');
    if ($ctaContainer) {
        while ($ctaContainer->hasChildNodes()) {
            $ctaContainer->removeChild($ctaContainer->firstChild);
        }

        if (!empty(trim($checkoutHtml))) {
            $fragment = $templateDom->createDocumentFragment();
            // Append HTML, suppressing errors for potentially malformed user input
            @$fragment->appendXML($checkoutHtml);
            $ctaContainer->appendChild($fragment);
        } elseif ($showCtaButton && $ctaUrl) {
            $link = $templateDom->createElement('a', $ctaText);
            $link->setAttribute('href', $ctaUrl);
            $link->setAttribute('class', 'btn btn-primary btn-lg');
            $link->setAttribute('role', 'button');
            $ctaContainer->appendChild($link);
        } else {
            // If no checkout HTML and button is disabled or no URL, remove the container
            if ($ctaContainer->parentNode) {
                $ctaContainer->parentNode->removeChild($ctaContainer);
            }
        }
    }

    // Extract the inner HTML of the temporary div
    $body = $templateDom->getElementsByTagName('div')->item(0);
    $finalPreviewHtml = '';
    foreach ($body->childNodes as $child) {
        $finalPreviewHtml .= $templateDom->saveHTML($child);
    }


    $htmlContent = <<<HTML
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>$title</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="icon" href="/assets/images/favicon.jpg" type="image/jpeg">
    <style>
        body {
            font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #F8F9FA;
            color: #212529;
        }
        .preview-container { max-width: 960px; }
        $cssContent
    </style>
</head>
<body>
    <main>
        <section class="py-5">
            <div class="container preview-container">
                $finalPreviewHtml
            </div>
        </section>
    </main>
    <footer class="text-center py-3 bg-light">
        <p class="mb-0">&copy; 2025 <a href="https://www.thecontentrepreneur.com/">The Contentrepreneur</a></p>
    </footer>
</body>
</html>
HTML;

    // Save the page
    $publishedDir = 'published';
    if (!is_dir($publishedDir)) {
        mkdir($publishedDir, 0755, true);
    }
    $pageId = uniqid();
    $filename = $publishedDir . '/' . $pageId . '.html';
    file_put_contents($filename, $htmlContent);

    $pageUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $filename;

    // Database interaction
    require_once 'db/config.php';
    $management_token = bin2hex(random_bytes(16));
    $expires_at = date('Y-m-d H:i:s', strtotime('+60 days'));

    try {
        $pdo = db();
        $stmt = $pdo->prepare("INSERT INTO published_pages (filename, management_token, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$pageId . '.html', $management_token, $expires_at]);
    } catch (PDOException $e) {
        // Log error, but don't show to user
        error_log("DB Error: " . $e->getMessage());
        // Fallback to just showing the page URL without management link
        echo "<div style='text-align:center; padding: 50px;'>";
        echo "<h2>Your page has been published!</h2>";
        echo "<p>You can view it here:</p>";
        echo "<a href='{$pageUrl}'>{$pageUrl}</a>";
        echo "</div>";
        exit;
    }

    $managementUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/manage.php?token=' . $management_token;

    // Display the success message and URL
    echo "<div style='text-align:center; padding: 50px;'>";
    echo "<h2>Your page has been published!</h2>";
    echo "<p>You can view it here:</p>";
    echo "<p><a href='{$pageUrl}'>{$pageUrl}</a></p>";
    echo "<hr style='margin: 20px auto; width: 50%;'>";
    echo "<p><strong>Manage your page:</strong></p>";
    echo "<p>To prevent your page from being deleted after 60 days, use the following link to extend its lifetime:</p>";
    echo "<p><a href='{$managementUrl}'>{$managementUrl}</a></p>";
    echo "</div>";

} else {
    header('Location: index.php');
    exit;
}
?>