<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $html = $_POST['html'] ?? '';
    if (!$html) {
        echo json_encode(['success' => false, 'error' => 'No HTML received']);
        exit;
    }

    $filename = 'saved_' . time() . '.html';
    $path = 'saved_pages/' . $filename;

    if (!is_dir('saved_pages')) {
        mkdir('saved_pages', 0755, true);
    }

    // ✅ Inject popup + script just before </body>
    $rewardBlock = <<<HTML

<!-- 🎁 Reward Claim Button -->
<div id="claimContainer" style="margin-top:30px; display:none;">
  <button id="claimReportBtn" style="padding:12px 24px; font-size:16px; background:#ff416c; color:white; border:none; border-radius:6px; cursor:pointer;">
    🎁 Claim Your Free Report
  </button>
</div>

<!-- 📄 Report Popup -->
<div id="reportPopup" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.85); z-index:9999;">
  <div style="background:white; color:black; padding:20px; margin:80px auto; width:90%; max-width:500px; border-radius:12px; font-family:sans-serif;">
    <h2 style="margin-top:0;">🎉 Your Free Report</h2>
    <p><strong>Here’s what you’ll discover:</strong></p>
    <ul>
      <li>🚀 High-converting traffic strategies</li>
      <li>💡 Free tools & automation hacks</li>
      <li>📈 Secrets the top 1% marketers use</li>
    </ul>
    <p>This is your edge. Use it wisely.</p>
    <button id="closePopup" style="margin-top:20px; padding:10px 20px; background:#333; color:white; border:none; border-radius:6px;">Close</button>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const clicked = new Set();
    const buttons = document.querySelectorAll('.social-bar a');

    buttons.forEach(btn => {
      btn.addEventListener('click', () => {
        clicked.add(btn.className);
        if (clicked.size >= 2) {
          document.getElementById('claimContainer').style.display = 'block';
        }
      });
    });

    document.getElementById('claimReportBtn')?.addEventListener('click', () => {
      document.getElementById('reportPopup').style.display = 'block';
    });

    document.getElementById('closePopup')?.addEventListener('click', () => {
      document.getElementById('reportPopup').style.display = 'none';
    });
  });
</script>

HTML;

    // Inject reward block just before </body>
    $html = str_replace('</body>', $rewardBlock . "\n</body>", $html);

    file_put_contents($path, $html);

    // Track views
    $countFile = 'saved_pages/' . basename($filename, '.html') . '.count';
    file_put_contents($countFile, '0');

    $fullUrl = 'https://bestleadsgen.com/' . $path;
    echo json_encode(['success' => true, 'url' => $fullUrl]);
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
}
