<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';

require_admin();

$pageTitle = 'FAQs';
$success = '';
$error = '';
$editFaq = null;

if (isset($_GET['created'])) {
    $success = 'FAQ created successfully.';
}

if (isset($_GET['updated'])) {
    $success = 'FAQ updated successfully.';
}

if (isset($_GET['deleted'])) {
    $success = 'FAQ deleted successfully.';
}

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];

    $stmt = $pdo->prepare("SELECT * FROM faqs WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editFaq = $stmt->fetch();

    if (!$editFaq) {
        $error = 'FAQ not found.';
    }
}

if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("DELETE FROM faqs WHERE id = ?");
    $stmt->execute([$deleteId]);

    redirect(ADMIN_URL . '/faqs.php?deleted=1');
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $faqId = (int) ($_POST['faq_id'] ?? 0);
        $question = trim($_POST['question'] ?? '');
        $answer = trim($_POST['answer'] ?? '');
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        $status = $_POST['status'] ?? 'active';

        if ($question === '') {
            $error = 'Question is required.';
        } elseif ($answer === '') {
            $error = 'Answer is required.';
        } elseif (!in_array($status, ['active', 'inactive'], true)) {
            $error = 'Invalid status.';
        } else {
            if ($faqId > 0) {
                $stmt = $pdo->prepare("
                    UPDATE faqs
                    SET question = ?,
                        answer = ?,
                        sort_order = ?,
                        status = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    $question,
                    $answer,
                    $sortOrder,
                    $status,
                    $faqId
                ]);

                redirect(ADMIN_URL . '/faqs.php?updated=1');
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO faqs (
                        question,
                        answer,
                        sort_order,
                        status
                    ) VALUES (?, ?, ?, ?)
                ");

                $stmt->execute([
                    $question,
                    $answer,
                    $sortOrder,
                    $status
                ]);

                redirect(ADMIN_URL . '/faqs.php?created=1');
            }
        }
    }
}

$faqs = $pdo->query("
    SELECT *
    FROM faqs
    ORDER BY sort_order ASC, id DESC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>FAQs</h1>
            <div class="admin-user">Create and manage website FAQ content.</div>
        </div>

        <?php if ($editFaq): ?>
            <a href="<?= e(ADMIN_URL); ?>/faqs.php" class="admin-btn admin-btn-light">Cancel Edit</a>
        <?php endif; ?>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2><?= $editFaq ? 'Edit FAQ' : 'Add New FAQ'; ?></h2>

        <form method="POST">
            <?= csrf_field(); ?>

            <input type="hidden" name="faq_id" value="<?= e($editFaq['id'] ?? 0); ?>">

            <div class="admin-field">
                <label>Question *</label>
                <input type="text" name="question" value="<?= e($editFaq['question'] ?? ''); ?>" required>
            </div>

            <div class="admin-field">
                <label>Answer *</label>
                <textarea name="answer" required><?= e($editFaq['answer'] ?? ''); ?></textarea>
            </div>

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Sort Order</label>
                    <input type="number" name="sort_order" value="<?= e($editFaq['sort_order'] ?? 0); ?>">
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= ($editFaq['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?= ($editFaq['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
            </div>

            <button type="submit" class="admin-btn">
                <?= $editFaq ? 'Update FAQ' : 'Create FAQ'; ?>
            </button>
        </form>
    </section>

    <section class="admin-panel">
        <h2>All FAQs</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Sort</th>
                    <th>Question</th>
                    <th>Answer</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$faqs): ?>
                    <tr>
                        <td colspan="5">No FAQs created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($faqs as $faq): ?>
                    <tr>
                        <td><?= e($faq['sort_order']); ?></td>
                        <td><strong><?= e($faq['question']); ?></strong></td>
                        <td><?= e(mb_strimwidth($faq['answer'], 0, 120, '...')); ?></td>
                        <td><?= e(ucfirst($faq['status'])); ?></td>
                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/faqs.php?edit=<?= e($faq['id']); ?>">Edit</a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/faqs.php?delete=<?= e($faq['id']); ?>"
                                onclick="return confirm('Delete this FAQ?');"
                            >
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>