<?php
require_once '../config.php';

$conn = get_db_connection();
$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
            $question = trim($_POST['question'] ?? '');
            $answer = trim($_POST['answer'] ?? '');
            $display_order = intval($_POST['display_order'] ?? 0);

            if (empty($question) || empty($answer)) {
                $message = 'Question and Answer are required!';
                $message_type = 'danger';
            } else {
                if ($_POST['action'] === 'add') {
                    $stmt = $conn->prepare("INSERT INTO faqs (question, answer, display_order) VALUES (?, ?, ?)");
                    $stmt->bind_param("ssi", $question, $answer, $display_order);
                    if ($stmt->execute()) {
                        $message = 'FAQ added successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error adding FAQ: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                } else {
                    $id = intval($_POST['id']);
                    $stmt = $conn->prepare("UPDATE faqs SET question = ?, answer = ?, display_order = ? WHERE id = ?");
                    $stmt->bind_param("ssii", $question, $answer, $display_order, $id);
                    if ($stmt->execute()) {
                        $message = 'FAQ updated successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating FAQ: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                }
            }
        } elseif ($_POST['action'] === 'delete') {
            $id = intval($_POST['id']);
            $stmt = $conn->prepare("DELETE FROM faqs WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                $message = 'FAQ deleted successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error deleting FAQ: ' . $stmt->error;
                $message_type = 'danger';
            }
            $stmt->close();
        }
    }
}

// Get all FAQs
$faqs_result = $conn->query("SELECT * FROM faqs ORDER BY display_order ASC, id ASC");
$faqs = [];
if ($faqs_result) {
    while ($row = $faqs_result->fetch_assoc()) {
        $faqs[] = $row;
    }
}

// Get FAQ for editing
$edit_faq = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM faqs WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $row = $result->fetch_assoc()) {
        $edit_faq = $row;
    }
    $stmt->close();
}

$page_title = 'FAQ Management';
$extra_css = '<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">';
$extra_js = '<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
    var quill = new Quill("#answer-editor", {
        theme: "snow",
        modules: {
            toolbar: [
                [{ "header": [1, 2, 3, false] }],
                ["bold", "italic", "underline", "strike"],
                [{ "color": [] }, { "background": [] }],
                [{ "list": "ordered"}, { "list": "bullet" }],
                [{ "align": [] }],
                ["link", "blockquote", "code-block"],
                ["clean"]
            ]
        }
    });
    
    var form = document.querySelector("form");
    var answerTextarea = document.getElementById("answer");
    
    if (answerTextarea.value) {
        quill.root.innerHTML = answerTextarea.value;
    }
    
    form.addEventListener("submit", function(e) {
        answerTextarea.value = quill.root.innerHTML;
    });
</script>';

require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title"><?php echo $edit_faq ? 'Edit FAQ' : 'Add New FAQ'; ?></h2>
        <?php if ($edit_faq): ?>
            <a href="faq" class="btn btn-secondary btn-sm">Cancel</a>
        <?php endif; ?>
    </div>

    <form method="POST" action="">
        <input type="hidden" name="action" value="<?php echo $edit_faq ? 'edit' : 'add'; ?>">
        <?php if ($edit_faq): ?>
            <input type="hidden" name="id" value="<?php echo $edit_faq['id']; ?>">
        <?php endif; ?>

        <div class="form-group">
            <label for="question">Question *</label>
            <input type="text" id="question" name="question" class="form-control" required
                value="<?php echo htmlspecialchars($edit_faq['question'] ?? ''); ?>" placeholder="Enter FAQ question">
        </div>

        <div class="form-group">
            <label for="answer">Answer *</label>
            <div id="answer-editor"
                style="height: 300px; background: white; border-radius: 0 0 var(--radius-md) var(--radius-md);">
                <?php echo $edit_faq['answer'] ?? ''; ?></div>
            <textarea id="answer" name="answer" required
                style="display: none;"><?php echo htmlspecialchars($edit_faq['answer'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
        </div>

        <div class="form-group">
            <label for="display_order">Display Order</label>
            <input type="number" id="display_order" name="display_order" class="form-control" style="max-width: 200px;"
                value="<?php echo $edit_faq['display_order'] ?? count($faqs) + 1; ?>" min="0" placeholder="0">
        </div>

        <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> <?php echo $edit_faq ? 'Update FAQ' : 'Add FAQ'; ?>
        </button>
    </form>
</div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">All FAQs (<?php echo count($faqs); ?>)</h2>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th style="width: 40%;">Question</th>
                    <th style="width: 40%;">Answer Preview</th>
                    <th style="width: 10%;">Order</th>
                    <th style="width: 10%;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($faqs)): ?>
                    <tr>
                        <td colspan="4" style="text-align: center; padding: 40px; color: var(--text-muted);">No FAQs found.
                            Add your first FAQ above.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($faqs as $faq): ?>
                        <tr>
                            <td style="font-weight: 600;"><?php echo htmlspecialchars($faq['question']); ?></td>
                            <td>
                                <div style="max-height: 60px; overflow: hidden; color: var(--text-muted); font-size: 13px;">
                                    <?php echo strip_tags($faq['answer']); ?>
                                </div>
                            </td>
                            <td><?php echo $faq['display_order']; ?></td>
                            <td>
                                <div style="display: flex; gap: 8px;">
                                    <a href="?edit=<?php echo $faq['id']; ?>" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form method="POST" action="" style="display: inline;"
                                        onsubmit="return confirm('Are you sure you want to delete this FAQ?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $faq['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once 'includes/admin-footer.php'; ?>