<?php
// Include header (which includes all dependencies)
include 'includes/header.php';

// Make sure user is admin
if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_PERMISSION_DENIED'] ?? 'You do not have permission to manage FAQs', 'danger');
    redirectTo('faq');
    exit;
}

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token first
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
        redirectTo('faq');
        exit;
    }

    // Get the action
    $action = isset($_POST['action']) ? sanitizeInput($_POST['action']) : '';

    try {
        // Handle add FAQ
        if ($action === 'add') {
            $question = isset($_POST['question']) ? sanitizeInput($_POST['question']) : '';
            $answer = isset($_POST['answer']) ? cleanHTML($_POST['answer']) : '';
            $category = isset($_POST['category']) ? sanitizeInput($_POST['category']) : '';
            $currentDateTime = getCurrentDateTime();

            if (empty($question) || empty($answer)) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_FAQ_QUESTION_ANSWER_REQUIRED'] ?? 'Both question and answer are required', 'danger');
            } else {
                $stmt = $pdo->prepare("INSERT INTO faqs (question, answer, category, created_at, updated_at) VALUES (?, ?, ?, ?, ?)");
                if ($stmt->execute([$question, $answer, $category, $currentDateTime, $currentDateTime])) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_FAQ_ADDED_SUCCESS'] ?? 'FAQ added successfully');
                } else {
                    $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_FAQ_ERROR_ADDING_PREFIX'] ?? 'Error adding FAQ: ') . implode(' ', $stmt->errorInfo()), 'danger');
                }
            }
        }
        // Handle edit FAQ
        elseif ($action === 'edit') {
            $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
            $question = isset($_POST['question']) ? sanitizeInput($_POST['question']) : '';
            $answer = isset($_POST['answer']) ? cleanHTML($_POST['answer']) : '';
            $category = isset($_POST['category']) ? sanitizeInput($_POST['category']) : '';

            if (empty($question) || empty($answer)) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_FAQ_QUESTION_ANSWER_REQUIRED'] ?? 'Both question and answer are required', 'danger');
            } else {
                $currentDateTime = getCurrentDateTime();
                $stmt = $pdo->prepare("UPDATE faqs SET question = ?, answer = ?, category = ?, updated_at = ? WHERE id = ?");
                if ($stmt->execute([$question, $answer, $category, $currentDateTime, $id])) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_FAQ_UPDATED_SUCCESS'] ?? 'FAQ updated successfully');
                } else {
                    $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_FAQ_ERROR_UPDATING_PREFIX'] ?? 'Error updating FAQ: ') . implode(' ', $stmt->errorInfo()), 'danger');
                }
            }
        }
        // Handle delete FAQ
        elseif ($action === 'delete') {
            $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;

            $stmt = $pdo->prepare("DELETE FROM faqs WHERE id = ?");
            if ($stmt->execute([$id])) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_FAQ_DELETED_SUCCESS'] ?? 'FAQ deleted successfully');
            } else {
                $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_FAQ_ERROR_DELETING_PREFIX'] ?? 'Error deleting FAQ: ') . implode(' ', $stmt->errorInfo()), 'danger');
            }
        } else {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_ACTION'] ?? 'Invalid action', 'danger');
        }
    } catch (PDOException $e) {
        $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_DATABASE_ERROR_PREFIX'] ?? 'Database error: ') . $e->getMessage(), 'danger');
    }
}

// Redirect back to the FAQ page through the router
redirectTo('faq');
exit;
?>