<?php
include "../include/db.php";
include "include/header.php";

$landing_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($landing_id <= 0) {
    die('<div class="text-red-600 text-center text-2xl mt-20">Invalid Landing ID</div>');
}

$message = "";
$existing = null;

// Load existing data
$stmt = $conn->prepare("SELECT * FROM fb_settings WHERE landing_id = ?");
$stmt->bind_param("i", $landing_id);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows > 0) {
    $existing = $res->fetch_assoc();
}
$stmt->close();

// Save / Update
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_pixel'])) {
    $fb_pixel_id     = trim($_POST['fb_pixel_id']);
    $fb_access_token = trim($_POST['fb_access_token']);
    $test_event_code = trim($_POST['test_event_code']);

    if ($existing) {
        $sql = "UPDATE fb_settings SET fb_pixel_id = ?, fb_access_token = ?, test_event_code = ? WHERE landing_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssi", $fb_pixel_id, $fb_access_token, $test_event_code, $landing_id);
    } else {
        $sql = "INSERT INTO fb_settings (landing_id, fb_pixel_id, fb_access_token, test_event_code) VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isss", $landing_id, $fb_pixel_id, $fb_access_token, $test_event_code);
    }

    if ($stmt->execute()) {
        $message = '<div class="bg-green-100 border border-green-400 text-green-700 px-6 py-4 rounded-lg mb-6">✓ Pixel Settings Saved Successfully!</div>';

        // Reload fresh data
        $stmt2 = $conn->prepare("SELECT * FROM fb_settings WHERE landing_id = ?");
        $stmt2->bind_param("i", $landing_id);
        $stmt2->execute();
        $existing = $stmt2->get_result()->fetch_assoc();
        $stmt2->close();
    } else {
        $message = '<div class="bg-red-100 border border-red-400 text-red-700 px-6 py-4 rounded-lg mb-6">✗ Error: ' . htmlspecialchars($stmt->error) . '</div>';
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Facebook Pixel Setup - Landing #<?= $landing_id ?> | CourseLMS Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .modal { transition: all 0.3s ease; }
    </style>
</head>
<body class="bg-gray-50">

<div class="content p-6 min-h-screen">
    <div class="max-w-4xl mx-auto">
        <div class="mb-8 text-center">
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fab fa-facebook-square text-blue-600"></i> Facebook Pixel Setup
            </h1>
            <p class="text-lg text-gray-600">Landing Page ID: <span class="font-bold text-amber-600">#<?= $landing_id ?></span></p>
        </div>

        <?= $message ?>

        <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
            <div class="bg-gradient-to-r from-blue-600 to-indigo-700 text-white p-6">
                <h2 class="text-2xl font-semibold">Pixel Configuration Status</h2>
            </div>
            <div class="p-8">
                <?php if ($existing): ?>
                    <div class="flex items-center text-green-600 text-lg font-medium mb-6">
                        <i class="fas fa-check-circle text-3xl mr-3"></i>
                        Pixel is already configured
                    </div>
                <?php else: ?>
                    <div class="flex items-center text-amber-600 text-lg font-medium mb-6">
                        <i class="fas fa-exclamation-triangle text-3xl mr-3"></i>
                        No pixel configured yet
                    </div>
                <?php endif; ?>

                <button style="background: cornflowerblue;color:white" id="openModalBtn" class="bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white font-bold py-4 px-10 rounded-xl shadow-lg transform transition hover:scale-105">
                    <i class="fab fa-facebook-f mr-2"></i>
                    <?= $existing ? 'Edit' : 'Setup' ?> Facebook Pixel
                </button>
                
                  <?php
// URL থেকে landing ID নেওয়া
$landing_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
?>

<a href="manage_landing.php?id=<?= $landing_id ?>" 
   style="background: #01050c; color:white" 
   class="bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white font-bold py-4 px-10 rounded-xl shadow-lg transform transition hover:scale-105">
    <i class="fab fa-facebook-f mr-2"></i>
    <?= $existing ? 'Edit' : 'Setup' ?>  Back
</a>

                
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div id="pixelModal" class="fixed inset-0 bg-black bg-opacity-60 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-2xl shadow-2xl w-11/12 max-w-2xl p-8 relative">
        <button id="closeModalBtn" class="absolute top-4 right-6 text-gray-400 hover:text-gray-800 text-4xl">&times;</button>

        <h3 class="text-2xl font-bold text-gray-800 mb-6">Facebook Pixel Settings</h3>

        <form method="POST" class="space-y-6">
            <input type="hidden" name="save_pixel" value="1">

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Facebook Pixel ID <span class="text-red-500">*</span></label>
                <input type="text" name="fb_pixel_id" required value="<?= htmlspecialchars($existing['fb_pixel_id'] ?? '') ?>"
                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
                       placeholder="e.g. 123456789012345">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Access Token <span class="text-red-500">*</span></label>
                <textarea name="fb_access_token" rows="5" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
                          placeholder="Paste your long-lived access token here..."><?= htmlspecialchars($existing['fb_access_token'] ?? '') ?></textarea>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Test Event Code (Optional)</label>
                <input type="text" name="test_event_code" value="<?= htmlspecialchars($existing['test_event_code'] ?? '') ?>"
                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
                       placeholder="e.g. TEST12345">
            </div>

            <div class="flex justify-end gap-4">
                <button type="button" id="cancelBtn" class="px-6 py-3 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition">
                    Cancel
                </button>
                <button type="submit" class="px-8 py-3 bg-gradient-to-r from-green-500 to-green-600 text-white font-bold rounded-lg shadow-lg hover:from-green-600 hover:to-green-700 transition transform hover:scale-105">
                    <i class="fas fa-save mr-2"></i> Save Settings
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Fixed JavaScript (this was the real problem before) -->
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const modal = document.getElementById('pixelModal');
        const openBtn = document.getElementById('openModalBtn');
        const closeBtn = document.getElementById('closeModalBtn');
        const cancelBtn = document.getElementById('cancelBtn');

        // Open modal
        openBtn.onclick = function () {
            modal.classList.remove('hidden');
        }

        // Close modal
        closeBtn.onclick = cancelBtn.onclick = function () {
            modal.classList.add('hidden');
        }

        // Close when clicking outside
        window.onclick = function (event) {
            if (event.target === modal) {
                modal.classList.add('hidden');
            }
        }
    });
</script>

<?php include "include/footer.php"; ?>
<?php $conn->close(); ?>
</body>
</html>