<?php
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    ini_set('session.cookie_lifetime', 31536000);
    session_start();
}

require_once 'db.php';


$aiUsageCount = 0;

if (isset($_SESSION['logged_in_user'])) {
    $loggedInUser = $_SESSION['logged_in_user'];

    $query = $pdo->prepare("
        SELECT COUNT(*) FROM ai_usage_log 
        WHERE user_id = (SELECT id FROM users WHERE user_id = ?)
        AND MONTH(used_at) = MONTH(NOW()) 
        AND YEAR(used_at) = YEAR(NOW())
    ");
    $query->execute([$loggedInUser]);
    $aiUsageCount = $query->fetchColumn();
}

// ✅ Fetch Branding Settings (Logo)
$stmt = $pdo->query("SELECT logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch();
$logoImage = $branding['logo_image'] ?? '';


if (!isset($_SESSION['logged_in_user'])) {
    header("Location: user-login.php");
    exit;
}

$loggedInUser = $_SESSION['logged_in_user'];

// Fetch user's numeric user ID
$userQuery = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$userQuery->execute([$loggedInUser]);
$userData = $userQuery->fetch(PDO::FETCH_ASSOC);

if (!$userData) {
    header("Location: user-login.php");
exit;
}

$user_id = $userData['id']; // The correct numeric ID

$errorMessage = "";
$successMessage = "";


$share_code = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 6)); // Generates a 6-character unique code

// ✅ Define the mapping of colors to thumbnails
$colorToThumbnail = [
    "blue" => "1.png",
    "green" => "2.png",
    "orange" => "3.png",
    "purple" => "4.png",
    "red" => "5.png",
    "teal" => "6.png",
    "yellow" => "7.png",
    "pink" => "8.png",
    "gray" => "9.png"
];

// ✅ Form Handling - Save Lead Capture Page
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $headline = trim($_POST['headline']);
    $allowedTags = '<p><br><b><i><u><strong><em><span><div><ul><li><ol><a><img><h1><h2><h3><h4><h5><h6><center><blockquote><small><hr><pre><code><style><mark><strike><sup><sub><table><thead><tbody><tr><td><th>';
$subheadline = strip_tags($_POST['subheadline'], $allowedTags);
    $background = trim($_POST['background'] ?? 'bg1.jpg'); // ✅ Default to bg1.jpg if nothing is selected
    $mockup_filename = $_POST['mockup_filename'] ?? null;
    $color_theme = trim($_POST['color_theme']); // ✅ Ensure color is set first
    $cta_text = trim($_POST['cta_text'] ?? '');



    

    // ✅ Now determine the thumbnail AFTER setting color_theme
    $thumbnailFile = $colorToThumbnail[$color_theme] ?? "default.png"; 
    $thumbnailPath = "assets/thumbnails/" . $thumbnailFile;

    // ✅ Validate required fields
    if (empty($headline) || empty($subheadline) || empty($color_theme)) {
        $errorMessage = "All fields are required.";
    } else {
        // ✅ Insert into database
$stmt = $pdo->prepare("INSERT INTO lead_capture_pages 
(user_id, headline, subheadline, background, mockup_filename, color_theme, thumbnail, font_headline, font_subheading, share_code, cta_text, created_at) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");



        $font_headline = trim($_POST['font_headline']);
        $font_subheading = trim($_POST['font_subheading']);

$insertSuccess = $stmt->execute([
    $user_id,
    $headline,
    $subheadline,
    $background,
    $mockup_filename,
    $color_theme,
    $thumbnailPath,
    $font_headline,
    $font_subheading,
    $share_code,
    $cta_text
]);




        if (!$insertSuccess) {
            file_put_contents('debug_log.txt', "DB Insert Error: " . print_r($stmt->errorInfo(), true) . "\n", FILE_APPEND);
            die("Error: Could not create lead capture page. Check debug_log.txt for details.");
        }

        if ($insertSuccess) {
            // Redirect to lead-capture.php after successful submission
            header("Location: lead-capture.php?success=1");
            exit;
        } else {
            $errorMessage = "Error: Could not create lead capture page.";
        }
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create a New Lead Capture Page</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="assets/css/nav-style.css">
    
    <!-- Trumbowyg Editor CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css">

<!-- jQuery (required) -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<!-- Trumbowyg Editor JS -->
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js"></script>

<!-- ✅ Add this color plugin for text & background color support -->
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/colors/trumbowyg.colors.min.js"></script>

<!-- Trumbowyg Emoji Plugin -->
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/emoji/trumbowyg.emoji.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/emoji/ui/trumbowyg.emoji.min.css">



        <style>
    
    body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.container-fluid {
    flex-grow: 1;
}


    /* Ensure the sidebar stays fixed properly */
    .sidebar {
        width: 250px !important;
        min-height: 100vh;
        background-color: #f8f9fa;
    }

    /* Fix the main content so it doesn't shrink */
    .container-fluid {
        flex-grow: 1 !important;
        padding: 20px !important;
    }

    /* Ensure widgets and buttons stay aligned */
    .card {
        border-radius: 10px !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
    }

    /* Fix footer width */
    footer {
        width: 100% !important;
    }
    
    /* Floating Copy Notification */
.copy-notification {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #28a745; /* Green (Success) */
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 16px;
    display: none; /* Initially hidden */
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    transition: opacity 0.5s ease-in-out;
}

.copy-notification.show {
    display: block;
    opacity: 1;
}

.copy-notification i {
    margin-right: 8px;
}

/* Footer */
.footer {
    background-color: #343a40; /* Dark background */
    color: #ffffff; /* White text */
    text-align: center;
    padding: 15px;
    font-size: 14px;
    width: 100%;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    position: relative; /* Ensures it stays below content */
    margin-top: 20px; /* Adds space above the footer */
}

.rounded-circle {
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #ddd;
    transition: 0.3s;
}
.rounded-circle:hover {
    border-color: #007bff;
}


.color-selection {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: center;
}

.color-option {
    cursor: pointer;
    position: relative;
    display: inline-block;
}

.color-option input {
    display: none;
}

.color-circle {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: block;
    border: 3px solid transparent;
    transition: all 0.3s ease-in-out;
}

.color-option input:checked + .color-circle {
    border-color: #000;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
}

.color-option:hover .color-circle {
    transform: scale(1.1);
}

.ai-generator-box {
    background: linear-gradient(135deg, #f9fbff, #eef3ff);
    border-left: 5px solid #0d6efd;
    transition: all 0.3s ease;
}

.ai-generator-box:hover {
    background: linear-gradient(135deg, #f0f8ff, #dce9ff);
    border-color: #0b5ed7;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.ai-generator-box .form-label {
    font-size: 1.05rem;
}

#generateAI {
    transition: all 0.3s ease-in-out;
}

#generateAI:hover {
    transform: scale(1.04);
    background-color: #ffc107 !important;
    color: #000;
}

.glow-button {
    box-shadow: 0 0 10px rgba(255, 193, 7, 0.4) !important;
    animation: pulse-glow 2s infinite;
}


@keyframes pulse-glow {
    0%   { box-shadow: 0 0 8px rgba(255, 193, 7, 0.4) !important; }
    50%  { box-shadow: 0 0 16px rgba(255, 193, 7, 0.8) !important; }
    100% { box-shadow: 0 0 8px rgba(255, 193, 7, 0.4) !important; }
}


</style>

<style>
.insert-snippet {
    font-size: 14px;
    padding: 12px;
    background: #fff;
    transition: all 0.3s ease;
    border-radius: 8px;
}
.insert-snippet:hover {
    background: #f0f8ff;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
</style>

</head>
<body>



<!-- Floating Notification -->
<div id="copyNotification" class="copy-notification">
    <i class="fa fa-check-circle"></i> Copied to clipboard!
</div>


<?php include 'top-navbar.php'; ?>

<?php include 'sidebar.php'; ?>
<!-- Sidebar Toggle Button (Mobile Only) -->
<button onclick="toggleSidebar()" class="sidebar-toggle-btn">
    <i class="fas fa-bars"></i>
</button>

<!-- Overlay for sidebar on mobile -->
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>


        <div class="container-fluid p-4" style="background: #fff; min-height: 100vh;">



        <h2>Create a New Lead Capture Page<?php include 'google-translate-widget.php'; ?>
</h2>
<?php if (!empty($errorMessage)) : ?>
    <p style="color: red;"><?php echo $errorMessage; ?></p>
<?php endif; ?>

<?php if (!empty($successMessage)) : ?>
    <p style="color: green;"><?php echo $successMessage; ?></p>
<?php endif; ?>

<form method="POST">
    <div class="mb-3">
<label class="form-label">Headline</label>

<!-- ✨ AI Generator Section -->
<div class="ai-generator-box p-3 rounded shadow-sm mb-4">
    <div class="mb-2">
        <label for="aiTone" class="form-label fw-bold mb-1">
            🤖 <span class="text-primary">AI-Powered Headline Generator</span>
        </label>
        <select id="aiTone" class="form-select form-select-sm w-auto d-inline-block">
            <option value="friendly">😊 Friendly</option>
            <option value="aggressive">⚡ Aggressive</option>
            <option value="curiosity-driven">🧠 Curiosity</option>
            <option value="bold">🔥 Bold & Hype</option>
            <option value="emotional">💖 Emotional</option>
        </select>
    </div>

    <div class="d-flex flex-wrap align-items-center gap-3 mt-2">
        <button id="generateAI" type="button" class="btn btn-warning btn-sm shadow-sm fw-bold glow-button">
            <i class="fa fa-magic me-1"></i> 🔌 Generate Catchy Headline + Subheadline
        </button>

        <span id="cooldownNotice" class="text-muted small" style="display:none;">
            ⏳ Please wait 15 seconds between generations to avoid overuse.
        </span>

        <div class="small text-muted">
            <strong>Used:</strong> <?= $aiUsageCount ?> / 30 this month
        </div>
    </div>
</div>






<input type="text" name="headline" class="form-control" required>

    </div>

<div class="mb-3">


    <label class="form-label">Subheadline (You can use line breaks, emojis, etc.)</label><BR>
        
        <!-- 🔘 Insert Snippet Button -->
<button type="button" class="btn btn-outline-secondary mb-2" data-bs-toggle="modal" data-bs-target="#snippetModal">
    💡 Insert From Snippet Library
</button>




        
        <textarea name="subheadline" class="form-control" id="subheadline-editor"><?= htmlspecialchars($_POST['subheadline'] ?? '') ?></textarea>
        
        
    <small class="form-text text-muted">Use <code>&lt;br&gt;</code> for line breaks. Basic HTML like <code>&lt;b&gt;</code>, <code>&lt;i&gt;</code> will be supported soon.</small>
</div>





<h3>Select a Font Set</h3>
<div class="font-selection d-flex flex-wrap gap-3">
    <?php
    // Define font sets with their Google Fonts
    $fontSets = [
        1 => ['file' => 'Anton-Pacifico-set.png', 'headline' => 'Anton', 'subheading' => 'Pacifico'],
        2 => ['file' => 'Bebas-Neue-Dancing-Script-set.png', 'headline' => 'Bebas Neue', 'subheading' => 'Dancing Script'],
        3 => ['file' => 'Montserrat-Raleway-set.png', 'headline' => 'Montserrat', 'subheading' => 'Raleway'],
        4 => ['file' => 'Oswald-Lobster-set.png', 'headline' => 'Oswald', 'subheading' => 'Lobster'],
        5 => ['file' => 'Lato-Courgette-set.png', 'headline' => 'Lato', 'subheading' => 'Courgette'],
        6 => ['file' => 'Poppins-Roboto-set.png', 'headline' => 'Poppins', 'subheading' => 'Roboto'],
        7 => ['file' => 'Abril-Nunito-set.png', 'headline' => 'Abril Fatface', 'subheading' => 'Nunito'],
        8 => ['file' => 'Bangers-WorkSans-set.png', 'headline' => 'Bangers', 'subheading' => 'Work Sans'],
    ];

    foreach ($fontSets as $id => $set) {
        echo '
        <label class="font-option text-center">
            <input type="radio" name="font_set" value="'.$id.'" required class="d-none" data-headline="'.$set['headline'].'" data-subheading="'.$set['subheading'].'">
            <img src="assets/font-set-thumbs/'.$set['file'].'" alt="Font Set '.$id.'" class="font-thumbnail">
        </label>';
    }
    ?>
</div>

<script>
    document.querySelectorAll('input[name="font_set"]').forEach(input => {
        input.addEventListener('change', function() {
            document.getElementById('font_headline').value = this.dataset.headline;
            document.getElementById('font_subheading').value = this.dataset.subheading;
        });
    });
</script>

<!-- Hidden Inputs to Store Font Names -->
<input type="hidden" name="font_headline" id="font_headline" value="Anton">
<input type="hidden" name="font_subheading" id="font_subheading" value="Pacifico">

<style>
    .font-selection {
        display: flex;
        gap: 15px;
        justify-content: center;
        align-items: center;
        flex-wrap: wrap;
    }
    .font-option {
        cursor: pointer;
        border: 2px solid transparent;
        padding: 5px;
        border-radius: 10px;
        transition: all 0.3s ease-in-out;
    }
    .font-option img {
        width: 150px; /* Adjust size as needed */
        height: auto;
        border-radius: 5px;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    }
    .font-option:hover {
        border: 2px solid #007bff;
    }
    input[type="radio"]:checked + img {
        border: 3px solid #007bff;
    }
</style>


<?php
// Check permission to show upload modal
$stmt = $pdo->prepare("SELECT can_upload_backgrounds FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$flag = $stmt->fetchColumn();

if ($flag == 1): ?>
    <!-- Upload Button -->
    <button class="btn btn-outline-secondary btn-sm mb-3" data-bs-toggle="modal" data-bs-target="#uploadModal">
        <i class="fa fa-upload"></i> Upload Custom Background
    </button>

    
<?php endif; ?>


<!-- ✅ Background Selection -->
<div class="mb-3">
    <label class="form-label">Choose a Background</label>
    <div class="background-selection d-flex flex-wrap gap-3">
    <!-- Background selector loaded -->

        <?php
        $backgroundDir = 'assets/backgrounds/';
        // Load background grid content from external file with real filtering
include 'load-background-grid.php';
 // Fetch all .jpg files dynamically
        ?>
    </div>
</div>

<style>
    .background-selection {
        display: flex;
        gap: 15px;
        justify-content: center;
        align-items: center;
        flex-wrap: wrap;
    }
    .background-option {
        cursor: pointer;
        border: 2px solid transparent;
        padding: 5px;
        border-radius: 10px;
        transition: all 0.3s ease-in-out;
    }
    .background-option img {
        width: 150px; /* Adjust size as needed */
        height: auto;
        border-radius: 5px;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    }
    .background-option:hover {
        border: 2px solid #007bff;
    }
    input[type="radio"]:checked + img {
        border: 3px solid #007bff;
    }
</style>



<div class="mb-3">
    <label class="form-label">Optional: Select a Mockup Image</label>
    <p class="small text-muted">PNG only. Max 400KB. <a href="https://tinypng.com" target="_blank">Compress via TinyPNG</a>.</p>

    <!-- File input for uploading a custom mockup -->
    <input type="file" id="mockupUploader" accept=".png" class="form-control mb-3">

    <!-- Container for showing user's uploaded mockups -->
    <div id="mockupGrid" class="row mb-3"></div>


</div>


<style>
.mockup-thumb {
    border: 3px solid transparent;
    border-radius: 10px;
    transition: border-color 0.3s ease;
    cursor: pointer;
    width: 100%;
    height: auto;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
input[type="radio"].btn-check:checked + label .mockup-thumb {
    border-color: #28a745; /* Green border when selected */
}
.mockup-label {
    display: inline-block;
    cursor: pointer;
}
</style>




<!-- ✅ Call-to-Action Button Style Selector -->
<div class="mb-4">
    <label class="form-label">Choose Your Call-to-Action Button</label>
    <div class="d-flex flex-wrap gap-3 justify-content-center">
        <?php
$cta_options = [
    "fa-rocket YES, LET ME IN!",
    "fa-paper-plane SEND ME THE SYSTEM",
    "fa-bolt UNLOCK INSTANT ACCESS",
    "fa-magic SHOW ME HOW IT WORKS",
    "fa-gift CLAIM MY FREE SYSTEM",
    "fa-check START MY SETUP",
    "fa-play LET US GO!",
    "fa-lightbulb REVEAL THE METHOD",
    "fa-fire IGNITE MY FUNNEL",
    "fa-user-plus JOIN FOR FREE",
    "fa-forward I AM READY TO START",
    "fa-arrow-circle-right NEXT STEP, PLEASE"
];



        foreach ($cta_options as $option) {
            list($icon, $text) = explode(' ', $option, 2);
            $btnPreview = "<i class='fa $icon me-2'></i>$text";
            echo "
            <label class='btn btn-outline-primary d-flex align-items-center' style='padding: 10px; gap: 10px; border-radius: 8px;'>
                <input type='radio' name='cta_text' value='$option' class='d-none'>
                <span>$btnPreview</span>
            </label>";
        }
        ?>
    </div>
</div>

<style>
    input[name="cta_text"]:checked + span {
        font-weight: bold;
        color: #198754;
    }

    label.btn input[type="radio"]:checked + span {
        color: #fff !important;
        background-color: #198754 !important;
        padding: 6px 12px;
        border-radius: 6px;
    }
</style>


<!-- ✅ Modern Color Selection (No JavaScript) -->
<div class="mb-3">
    <label class="form-label">Choose Theme Color</label>
    <div class="color-selection d-flex flex-wrap gap-3 justify-content-center">
        <?php
        $colors = [
            "blue" => "#007bff",
            "green" => "#28a745",
            "orange" => "#fd7e14",
            "purple" => "#6f42c1",
            "red" => "#dc3545",
            "teal" => "#20c997",
            "yellow" => "#ffc107",
            "pink" => "#e83e8c",
            "gray" => "#6c757d"
        ];

        foreach ($colors as $colorName => $hex) {
            echo '
            <label class="color-option">
                <input type="radio" name="color_theme" value="'.$colorName.'" required class="d-none">
                <span class="color-circle" style="background-color: '.$hex.';"></span>
            </label>';
        }
        ?>
    </div>
</div>







    <button type="submit" class="btn btn-success">Save Lead Capture Page</button>
</form>

<!-- Upload Modal -->
    <div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <form id="uploadBgForm" enctype="multipart/form-data" novalidate>
            <div class="modal-header">
              <h5 class="modal-title" id="uploadModalLabel">Upload Background Image</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger d-none" id="uploadError"></div>
                <div class="alert alert-success d-none" id="uploadSuccess">Upload complete!</div>
                    <div class="alert alert-info small" style="font-size: 0.9rem;">
        💡 <strong>Tip:</strong> Make sure your image is a <code>.jpg</code> and under <strong>200 KB</strong>.  
        You can easily compress your image using <a href="https://tinypng.com" target="_blank">TinyPNG</a>.
    </div>

                <div class="mb-3">
                    <label class="form-label">Choose a .jpg image under 200 KB</label>
                    <input type="file" name="background_image" accept=".jpg" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
              <button type="submit" class="btn btn-primary">Upload</button>
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    </div>
    </div>
<?php include 'footer.php'; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>

 <script>
function toggleSidebar() {
  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');
  const toggleBtn = document.querySelector('.sidebar-toggle-btn');

  sidebar.classList.toggle('open');
  overlay.classList.toggle('show');
  document.body.classList.toggle('sidebar-opened');

  // Optional: toggle button visibility while sidebar is open
  if (document.body.classList.contains('sidebar-opened')) {
    toggleBtn.style.display = 'none';
  } else {
    toggleBtn.style.display = 'block';
  }
}

// ✅ Hide sidebar if top navbar is toggled (on mobile)
document.querySelector('.navbar-toggler')?.addEventListener('click', function () {
  document.querySelector('.sidebar')?.classList.remove('open');
  document.querySelector('.sidebar-overlay')?.classList.remove('show');
  document.body.classList.remove('sidebar-opened');
});
</script>

<script>
document.getElementById('uploadBgForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const form = e.target;
    const formData = new FormData(form);
    const successBox = document.getElementById('uploadSuccess');
    const errorBox = document.getElementById('uploadError');
    successBox.classList.add('d-none');
    errorBox.classList.add('d-none');

    fetch('ajax-upload-bg.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            successBox.classList.remove('d-none');
            form.reset();

// Refresh background selection with session cookies
fetch('load-background-grid.php', {
    credentials: 'include'
})
.then(res => res.text())
.then(html => {
    document.querySelector('.background-selection').innerHTML = html;
});


            // Close modal after delay
            setTimeout(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('uploadModal'));
                modal.hide();
            }, 1500);
        } else {
            errorBox.textContent = data.error;
            errorBox.classList.remove('d-none');
        }
    })
    .catch(err => {
        errorBox.textContent = 'Upload failed. Please try again.';
        errorBox.classList.remove('d-none');
    });
});
</script>
<script>
document.getElementById('mockupUploader').addEventListener('change', function() {
    let formData = new FormData();
    formData.append('file', this.files[0]);

    fetch('ajax-upload-mockup.php', {
        method: 'POST',
        body: formData
    }).then(res => res.text()).then(response => {
        if (response.trim() === "success") {
            loadMockups();
        } else {
            alert(response);
        }
    });
});

function loadMockups() {
    fetch('load-mockup-grid.php?mode=insert')
        .then(res => res.text())
        .then(html => {
            document.getElementById('mockupGrid').innerHTML = html;
        });
}

loadMockups();
</script>

<script>
$(document).ready(function() {
$('#subheadline-editor').trumbowyg({
    btns: [
        ['strong', 'em', 'underline'],
        ['foreColor', 'backColor'],
        ['emoji'],
        ['justifyLeft', 'justifyCenter', 'justifyRight'],
        ['removeformat'],
        ['viewHTML']
    ],
    plugins: {
        colors: {
            colorList: [
                '000000', '444444', '666666', '999999', 'cccccc', 'eeeeee', 'ffffff',
                'f44336', 'e91e63', '9c27b0', '673ab7', '3f51b5', '2196f3', '03a9f4',
                '00bcd4', '009688', '4caf50', '8bc34a', 'cddc39', 'ffeb3b', 'ffc107',
                'ff9800', 'ff5722'
            ]
        }
    },
    autogrow: true,
    removeformatPasted: false,
    semantic: false
});
});
</script>

<!-- 🧠 Snippet Modal -->
<div class="modal fade" id="snippetModal" tabindex="-1" aria-labelledby="snippetModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h5 class="modal-title" id="snippetModalLabel">📋 Subheadline Snippet Library</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row row-cols-1 row-cols-md-2 g-3">
          <!-- ✨ Snippet Buttons -->
          <!-- We will fill this with JS below -->
        </div>
      </div>
    </div>
  </div>
</div>
<script>
let snippets = [];

fetch('assets/data/snippets.json')
  .then(response => response.json())
  .then(data => {
    snippets = data;
    const container = $('#snippetModal .modal-body .row');
    snippets.forEach((item, index) => {
      const preview = $(
        `<div class="col"><button type="button" class="btn btn-light w-100 text-start border insert-snippet" data-index="${index}">${item.html}</button></div>`
      );
      container.append(preview);
    });
  });

$(document).on('click', '.insert-snippet', function () {
  const html = snippets[$(this).data('index')].html;
  $('#subheadline-editor').trumbowyg('html', html);
  const modal = bootstrap.Modal.getInstance(document.getElementById('snippetModal'));
  modal.hide();
});



// Build and insert snippet buttons
$(function () {
    const container = $('#snippetModal .modal-body .row');
    snippets.forEach((html, index) => {
        const preview = $('<div class="col"><button type="button" class="btn btn-light w-100 text-start border insert-snippet" data-index="' + index + '">' + html + '</button></div>');
        container.append(preview);
    });

    $(document).on('click', '.insert-snippet', function () {
        const html = snippets[$(this).data('index')].html;
        $('#subheadline-editor').trumbowyg('html', html);
        const modal = bootstrap.Modal.getInstance(document.getElementById('snippetModal'));
        modal.hide();
    });
});
</script>



<!-- 🖼️ Mockup Insert Modal -->
<div class="modal fade" id="mockupInsertModal" tabindex="-1" aria-labelledby="mockupInsertModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h5 class="modal-title" id="mockupInsertModalLabel">🖼️ Insert a Mockup Image</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="mockupModalContent">
        <!-- Filled by JS -->
      </div>
    </div>
  </div>
</div>
<script>
// 🧠 Load Mockup Modal
$('#loadMockupModal').on('click', function () {
    fetch('load-mockup-grid.php')
        .then(res => res.text())
        .then(html => {
            $('#mockupModalContent').html(html);
        });
});

// 🧠 Insert Image Tag When Clicked
$(document).on('click', '.insert-mockup', function () {
    const imageUrl = $(this).data('url');
    const imgTag = `<img src="${imageUrl}" style="max-width:100%; height:auto; display:block; margin:0 auto; border-radius:10px; box-shadow:0 2px 8px rgba(0,0,0,0.2);">`;
    $('#subheadline-editor').trumbowyg('execCmd', {
        cmd: 'insertHTML',
        param: imgTag,
        forceCss: false
    });
    const modal = bootstrap.Modal.getInstance(document.getElementById('mockupInsertModal'));
    modal.hide();
});
</script>



<script>
let cooldown = false;

document.getElementById('generateAI').addEventListener('click', function () {
    if (cooldown) return;

    const btn = this;
    const tone = document.getElementById('aiTone').value;
    const headlineField = document.querySelector('input[name="headline"]');
    const subField = $('#subheadline-editor');
    const cooldownNotice = document.getElementById('cooldownNotice');

    btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Generating...';
    btn.disabled = true;
    cooldownNotice.style.display = 'inline';

    fetch('generate-headline.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'tone=' + encodeURIComponent(tone)
    })
    .then(res => res.json())
.then(data => {
    const notif = document.getElementById('copyNotification');

    if (data.error || !data.headline) {
        const userFriendlyError = (data.error?.includes("API key") || !data.headline)
            ? "⚠️ AI is currently unavailable. Please let the admin know to set up the OpenAI API key in branding settings."
            : data.error || "⚠️ No headline was returned.";

        notif.innerHTML = '<i class="fa fa-exclamation-triangle"></i> ' + userFriendlyError;
        notif.style.backgroundColor = '#dc3545'; // red
        notif.classList.add('show');

        alert(userFriendlyError);

        setTimeout(() => {
            notif.classList.remove('show');
            notif.style.backgroundColor = '#28a745'; // restore green
        }, 5000);
        return;
    }

    // ✅ Success
    if (headlineField) headlineField.value = data.headline;
    if (subField.length && subField.data('trumbowyg')) {
        subField.trumbowyg('html', data.subheadline);
    } else {
        subField.val(data.subheadline);
    }

    notif.innerHTML = '<i class="fa fa-robot"></i> Headline Generated!';
    notif.classList.add('show');
    setTimeout(() => notif.classList.remove('show'), 2500);
})



    .catch(err => {
        console.error(err);
        alert("⚠ Something went wrong. Please try again.");
    })
.finally(() => {
    btn.innerHTML = '<i class="fa fa-magic"></i> Generate Headline + Subheadline';
    cooldown = true;

    setTimeout(() => {
        btn.disabled = false;
        cooldownNotice.style.display = 'none';
        cooldown = false;
    }, 15000); // 15 seconds
});
});
</script>


</body>
</html>
