<?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'] === 'download') {
    // (The download logic remains the same)
    // 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');
    $checkoutHtml = $_POST['checkoutHtml'] ?? '<!-- Paste your checkout/buy button code here -->';

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

    // Prepare image for ZIP
    $imageContent = @file_get_contents($imageUrl);
    $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();
    @$templateDom->loadHTML($templateHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    $imgTag = $templateDom->getElementById('previewImage');
    if ($imgTag) $imgTag->setAttribute('src', $imageFilename);
    
    $titleTag = $templateDom->getElementById('previewTitle');
    if ($titleTag) $titleTag->nodeValue = $title;
    
    $descTag = $templateDom->getElementById('previewDescription');
    if ($descTag) $descTag->nodeValue = $description;
    
    $ctaContainer = $templateDom->getElementById('previewCtaContainer');
    if ($ctaContainer) {
        // Clear existing content
        while ($ctaContainer->hasChildNodes()) {
            $ctaContainer->removeChild($ctaContainer->firstChild);
        }
        if (!empty(trim($checkoutHtml))) {
            $fragment = $templateDom->createDocumentFragment();
            @$fragment->appendXML($checkoutHtml);
            $ctaContainer->appendChild($fragment);
        } else {
             $ctaContainer->nodeValue = $ctaText; // Fallback to simple text if no HTML
        }
    }
    
    $finalPreviewHtml = $templateDom->saveHTML();


    $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">
    <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;

    // Create a Zip archive
    $zip = new ZipArchive();
    $zipFileName = tempnam(sys_get_temp_dir(), 'ebook') . '.zip';
    if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
        $zip->addFromString('index.html', $htmlContent);
        if ($imageContent) {
            $zip->addFromString($imageFilename, $imageContent);
        }
        $zip->close();

        // Force download
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="ebook_page.zip"');
        header('Content-Length: ' . filesize($zipFileName));
        readfile($zipFileName);
        unlink($zipFileName);
        exit;
    } else {
        error_log('Failed to create the ZIP file.');
        exit('Could not create ZIP file.');
    }
}

$template_id = isset($_GET['template_id']) ? (int)$_GET['template_id'] : null;
$selectedTemplate = null;
$templateContent = '';

if ($template_id) {
    foreach ($templates as $t) {
        if ($t['id'] === $template_id) {
            $selectedTemplate = $t;
            break;
        }
    }
    if ($selectedTemplate && file_exists($selectedTemplate['file'])) {
        $templateContent = file_get_contents($selectedTemplate['file']);
    } else {
        $template_id = null; // Reset if template not found
    }
}

// Read project preview data from environment
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Create and customize your own ebook landing page.';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Ebook Lead Magnet Generator</title>

    <?php if ($projectDescription): ?>
    <meta name="description" content="<?= htmlspecialchars($projectDescription) ?>" />
    <meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
    <meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" />
    <?php endif; ?>
    <?php if ($projectImageUrl): ?>
    <meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
    <meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
    <?php endif; ?>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>

    <header class="py-3 mb-4 border-bottom bg-white">
        <div class="container d-flex flex-wrap justify-content-center">
            <a href="index.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-dark text-decoration-none">
                <span class="fs-4">Ebook Page Builder</span>
            </a>
        </div>
    </header>

    <main>
        <?php if ($template_id): ?>
            <section id="preview-section" class="py-5">
                <div class="container preview-container">
                    <?= $templateContent ?>
                </div>
            </section>

            <section id="editor-section" class="bg-light-subtle py-5 border-top">
                <div class="container">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2 class="m-0">Customize Your Page</h2>
                        
                    </div>
                    <form action="publish.php" method="POST">
                        <input type="hidden" name="template_id" value="<?= $template_id ?>">
                        <div class="row g-4">
                            <div class="col-md-6">
                                <label for="titleInput" class="form-label">Title</label>
                                <input type="text" class="form-control" id="titleInput" name="title" placeholder="Enter ebook title">
                            </div>
                            <div class="col-md-6">
                                <label for="ctaInput" class="form-label">Call to Action Button Text</label>
                                <input type="text" class="form-control" id="ctaInput" name="ctaText" placeholder="e.g., Get Your Free Copy">
                            </div>
                            <div class="col-12">
                                <label for="descriptionInput" class="form-label">Description</label>
                                <textarea class="form-control" id="descriptionInput" name="description" rows="3" placeholder="Describe your ebook"></textarea>
                            </div>
                            <div class="col-12">
                                <label for="imageUrlInput" class="form-label">Featured Image URL</label>
                                <input type="url" class="form-control" id="imageUrlInput" name="imageUrl" placeholder="https://example.com/image.jpg">
                            </div>
                            <div class="col-md-6">
                                <label for="ctaUrlInput" class="form-label">Button Link URL</label>
                                <input type="url" class="form-control" id="ctaUrlInput" name="ctaUrl" placeholder="https://your-download-link.com">
                            </div>
                            <div class="col-md-6 d-flex align-items-end">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" role="switch" id="showCtaButton" name="showCtaButton" checked>
                                    <label class="form-check-label" for="showCtaButton">Show Call to Action Button</label>
                                </div>
                            </div>
                            <div class="col-12">
                                <label for="checkoutHtmlInput" class="form-label">Checkout/Buy Button HTML</label>
                                <textarea class="form-control" id="checkoutHtmlInput" name="checkoutHtml" rows="4" placeholder="Paste your HTML embed code here (e.g., from Stripe, PayPal, Gumroad)"></textarea>
                                <div class="form-text">This will replace the default button in the preview. If you use this, uncheck "Show Call to Action Button" above.</div>
                            </div>
                            <div class="col-12 text-center mt-4">
                                <button type="submit" name="action" value="download" class="btn btn-success btn-lg">Generate and Download ZIP</button>
                                <button type="submit" name="action" value="publish" class="btn btn-primary btn-lg">Publish Page</button>
                            </div>
                        </div>
                    </form>
                </div>
            </section>
        <?php else: ?>
            <section id="gallery-section" class="py-5">
                <div class="container">
                    <div class="text-center mb-5">
                        <h1 class="display-5 fw-bold">Start with a Beautiful Design</h1>
                        <p class="lead fs-4 text-muted">Select a professionally designed template to begin.</p>
                    </div>
                    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
                        <?php foreach ($templates as $template):
                        ?>
                            <div class="col">
                                <div class="card h-100 shadow-sm">
                                    <img src="<?= htmlspecialchars($template['preview_image']) ?>" class="card-img-top" alt="<?= htmlspecialchars($template['name']) ?>">
                                    <div class="card-body">
                                        <h5 class="card-title"><?= htmlspecialchars($template['name']) ?></h5>
                                        <p class="card-text"><?= htmlspecialchars($template['description']) ?></p>
                                    </div>
                                    <div class="card-footer bg-white border-0">
                                        <a href="?template_id=<?= $template['id'] ?>" class="btn btn-primary w-100">Customize this template</a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach;
                        ?>
                    </div>
                </div>
            </section>
        <?php endif; ?>
    </main>
    
    <section id="how-to-deploy" class="py-5 bg-light">
        <div class="container">
            <div class="text-center mb-5">
                <h2 class="fw-bold">How to Deploy Your Ebook Page</h2>
                <p class="lead fs-4 text-muted">A simple guide to get your page online.</p>
            </div>
            <div class="row g-4">
                <div class="col-md-4">
                    <div class="text-center">
                        <div class="mb-3">
                            <span class="fs-1">1</span>
                        </div>
                        <h5>Unzip the File</h5>
                        <p>The file you downloaded is a ZIP archive. Unzip it to a folder on your computer. You will find an `index.html` file and an image file inside.</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="text-center">
                        <div class="mb-3">
                            <span class="fs-1">2</span>
                        </div>
                        <h5>Upload to Your Hosting</h5>
                        <p>Log in to your web hosting control panel (like cPanel, Plesk, or others) or use an FTP client (like FileZilla). Upload the `index.html` file and the image file to the `public_html` or `www` directory of your domain.</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="text-center">
                        <div class="mb-3">
                            <span class="fs-1">3</span>
                        </div>
                        <h5>Visit Your Page</h5>
                        <p>Once the files are uploaded, you should be able to visit your domain in your browser and see your new ebook landing page live.</p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <footer class="text-center py-3 mt-5 bg-light border-top">
        <p class="mb-0">&copy; <?= date('Y') ?> <a href="https://www.thecontentrepreneur.com/">The Contentrepreneur</a></p>
    </footer>

    <script src="assets/js/main.js?v=<?php echo time(); ?>"></script>
</body>
</html>
