<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

$jsonFile = __DIR__ . '/assets/data/snippets.json';
$defaultJsonFile = __DIR__ . '/assets/data/snippets-default.json';
$snippets = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];

if (isset($_GET['restore']) && $_GET['restore'] === '1') {
    if (file_exists($defaultJsonFile)) {
        $snippets = json_decode(file_get_contents($defaultJsonFile), true);
        file_put_contents($jsonFile, json_encode($snippets, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        header("Location: snippet-manager.php?restored=1");
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['snippets'])) {
    $decoded = json_decode($_POST['snippets'], true);
    if (json_last_error() === JSON_ERROR_NONE) {
        file_put_contents($jsonFile, json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        $snippets = $decoded;
        $success = true;
    } else {
        $error = "Invalid JSON format.";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Snippet Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/colors/ui/trumbowyg.colors.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/emoji/ui/trumbowyg.emoji.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/colors/trumbowyg.colors.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/emoji/trumbowyg.emoji.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
</head>
<body style="margin:0;">
<div style="display:flex; min-height:100vh;">

<!-- Sidebar -->
<div style="width:220px; background:#343a40; color:#fff; padding:20px;">
  <?php include 'admin-links.php'; ?>
</div>

<!-- Main content area -->
<div style="flex-grow:1; padding:30px;">
    <h2>🧠 Snippet Manager</h2>
    <?php if (!empty($success)): ?>
        <div class="alert alert-success">✅ Snippets updated successfully.</div>
    <?php elseif (!empty($_GET['restored'])): ?>
        <div class="alert alert-warning">♻️ Snippets have been restored to defaults.</div>
    <?php elseif (!empty($error)): ?>
        <div class="alert alert-danger">❌ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" onsubmit="return saveAllSnippets();">
        <input type="hidden" name="snippets" id="snippets">
        <div id="snippetList" class="accordion"></div>
        <button type="button" class="btn btn-secondary mt-3" onclick="addSnippet()">➕ Add Snippet</button>
        <button type="button" class="btn btn-warning mt-3" onclick="restoreDefaults()">♻️ Restore Default Snippets</button>
        <button type="button" class="btn btn-info mt-3" onclick="undoDelete()" id="undoDeleteBtn" style="display:none;">↩️ Undo Delete</button>
        <button type="submit" class="btn btn-success mt-3">💾 Save Snippets</button>
        <button type="button" class="btn btn-outline-dark mt-3 float-end" data-bs-toggle="modal" data-bs-target="#importSnippetsModal">
🧠 Generate Snippets with ChatGPT
</button>

    </form>
</div>

<script>
const existingSnippets = <?php echo json_encode($snippets, JSON_UNESCAPED_UNICODE); ?>;
let deletedSnippets = [];

function buildSnippetCard(snippet = {label:'', html:''}, index = Date.now()) {
    return `
    <div class="accordion-item" data-id="${index}">
        <h2 class="accordion-header">
            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-${index}">
                <input type="text" class="form-control border-0 bg-transparent" placeholder="Snippet Label" value="${snippet.label.replace(/"/g, '&quot;')}">
            </button>
        </h2>
        <div id="collapse-${index}" class="accordion-collapse collapse">
            <div class="accordion-body">
                <textarea class="snippet-editor form-control" style="height:100px;">${snippet.html.replace(/</g,'&lt;')}</textarea>
                <button type="button" class="btn btn-danger btn-sm mt-2" onclick="deleteSnippet(this)">🗑️ Delete</button>
            </div>
        </div>
    </div>`;
}

function renderSnippets() {
    const container = document.getElementById('snippetList');
    container.innerHTML = '';
    existingSnippets.forEach((snip, i) => {
        container.insertAdjacentHTML('beforeend', buildSnippetCard(snip, i));
    });
    initEditors();
}

function initEditors() {
    $('.snippet-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
    });
}

function addSnippet() {
    const newCard = buildSnippetCard();
    document.getElementById('snippetList').insertAdjacentHTML('beforeend', newCard);
    initEditors();
}

function deleteSnippet(btn) {
    const card = btn.closest('.accordion-item');
    const label = card.querySelector('input').value.trim();
    const html = $(card).find('.snippet-editor').trumbowyg('html');
    deletedSnippets.push({ label, html });
    card.remove();
    document.getElementById('undoDeleteBtn').style.display = 'inline-block';
}

function undoDelete() {
    if (deletedSnippets.length > 0) {
        const last = deletedSnippets.pop();
        document.getElementById('snippetList').insertAdjacentHTML('beforeend', buildSnippetCard(last));
        initEditors();
        if (deletedSnippets.length === 0) {
            document.getElementById('undoDeleteBtn').style.display = 'none';
        }
    }
}

function restoreDefaults() {
    if (confirm('Are you sure you want to restore all default snippets? This will overwrite your current list.')) {
        window.location.href = 'snippet-manager.php?restore=1';
    }
}
function copyPrompt() {
  const theme = document.getElementById('snippetTheme').value;

  const styleExamples = `[
  {
    "label": "💼 Work Smarter, Not Harder",
    "html": "<p style=\\"color:#4caf50; font-size:16px;\\"><strong>💼 Work Smarter, Not Harder</strong><br>This system works 24/7 to help you generate leads and signups.</p>"
  },
  {
    "label": "💡 Pro Tip: Let the System Do the Explaining",
    "html": "<p style=\\"background:#f9f9f9; padding:12px; border-left:4px solid #4caf50; color:#333;\\">💡 <strong>Pro Tip:</strong> Let the system do the explaining — you focus on sharing.</p>"
  },
  {
    "label": "📘 Did You Know? Start Free and Upgrade Later",
    "html": "<p style=\\"background:#f0f8ff; padding:12px; border-left:4px solid #03a9f4; color:#333;\\">📘 <strong>Did You Know?</strong><br>You can start 100% free and upgrade later as you grow.</p>"
  },
  {
    "label": "🔐 No Selling. No Tech. No Guesswork.",
    "html": "<p style=\\"background:#ffebee; padding:10px; border-left:5px solid #f44336; color:#333;\\">🔐 <strong>No Selling. No Tech. No Guesswork.</strong><br>Just follow the steps, share your link, and grow.</p>"
  }
]`;

  const promptText = `You are a marketing copywriter. I need 10 diverse and high-converting HTML snippets for a lead capture page promoting this theme: **${theme}**.

Please use this structure for each snippet:
{
  "label": "Short label for the snippet with emoji",
  "html": "Short HTML snippet (1–2 lines max, using bold, background colors, emojis, optional borders or highlight styles)"
}

Please vary the layout. Use a mix of centered text, bordered callouts, color highlights, bullet points, etc.

Respond ONLY with a JSON array like this:
${styleExamples}

Do NOT include commentary or explanation — just the clean JSON array.`;

  document.getElementById('gptPrompt').textContent = promptText;
  navigator.clipboard.writeText(promptText).then(() => {
    alert('✅ Prompt copied! Now paste it into ChatGPT.');
  });
}


function importSnippets() {
  const jsonText = document.getElementById('importJsonArea').value.trim();
  if (!jsonText) return alert('❗ Please paste some JSON first.');

  if (!confirm('Are you sure you want to replace ALL current snippets? This cannot be undone unless you restore defaults.')) return;

  try {
    const parsed = JSON.parse(jsonText);
    if (!Array.isArray(parsed)) throw new Error('Not a valid JSON array.');

    // Clear current
    document.getElementById('snippetList').innerHTML = '';

    // Build new
    parsed.forEach((snip, i) => {
      const html = buildSnippetCard(snip, i);
      document.getElementById('snippetList').insertAdjacentHTML('beforeend', html);
    });

    initEditors();
    alert('✅ Snippets imported. Click “Save Snippets” to apply.');

    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('importSnippetsModal'));
    modal.hide();
  } catch (err) {
    alert('❌ Invalid JSON format. Please check your structure.');
  }
}


function saveAllSnippets() {
    const snippets = [];
    document.querySelectorAll('#snippetList .accordion-item').forEach(item => {
        const label = item.querySelector('input').value.trim();
        const html = $(item).find('.snippet-editor').trumbowyg('html');
        if (label && html) {
            snippets.push({ label, html });
        }
    });
    document.getElementById('snippets').value = JSON.stringify(snippets);
    return true;
}

new Sortable(document.getElementById('snippetList'), {
    animation: 150,
    handle: '.accordion-header',
    draggable: '.accordion-item'
});

renderSnippets();
</script>
<!-- 🔮 Modal: ChatGPT Snippet Import -->
<div class="modal fade" id="importSnippetsModal" tabindex="-1" aria-labelledby="importSnippetsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h5 class="modal-title" id="importSnippetsModalLabel">🧠 Generate New Snippets with ChatGPT</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">

        <p>Use the tools below to generate a full set of fresh, branded snippets for your niche:</p>

        <h6>🎯 Choose Your Snippet Theme:</h6>
<select id="snippetTheme" class="form-select mb-3">
  <option value="Passive Income with Crypto">💰 Crypto Passive Income</option>
  <option value="AI Automation & Smart Tools">🤖 AI Automation</option>
  <option value="Weight Loss & Wellness Funnels">🏋️ Weight Loss Funnels</option>
  <option value="Affiliate Tools & Software">📈 Affiliate Tools</option>
  <option value="Generic Lead Generation System">🌐 Generic System</option>
</select>

<h6>📋 1. Copy This Prompt to ChatGPT:</h6>
<pre id="gptPrompt" class="bg-light p-3 border rounded" style="white-space:pre-wrap;"></pre>
<button class="btn btn-sm btn-outline-primary mt-2" onclick="copyPrompt()">📋 Copy ChatGPT Prompt</button>


        <hr>

        <h6>📥 2. Paste Your New JSON Snippets Below:</h6>
        <textarea id="importJsonArea" class="form-control" rows="12" placeholder="Paste your JSON array here..."></textarea>
        <button class="btn btn-danger mt-3" onclick="importSnippets()">⚠️ Replace All Snippets with Pasted JSON</button>
        <p class="text-muted mt-2">This will overwrite your current list. Don't worry — you can restore the defaults if needed.</p>

      </div>
    </div>
  </div>
</div>
</div> <!-- END main content -->
<?php include 'admin-footer.php'; ?>

</body>
</html>
