<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';

// Handle Add
if (isset($_POST['add_faq'])) {
    $q = $conn->real_escape_string($_POST['question']);
    $a = $conn->real_escape_string($_POST['answer']);
    $conn->query("INSERT INTO faqs (question, answer) VALUES ('$q', '$a')");
    header("Location: faqs.php");
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $conn->query("DELETE FROM faqs WHERE id=$id");
    header("Location: faqs.php");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage FAQs</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-6">
    <nav class="mb-6 flex gap-4">
        <a href="dashboard.php" class="text-blue-600 font-bold">← Back to Dashboard</a>
    </nav>

    <div class="grid md:grid-cols-3 gap-8">
        <div class="bg-white p-6 rounded shadow-md h-fit">
            <h2 class="text-xl font-bold mb-4">Add New Question</h2>
            <form method="POST" class="space-y-4">
                <div>
                    <label class="block text-sm text-gray-600">Question</label>
                    <input type="text" name="question" placeholder="e.g. Can I book online?" required class="w-full border p-2 rounded">
                </div>
                <div>
                    <label class="block text-sm text-gray-600">Answer</label>
                    <textarea name="answer" rows="4" placeholder="e.g. Yes, click the button..." required class="w-full border p-2 rounded"></textarea>
                </div>
                <button type="submit" name="add_faq" class="w-full bg-indigo-600 text-white py-2 rounded hover:bg-indigo-700">Save FAQ</button>
            </form>
        </div>

        <div class="md:col-span-2 space-y-4">
            <h2 class="text-xl font-bold">Current FAQs</h2>
            <?php
            $result = $conn->query("SELECT * FROM faqs ORDER BY id DESC");
            while($row = $result->fetch_assoc()) {
                echo '<div class="bg-white p-4 rounded shadow border-l-4 border-indigo-500 relative">';
                echo '<h3 class="font-bold text-gray-800 text-lg">Q: ' . $row['question'] . '</h3>';
                echo '<p class="text-gray-600 mt-2">A: ' . $row['answer'] . '</p>';
                echo '<a href="faqs.php?delete=' . $row['id'] . '" class="absolute top-2 right-2 text-red-500 text-sm hover:underline" onclick="return confirm(\'Delete?\')">Delete</a>';
                echo '</div>';
            }
            ?>
        </div>
    </div>
</body>
</html>