<?php 
session_start();
include('includes/head.php');

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// PIN for confirmation
$admin_pin = "1234";

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : '';
$faq_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;

// Status colors
$status_colors = array(
    'active' => 'success',
    'inactive' => 'danger'
);

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    
    // Get admin email for notification
    $adminEmailQuery = mysqli_query($conn, "SELECT email FROM users WHERE id='$admin_id'");
    $adminEmailData = mysqli_fetch_assoc($adminEmailQuery);
    $admin_email = $adminEmailData['email'] ?? 'admin@system.com';
    $admin_name_full = $_SESSION['admin_name'] ?: $admin_name;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'add_category':
                $name = mysqli_real_escape_string($conn, $_POST['name']);
                $description = mysqli_real_escape_string($conn, $_POST['description']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                $sql = "INSERT INTO faq_categories (name, description, is_active) 
                        VALUES ('$name', '$description', $is_active)";
                
                if (mysqli_query($conn, $sql)) {
                    $cat_id = mysqli_insert_id($conn);
                    logAdminActivity(
                        'FAQ Category Added',
                        "Added new FAQ category: $name",
                        'FAQ Management',
                        $cat_id,
                        'faq_categories'
                    );
                    
                    // NOTIFICATION: FAQ Category Added (ADMIN)
                    $mail_subject = "New FAQ Category Created";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>New FAQ Category Created</h2>
                                        
                                        <p class='message'>
                                            A new FAQ category has been added to the knowledge base.
                                        </p>

                                        <!-- Category Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Category ID:</strong> " . $cat_id . "<br>
                                                <strong>Category Name:</strong> " . htmlspecialchars($name) . "<br>
                                                <strong>Description:</strong> " . htmlspecialchars($description) . "<br>
                                                <strong>Status:</strong> <span style='color: " . ($is_active ? '#28a745' : '#dc3545') . ";'>" . ($is_active ? 'Active' : 'Inactive') . "</span><br>
                                                <strong>Created By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                                <strong>Creation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                            </div>
                                        </div>

                                        <!-- Admin Actions -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/admin/faq.php?category_id=" . $cat_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                View Category
                                            </a>
                                            <a href='" . $myUrl . "/admin/faq.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                Manage FAQs
                                            </a>
                                        </div>
                                    </div>";

                    require_once("../proccess/admin_mailer.php");
                    $success = "Category added successfully!";
                } else {
                    $error = "Failed to add category.";
                }
                break;
                
            case 'edit_category':
                $cat_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
                $name = mysqli_real_escape_string($conn, $_POST['name']);
                $description = mysqli_real_escape_string($conn, $_POST['description']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if ($cat_id > 0) {
                    // Get old data for notification
                    $old_sql = "SELECT * FROM faq_categories WHERE id = $cat_id";
                    $old_result = mysqli_query($conn, $old_sql);
                    $old_data = mysqli_fetch_assoc($old_result);
                    
                    $sql = "UPDATE faq_categories 
                            SET name = '$name', 
                                description = '$description', 
                                is_active = $is_active,
                                created_at = created_at
                            WHERE id = $cat_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        logAdminActivity(
                            'FAQ Category Updated',
                            "Updated FAQ category: $name",
                            'FAQ Management',
                            $cat_id,
                            'faq_categories'
                        );
                        
                        // NOTIFICATION: FAQ Category Updated (ADMIN)
                        $mail_subject = "FAQ Category Updated";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>FAQ Category Updated</h2>
                                            
                                            <p class='message'>
                                                An FAQ category has been modified by an administrator.
                                            </p>

                                            <!-- Category Update Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Category ID:</strong> " . $cat_id . "<br>
                                                    <strong>Category Name:</strong> " . htmlspecialchars($name) . "<br>
                                                    <strong>Updated By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                                    <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Status:</strong> <span style='color: " . ($is_active ? '#28a745' : '#dc3545') . ";'>" . ($is_active ? 'Active' : 'Inactive') . "</span><br>
                                                </div>
                                            </div>

                                            <!-- Changes Summary -->
                                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #495057;'>📝 Changes Made</h4>
                                                <table style='width: 100%; border-collapse: collapse;'>
                                                    <tr>
                                                        <th style='text-align: left; padding: 5px;'>Field</th>
                                                        <th style='text-align: left; padding: 5px;'>Old Value</th>
                                                        <th style='text-align: left; padding: 5px;'>New Value</th>
                                                    </tr>
                                                    <tr>
                                                        <td style='padding: 5px;'>Name</td>
                                                        <td style='padding: 5px;'>" . htmlspecialchars($old_data['name']) . "</td>
                                                        <td style='padding: 5px;'>" . htmlspecialchars($name) . "</td>
                                                    </tr>
                                                    <tr>
                                                        <td style='padding: 5px;'>Description</td>
                                                        <td style='padding: 5px;'>" . htmlspecialchars($old_data['description']) . "</td>
                                                        <td style='padding: 5px;'>" . htmlspecialchars($description) . "</td>
                                                    </tr>
                                                    <tr>
                                                        <td style='padding: 5px;'>Status</td>
                                                        <td style='padding: 5px;'>" . ($old_data['is_active'] ? 'Active' : 'Inactive') . "</td>
                                                        <td style='padding: 5px;'>" . ($is_active ? 'Active' : 'Inactive') . "</td>
                                                    </tr>
                                                </table>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/faq.php?category_id=" . $cat_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    View Category
                                                </a>
                                            </div>
                                        </div>";

                        require_once("../proccess/admin_mailer.php");
                        $success = "Category updated successfully!";
                    } else {
                        $error = "Failed to update category.";
                    }
                }
                break;
                
            case 'delete_category':
                $cat_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
                
                if ($cat_id > 0) {
                    // Get category details before deletion
                    $cat_sql = "SELECT * FROM faq_categories WHERE id = $cat_id";
                    $cat_result = mysqli_query($conn, $cat_sql);
                    $cat_data = mysqli_fetch_assoc($cat_result);
                    
                    // Check if category has FAQs
                    $check_sql = "SELECT COUNT(*) as count FROM faq_items WHERE category_id = $cat_id";
                    $check_result = mysqli_query($conn, $check_sql);
                    $check_row = mysqli_fetch_assoc($check_result);
                    
                    if ($check_row['count'] > 0) {
                        $error = "Cannot delete category. It contains " . $check_row['count'] . " FAQ items. Move or delete them first.";
                    } else {
                        $sql = "DELETE FROM faq_categories WHERE id = $cat_id";
                        
                        if (mysqli_query($conn, $sql)) {
                            logAdminActivity(
                                'FAQ Category Deleted',
                                "Deleted FAQ category: " . $cat_data['name'],
                                'FAQ Management',
                                $cat_id,
                                'faq_categories'
                            );
                            
                            // NOTIFICATION: FAQ Category Deleted (ADMIN)
                            $mail_subject = "FAQ Category Deleted";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>FAQ Category Deleted</h2>
                                                
                                                <p class='message'>
                                                    An FAQ category has been permanently deleted from the knowledge base.
                                                </p>

                                                <!-- Deletion Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Category ID:</strong> " . $cat_id . "<br>
                                                        <strong>Category Name:</strong> " . htmlspecialchars($cat_data['name']) . "<br>
                                                        <strong>Description:</strong> " . htmlspecialchars($cat_data['description']) . "<br>
                                                        <strong>Deleted By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                                        <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                                        <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PERMANENTLY DELETED</span>
                                                    </div>
                                                </div>

                                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <p style='color: #721c24;'>
                                                        <strong>⚠️ This action is irreversible.</strong><br>
                                                        The category has been permanently removed from the database.
                                                    </p>
                                                </div>
                                            </div>";

                            require_once("../proccess/admin_mailer.php");
                            $success = "Category deleted successfully!";
                        } else {
                            $error = "Failed to delete category.";
                        }
                    }
                }
                break;
                
            case 'add_faq':
                $category_id = intval($_POST['category_id']);
                $question = mysqli_real_escape_string($conn, $_POST['question']);
                $answer = mysqli_real_escape_string($conn, $_POST['answer']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Get category name
                $cat_sql = "SELECT name FROM faq_categories WHERE id = $category_id";
                $cat_result = mysqli_query($conn, $cat_sql);
                $cat_data = mysqli_fetch_assoc($cat_result);
                $category_name = $cat_data['name'] ?? 'Unknown';
                
                $sql = "INSERT INTO faq_items (category_id, question, answer, is_active) 
                        VALUES ($category_id, '$question', '$answer', $is_active)";
                
                if (mysqli_query($conn, $sql)) {
                    $faq_id = mysqli_insert_id($conn);
                    logAdminActivity(
                        'FAQ Item Added',
                        "Added new FAQ item to category: $category_name",
                        'FAQ Management',
                        $faq_id,
                        'faq_items'
                    );
                    
                    // NOTIFICATION: FAQ Item Added (ADMIN)
                    $mail_subject = "New FAQ Item Created";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>New FAQ Item Created</h2>
                                        
                                        <p class='message'>
                                            A new FAQ item has been added to the knowledge base.
                                        </p>

                                        <!-- FAQ Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>FAQ ID:</strong> " . $faq_id . "<br>
                                                <strong>Category:</strong> " . htmlspecialchars($category_name) . "<br>
                                                <strong>Question:</strong> " . htmlspecialchars($question) . "<br>
                                                <strong>Status:</strong> <span style='color: " . ($is_active ? '#28a745' : '#dc3545') . ";'>" . ($is_active ? 'Active' : 'Inactive') . "</span><br>
                                                <strong>Created By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                                <strong>Creation Date:</strong> " . date('F j, Y g:i A') . "
                                            </div>
                                        </div>

                                        <!-- Answer Preview -->
                                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #495057;'>📄 Answer Preview</h4>
                                            <p style='color: #495057;'>" . substr(htmlspecialchars($answer), 0, 200) . (strlen($answer) > 200 ? '...' : '') . "</p>
                                        </div>

                                        <!-- Admin Actions -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/admin/faq.php?category_id=" . $category_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                View Category
                                            </a>
                                        </div>
                                    </div>";

                    require_once("../proccess/admin_mailer.php");
                    $success = "FAQ item added successfully!";
                } else {
                    $error = "Failed to add FAQ item.";
                }
                break;
                
            case 'edit_faq':
                $faq_id = isset($_POST['faq_id']) ? intval($_POST['faq_id']) : 0;
                $category_id = intval($_POST['category_id']);
                $question = mysqli_real_escape_string($conn, $_POST['question']);
                $answer = mysqli_real_escape_string($conn, $_POST['answer']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if ($faq_id > 0) {
                    // Get old data
                    $old_sql = "SELECT f.*, c.name as category_name FROM faq_items f LEFT JOIN faq_categories c ON f.category_id = c.id WHERE f.id = $faq_id";
                    $old_result = mysqli_query($conn, $old_sql);
                    $old_data = mysqli_fetch_assoc($old_result);
                    
                    // Get new category name
                    $cat_sql = "SELECT name FROM faq_categories WHERE id = $category_id";
                    $cat_result = mysqli_query($conn, $cat_sql);
                    $cat_data = mysqli_fetch_assoc($cat_result);
                    $category_name = $cat_data['name'] ?? 'Unknown';
                    
                    $sql = "UPDATE faq_items 
                            SET category_id = $category_id, 
                                question = '$question', 
                                answer = '$answer', 
                                is_active = $is_active
                            WHERE id = $faq_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        logAdminActivity(
                            'FAQ Item Updated',
                            "Updated FAQ item ID: $faq_id",
                            'FAQ Management',
                            $faq_id,
                            'faq_items'
                        );
                        
                        // NOTIFICATION: FAQ Item Updated (ADMIN)
                        $mail_subject = "FAQ Item Updated";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>FAQ Item Updated</h2>
                                            
                                            <p class='message'>
                                                An FAQ item has been modified by an administrator.
                                            </p>

                                            <!-- FAQ Update Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>FAQ ID:</strong> " . $faq_id . "<br>
                                                    <strong>Category:</strong> " . htmlspecialchars($category_name) . "<br>
                                                    <strong>Question:</strong> " . htmlspecialchars($question) . "<br>
                                                    <strong>Updated By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                                    <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Status:</strong> <span style='color: " . ($is_active ? '#28a745' : '#dc3545') . ";'>" . ($is_active ? 'Active' : 'Inactive') . "</span>
                                                </div>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/faq.php?category_id=" . $category_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    View Category
                                                </a>
                                            </div>
                                        </div>";

                        require_once("../proccess/admin_mailer.php");
                        $success = "FAQ item updated successfully!";
                    } else {
                        $error = "Failed to update FAQ item.";
                    }
                }
                break;
                
            case 'delete_faq':
                $faq_id = isset($_POST['faq_id']) ? intval($_POST['faq_id']) : 0;
                
                if ($faq_id > 0) {
                    // Get FAQ details before deletion
                    $faq_sql = "SELECT f.*, c.name as category_name FROM faq_items f LEFT JOIN faq_categories c ON f.category_id = c.id WHERE f.id = $faq_id";
                    $faq_result = mysqli_query($conn, $faq_sql);
                    $faq_data = mysqli_fetch_assoc($faq_result);
                    
                    $sql = "DELETE FROM faq_items WHERE id = $faq_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        logAdminActivity(
                            'FAQ Item Deleted',
                            "Deleted FAQ item: " . substr($faq_data['question'], 0, 50) . "...",
                            'FAQ Management',
                            $faq_id,
                            'faq_items'
                        );
                        
                        // NOTIFICATION: FAQ Item Deleted (ADMIN)
                        $mail_subject = "FAQ Item Deleted";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>FAQ Item Deleted</h2>
                                            
                                            <p class='message'>
                                                An FAQ item has been permanently deleted from the knowledge base.
                                            </p>

                                            <!-- Deletion Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>FAQ ID:</strong> " . $faq_id . "<br>
                                                    <strong>Category:</strong> " . htmlspecialchars($faq_data['category_name']) . "<br>
                                                    <strong>Question:</strong> " . htmlspecialchars($faq_data['question']) . "<br>
                                                    <strong>Deleted By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                                    <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PERMANENTLY DELETED</span>
                                                </div>
                                            </div>

                                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <p style='color: #721c24;'>
                                                    <strong>⚠️ This action is irreversible.</strong><br>
                                                    The FAQ item has been permanently removed from the database.
                                                </p>
                                            </div>
                                        </div>";

                        require_once("../proccess/admin_mailer.php");
                        $success = "FAQ item deleted successfully!";
                    } else {
                        $error = "Failed to delete FAQ item.";
                    }
                }
                break;
                
            case 'reorder_categories':
                $order = $_POST['order'];
                $count = count($order);
                foreach ($order as $position => $cat_id) {
                    $pos = $position + 1;
                    mysqli_query($conn, "UPDATE faq_categories SET sort_order = $pos WHERE id = $cat_id");
                }
                logAdminActivity(
                    'FAQ Categories Reordered',
                    "Reordered $count FAQ categories",
                    'FAQ Management',
                    0,
                    'faq_categories'
                );
                
                // NOTIFICATION: FAQ Categories Reordered (ADMIN)
                $mail_subject = "FAQ Categories Reordered";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>FAQ Categories Reordered</h2>
                                    
                                    <p class='message'>
                                        The display order of FAQ categories has been updated.
                                    </p>

                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Categories Reordered:</strong> " . $count . "<br>
                                            <strong>Reordered By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                            <strong>Date:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                        </div>
                                    </div>
                                </div>";

                require_once("../proccess/admin_mailer.php");
                $success = "Categories reordered successfully!";
                break;
                
            case 'reorder_faqs':
                $order = $_POST['order'];
                $count = count($order);
                foreach ($order as $position => $faq_id) {
                    $pos = $position + 1;
                    mysqli_query($conn, "UPDATE faq_items SET sort_order = $pos WHERE id = $faq_id");
                }
                logAdminActivity(
                    'FAQ Items Reordered',
                    "Reordered $count FAQ items",
                    'FAQ Management',
                    0,
                    'faq_items'
                );
                
                // NOTIFICATION: FAQ Items Reordered (ADMIN)
                $mail_subject = "FAQ Items Reordered";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>FAQ Items Reordered</h2>
                                    
                                    <p class='message'>
                                        The display order of FAQ items has been updated.
                                    </p>

                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Items Reordered:</strong> " . $count . "<br>
                                            <strong>Reordered By:</strong> " . $admin_name_full . " (Admin ID: " . $admin_id . ")<br>
                                            <strong>Date:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                        </div>
                                    </div>
                                </div>";

                require_once("../proccess/admin_mailer.php");
                $success = "FAQ items reordered successfully!";
                break;
        }
    }
}

// Get categories
$categories_sql = "SELECT * FROM faq_categories ORDER BY sort_order ASC, name ASC";
$categories_result = mysqli_query($conn, $categories_sql);

// Get selected category FAQs
$selected_category = null;
$faqs_result = null;

if ($category_id > 0) {
    $cat_sql = "SELECT * FROM faq_categories WHERE id = $category_id";
    $cat_result = mysqli_query($conn, $cat_sql);
    $selected_category = mysqli_fetch_assoc($cat_result);
    
    $faqs_sql = "SELECT f.*, c.name as category_name 
                 FROM faq_items f 
                 LEFT JOIN faq_categories c ON f.category_id = c.id 
                 WHERE f.category_id = $category_id 
                 ORDER BY f.sort_order ASC, f.created_at DESC";
    $faqs_result = mysqli_query($conn, $faqs_sql);
}

// Get all FAQs for overview
$all_faqs_sql = "SELECT f.*, c.name as category_name, c.is_active as category_active 
                 FROM faq_items f 
                 LEFT JOIN faq_categories c ON f.category_id = c.id 
                 ORDER BY c.sort_order ASC, f.sort_order ASC, f.created_at DESC 
                 LIMIT 50";
$all_faqs_result = mysqli_query($conn, $all_faqs_sql);
?>

<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-question-circle me-2"></i>FAQ Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
												<i class="fas fa-folder-plus me-1"></i> Add Category
											</button>
											<button class="btn btn-success ms-2" data-bs-toggle="modal" data-bs-target="#addFaqModal">
												<i class="fas fa-plus-circle me-1"></i> Add FAQ
											</button>
										</div>
									</div>
									<div class="box-body">
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Stats Cards -->
										<div class="row mb-20">
											<?php
											// Get stats
											$total_cats = mysqli_num_rows(mysqli_query($conn, "SELECT COUNT(*) as total FROM faq_categories"));
											$active_cats = mysqli_num_rows(mysqli_query($conn, "SELECT COUNT(*) as total FROM faq_categories WHERE is_active = 1"));
											$total_faqs = mysqli_num_rows(mysqli_query($conn, "SELECT COUNT(*) as total FROM faq_items"));
											$active_faqs = mysqli_num_rows(mysqli_query($conn, "SELECT COUNT(*) as total FROM faq_items WHERE is_active = 1"));
											?>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $total_cats; ?></h1>
														<p class="text-white mb-0">Categories</p>
														<small class="text-white-50"><?php echo $active_cats; ?> active</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $total_faqs; ?></h1>
														<p class="text-white mb-0">FAQ Items</p>
														<small class="text-white-50"><?php echo $active_faqs; ?> active</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $active_cats; ?></h1>
														<p class="text-white mb-0">Active Categories</p>
														<small class="text-white-50"><?php echo round(($active_cats/$total_cats)*100, 0); ?>% of total</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $active_faqs; ?></h1>
														<p class="text-white mb-0">Active FAQs</p>
														<small class="text-white-50"><?php echo round(($active_faqs/$total_faqs)*100, 0); ?>% of total</small>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Tabs -->
										<ul class="nav nav-tabs" role="tablist">
											<li class="nav-item">
												<a class="nav-link active" data-bs-toggle="tab" href="#categories">Categories</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#all_faqs">All FAQs</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#reorder">Reorder</a>
											</li>
										</ul>
										
										<div class="tab-content mt-3">
											<!-- Categories Tab -->
											<div class="tab-pane fade show active" id="categories">
												<div class="row">
													<div class="col-md-4">
														<div class="box">
															<div class="box-header">
																<h5 class="box-title"><i class="fas fa-folder me-2"></i>FAQ Categories</h5>
															</div>
															<div class="box-body p-0">
																<div class="list-group list-group-flush">
																	<?php if (mysqli_num_rows($categories_result) > 0): ?>
																		<?php while ($cat = mysqli_fetch_assoc($categories_result)): ?>
																			<?php
																			$is_active = $cat['is_active'];
																			$active_class = $is_active ? 'active' : '';
																			$active_badge = $is_active ? 'success' : 'danger';
																			$active_text = $is_active ? 'Active' : 'Inactive';
																			$faq_count = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM faq_items WHERE category_id = {$cat['id']}"));
																			?>
																			<a href="?category_id=<?php echo $cat['id']; ?>" 
																			   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center <?php echo ($category_id == $cat['id']) ? 'active' : ''; ?>">
																				<div>
																					<h6 class="mb-1"><?php echo htmlspecialchars($cat['name']); ?></h6>
																					<small class="text-mute"><?php echo htmlspecialchars($cat['description']); ?></small>
																				</div>
																				<div class="text-end">
																					<span class="badge bg-<?php echo $active_badge; ?>"><?php echo $active_text; ?></span>
																					<span class="badge bg-primary ms-1"><?php echo $faq_count; ?> FAQs</span>
																				</div>
																			</a>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<div class="list-group-item text-center py-20">
																			<i class="fas fa-folder-open fa-2x text-mute mb-3"></i>
																			<p class="text-mute mb-0">No categories found</p>
																		</div>
																	<?php endif; ?>
																</div>
															</div>
														</div>
													</div>
													
													<div class="col-md-8">
														<?php if ($selected_category): ?>
															<div class="box">
																<div class="box-header">
																	<div class="d-flex justify-content-between align-items-center">
																		<div>
																			<h5 class="box-title">
																				<i class="fas fa-folder me-2"></i>
																				<?php echo htmlspecialchars($selected_category['name']); ?>
																			</h5>
																			<p class="text-mute mb-0"><?php echo htmlspecialchars($selected_category['description']); ?></p>
																		</div>
																		<div>
																			<button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#editCategoryModal" 
																					data-cat-id="<?php echo $selected_category['id']; ?>"
																					data-cat-name="<?php echo htmlspecialchars($selected_category['name']); ?>"
																					data-cat-desc="<?php echo htmlspecialchars($selected_category['description']); ?>"
																					data-cat-active="<?php echo $selected_category['is_active']; ?>">
																				<i class="fas fa-edit me-1"></i> Edit
																			</button>
																			<button class="btn btn-sm btn-danger ms-1" onclick="confirmDeleteCategory(<?php echo $selected_category['id']; ?>)">
																				<i class="fas fa-trash me-1"></i> Delete
																			</button>
																		</div>
																	</div>
																</div>
																<div class="box-body">
																	<?php if (mysqli_num_rows($faqs_result) > 0): ?>
																		<div class="accordion" id="faqAccordion">
																			<?php $faq_index = 0; ?>
																			<?php while ($faq = mysqli_fetch_assoc($faqs_result)): ?>
																				<?php
																				$is_active = $faq['is_active'];
																				$active_badge = $is_active ? 'success' : 'danger';
																				$active_text = $is_active ? 'Active' : 'Inactive';
																				?>
																				<div class="accordion-item">
																					<h2 class="accordion-header" id="heading<?php echo $faq_index; ?>">
																						<button class="accordion-button <?php echo ($faq_index > 0) ? 'collapsed' : ''; ?>" 
																								type="button" data-bs-toggle="collapse" 
																								data-bs-target="#collapse<?php echo $faq_index; ?>">
																							<div class="d-flex justify-content-between w-100">
																								<span>
																									<?php echo htmlspecialchars($faq['question']); ?>
																									<span class="badge bg-<?php echo $active_badge; ?> ms-2"><?php echo $active_text; ?></span>
																								</span>
																								<small class="text-mute me-3">ID: <?php echo $faq['id']; ?></small>
																							</div>
																						</button>
																					</h2>
																					<div id="collapse<?php echo $faq_index; ?>" 
																						 class="accordion-collapse collapse <?php echo ($faq_index == 0) ? 'show' : ''; ?>" 
																						 data-bs-parent="#faqAccordion">
																						<div class="accordion-body">
																							<div class="d-flex justify-content-between mb-3">
																								<div>
																									<span class="badge bg-primary">FAQ ID: <?php echo $faq['id']; ?></span>
																									<span class="badge bg-secondary ms-1">Created: <?php echo date('M d, Y', strtotime($faq['created_at'])); ?></span>
																								</div>
																								<div>
																									<button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#editFaqModal"
																											data-faq-id="<?php echo $faq['id']; ?>"
																											data-category-id="<?php echo $faq['category_id']; ?>"
																											data-question="<?php echo htmlspecialchars($faq['question']); ?>"
																											data-answer="<?php echo htmlspecialchars($faq['answer']); ?>"
																											data-is-active="<?php echo $faq['is_active']; ?>">
																										<i class="fas fa-edit me-1"></i> Edit
																									</button>
																									<button class="btn btn-sm btn-danger ms-1" onclick="confirmDeleteFaq(<?php echo $faq['id']; ?>)">
																										<i class="fas fa-trash me-1"></i> Delete
																									</button>
																								</div>
																							</div>
																							<div class="bg-light p-3 rounded">
																								<?php echo nl2br(htmlspecialchars($faq['answer'])); ?>
																							</div>
																						</div>
																					</div>
																				</div>
																				<?php $faq_index++; ?>
																			<?php endwhile; ?>
																		</div>
																	<?php else: ?>
																		<div class="text-center py-20">
																			<i class="fas fa-question-circle fa-3x text-mute mb-3"></i>
																			<h5>No FAQs in this category</h5>
																			<p class="text-mute">Add FAQ items to this category</p>
																			<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addFaqModal">
																				<i class="fas fa-plus-circle me-1"></i> Add FAQ
																			</button>
																		</div>
																	<?php endif; ?>
																</div>
															</div>
														<?php else: ?>
															<div class="box">
																<div class="box-body text-center py-20">
																	<i class="fas fa-folder-open fa-3x text-mute mb-3"></i>
																	<h5>Select a Category</h5>
																	<p class="text-mute">Choose a category from the left to view and manage its FAQs</p>
																</div>
															</div>
														<?php endif; ?>
													</div>
												</div>
											</div>
											
											<!-- All FAQs Tab -->
											<div class="tab-pane fade" id="all_faqs">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-list me-2"></i>All FAQ Items</h5>
														<div class="box-controls">
															<input type="text" class="form-control" id="searchFaqs" placeholder="Search FAQs...">
														</div>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover" id="faqsTable">
																<thead>
																	<tr>
																		<th>ID</th>
																		<th>Question</th>
																		<th>Category</th>
																		<th>Status</th>
																		<th>Created</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($all_faqs_result) > 0): ?>
																		<?php while ($faq = mysqli_fetch_assoc($all_faqs_result)): ?>
																			<?php
																			$is_active = $faq['is_active'];
																			$category_active = $faq['category_active'];
																			$status_color = $is_active ? 'success' : 'danger';
																			$status_text = $is_active ? 'Active' : 'Inactive';
																			$category_color = $category_active ? 'success' : 'danger';
																			?>
																			<tr>
																				<td><?php echo $faq['id']; ?></td>
																				<td>
																					<div class="text-truncate" style="max-width: 300px;">
																						<?php echo htmlspecialchars($faq['question']); ?>
																					</div>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $category_color; ?>">
																						<?php echo htmlspecialchars($faq['category_name']); ?>
																					</span>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $status_color; ?>"><?php echo $status_text; ?></span>
																				</td>
																				<td><?php echo date('M d, Y', strtotime($faq['created_at'])); ?></td>
																				<td>
																					<div class="btn-group">
																						<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																							<i class="fas fa-cog"></i>
																						</button>
																						<div class="dropdown-menu">
																							<a class="dropdown-item" href="?category_id=<?php echo $faq['category_id']; ?>">
																								<i class="fas fa-eye me-2"></i> View in Category
																							</a>
																							<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#editFaqModal"
																							   data-faq-id="<?php echo $faq['id']; ?>"
																							   data-category-id="<?php echo $faq['category_id']; ?>"
																							   data-question="<?php echo htmlspecialchars($faq['question']); ?>"
																							   data-answer="<?php echo htmlspecialchars($faq['answer']); ?>"
																							   data-is-active="<?php echo $faq['is_active']; ?>">
																								<i class="fas fa-edit me-2"></i> Edit
																							</a>
																							<div class="dropdown-divider"></div>
																							<a class="dropdown-item text-danger" href="#" onclick="confirmDeleteFaq(<?php echo $faq['id']; ?>)">
																								<i class="fas fa-trash me-2"></i> Delete
																							</a>
																						</div>
																					</div>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="6" class="text-center py-20">
																				<i class="fas fa-question-circle fa-2x text-mute mb-3"></i>
																				<h5>No FAQs found</h5>
																				<p class="text-mute">Add FAQ items to get started</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
											
											<!-- Reorder Tab -->
											<div class="tab-pane fade" id="reorder">
												<div class="row">
													<div class="col-md-6">
														<div class="box">
															<div class="box-header">
																<h5 class="box-title"><i class="fas fa-sort me-2"></i>Reorder Categories</h5>
																<p class="text-mute mb-0">Drag and drop to reorder categories</p>
															</div>
															<div class="box-body">
																<form method="POST" id="reorderCategoriesForm">
																	<input type="hidden" name="action_type" value="reorder_categories">
																	<input type="hidden" name="admin_pin" value="<?php echo $admin_pin; ?>">
																	
																	<ul class="list-group sortable" id="categoriesSortable">
																		<?php
																		mysqli_data_seek($categories_result, 0);
																		while ($cat = mysqli_fetch_assoc($categories_result)):
																		?>
																			<li class="list-group-item d-flex justify-content-between align-items-center">
																				<div>
																					<i class="fas fa-grip-vertical text-mute me-3 handle"></i>
																					<?php echo htmlspecialchars($cat['name']); ?>
																					<small class="text-mute ms-2">(<?php echo $cat['sort_order']; ?>)</small>
																				</div>
																				<input type="hidden" name="order[]" value="<?php echo $cat['id']; ?>">
																				<span class="badge bg-primary">
																					<?php echo mysqli_num_rows(mysqli_query($conn, "SELECT id FROM faq_items WHERE category_id = {$cat['id']}")); ?> FAQs
																				</span>
																			</li>
																		<?php endwhile; ?>
																	</ul>
																	
																	<div class="mt-3">
																		<button type="submit" class="btn btn-primary">
																			<i class="fas fa-save me-1"></i> Save Order
																		</button>
																	</div>
																</form>
															</div>
														</div>
													</div>
													
													<div class="col-md-6">
														<div class="box">
															<div class="box-header">
																<h5 class="box-title"><i class="fas fa-sort-alpha-down me-2"></i>Reorder FAQ Items</h5>
																<p class="text-mute mb-0">Select a category to reorder its FAQs</p>
															</div>
															<div class="box-body">
																<div class="mb-3">
																	<label class="form-label">Select Category</label>
																	<select class="form-control" id="categorySelect" onchange="loadFaqsForReorder(this.value)">
																		<option value="">-- Select Category --</option>
																		<?php
																		mysqli_data_seek($categories_result, 0);
																		while ($cat = mysqli_fetch_assoc($categories_result)):
																		?>
																			<option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
																		<?php endwhile; ?>
																	</select>
																</div>
																
																<div id="faqsReorderContainer">
																	<!-- FAQs will be loaded here -->
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Adding Category -->
		<div class="modal fade" id="addCategoryModal" tabindex="-1" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addCategoryModalLabel">Add FAQ Category</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="add_category">
							
							<div class="mb-3">
								<label class="form-label">Category Name <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="name" required>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description</label>
								<textarea class="form-control" name="description" rows="3"></textarea>
							</div>
							
							<div class="mb-3">
								<div class="form-check">
									<input class="form-check-input" type="checkbox" name="is_active" id="catActive" checked>
									<label class="form-check-label" for="catActive">Active Category</label>
								</div>
								<small class="text-mute">Inactive categories won't be shown to users</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Add Category</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Editing Category -->
		<div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="editCategoryModalLabel">Edit FAQ Category</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="edit_category">
							<input type="hidden" name="category_id" id="editCatId">
							
							<div class="mb-3">
								<label class="form-label">Category Name <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="name" id="editCatName" required>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description</label>
								<textarea class="form-control" name="description" id="editCatDesc" rows="3"></textarea>
							</div>
							
							<div class="mb-3">
								<div class="form-check">
									<input class="form-check-input" type="checkbox" name="is_active" id="editCatActive">
									<label class="form-check-label" for="editCatActive">Active Category</label>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update Category</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adding FAQ -->
		<div class="modal fade" id="addFaqModal" tabindex="-1" aria-labelledby="addFaqModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addFaqModalLabel">Add FAQ Item</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="add_faq">
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Category <span class="text-danger">*</span></label>
										<select class="form-control" name="category_id" required>
											<option value="">-- Select Category --</option>
											<?php
											mysqli_data_seek($categories_result, 0);
											while ($cat = mysqli_fetch_assoc($categories_result)):
											?>
												<option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
											<?php endwhile; ?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Status</label>
										<select class="form-control" name="is_active">
											<option value="1">Active</option>
											<option value="0">Inactive</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Question <span class="text-danger">*</span></label>
								<textarea class="form-control" name="question" rows="3" required placeholder="Enter the question..."></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Answer <span class="text-danger">*</span></label>
								<textarea class="form-control" name="answer" rows="6" required placeholder="Enter the answer..."></textarea>
								<small class="text-mute">You can use HTML tags for formatting</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
							
							<!-- Live Preview -->
							<div class="card mt-3">
								<div class="card-header">
									<h6 class="mb-0"><i class="fas fa-eye me-2"></i>Live Preview</h6>
								</div>
								<div class="card-body">
									<div id="faqPreview">
										<p class="text-mute">Preview will appear here...</p>
									</div>
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Add FAQ</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Editing FAQ -->
		<div class="modal fade" id="editFaqModal" tabindex="-1" aria-labelledby="editFaqModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="editFaqModalLabel">Edit FAQ Item</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="edit_faq">
							<input type="hidden" name="faq_id" id="editFaqId">
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Category <span class="text-danger">*</span></label>
										<select class="form-control" name="category_id" id="editCategoryId" required>
											<option value="">-- Select Category --</option>
											<?php
											mysqli_data_seek($categories_result, 0);
											while ($cat = mysqli_fetch_assoc($categories_result)):
											?>
												<option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
											<?php endwhile; ?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Status</label>
										<select class="form-control" name="is_active" id="editFaqActive">
											<option value="1">Active</option>
											<option value="0">Inactive</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Question <span class="text-danger">*</span></label>
								<textarea class="form-control" name="question" id="editQuestion" rows="3" required></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Answer <span class="text-danger">*</span></label>
								<textarea class="form-control" name="answer" id="editAnswer" rows="6" required></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
							
							<!-- Live Preview -->
							<div class="card mt-3">
								<div class="card-header">
									<h6 class="mb-0"><i class="fas fa-eye me-2"></i>Live Preview</h6>
								</div>
								<div class="card-body">
									<div id="editFaqPreview">
										<p class="text-mute">Preview will appear here...</p>
									</div>
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update FAQ</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Hidden Forms for Deletions -->
		<form method="POST" id="deleteCategoryForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_category">
			<input type="hidden" name="category_id" id="deleteCatId">
			<input type="hidden" name="admin_pin" id="deleteCatPin">
		</form>
		
		<form method="POST" id="deleteFaqForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_faq">
			<input type="hidden" name="faq_id" id="deleteFaqId">
			<input type="hidden" name="admin_pin" id="deleteFaqPin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<!-- SortableJS -->
		<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable for FAQs
			$('#faqsTable').DataTable({
				"pageLength": 25,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Quick search for FAQs table
			$('#searchFaqs').on('keyup', function() {
				$('#faqsTable').DataTable().search($(this).val()).draw();
			});
			
			// Edit Category Modal
			$('#editCategoryModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var catId = button.data('cat-id');
				var catName = button.data('cat-name');
				var catDesc = button.data('cat-desc');
				var catActive = button.data('cat-active');
				var modal = $(this);
				
				modal.find('#editCatId').val(catId);
				modal.find('#editCatName').val(catName);
				modal.find('#editCatDesc').val(catDesc);
				modal.find('#editCatActive').prop('checked', catActive == 1);
				modal.find('.modal-title').text('Edit Category: ' + catName);
			});
			
			// Edit FAQ Modal
			$('#editFaqModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var faqId = button.data('faq-id');
				var categoryId = button.data('category-id');
				var question = button.data('question');
				var answer = button.data('answer');
				var isActive = button.data('is-active');
				var modal = $(this);
				
				modal.find('#editFaqId').val(faqId);
				modal.find('#editCategoryId').val(categoryId);
				modal.find('#editQuestion').val(question);
				modal.find('#editAnswer').val(answer);
				modal.find('#editFaqActive').val(isActive);
				modal.find('.modal-title').text('Edit FAQ #' + faqId);
				
				// Update preview
				updateFaqPreview(question, answer, '#editFaqPreview');
			});
			
			// Live preview for Add FAQ
			$('#addFaqModal textarea[name="question"], #addFaqModal textarea[name="answer"]').on('input', function() {
				var question = $('#addFaqModal textarea[name="question"]').val();
				var answer = $('#addFaqModal textarea[name="answer"]').val();
				updateFaqPreview(question, answer, '#faqPreview');
			});
			
			// Live preview for Edit FAQ
			$('#editFaqModal textarea[name="question"], #editFaqModal textarea[name="answer"]').on('input', function() {
				var question = $('#editFaqModal textarea[name="question"]').val();
				var answer = $('#editFaqModal textarea[name="answer"]').val();
				updateFaqPreview(question, answer, '#editFaqPreview');
			});
			
			// Initialize sortable for categories
			var categoriesSortable = Sortable.create(document.getElementById('categoriesSortable'), {
				handle: '.handle',
				animation: 150,
				onUpdate: function() {
					// Update hidden inputs order
					$('#categoriesSortable input[name="order[]"]').each(function(index) {
						$(this).val($(this).closest('li').find('input[name="order[]"]').val());
					});
				}
			});
		});
		
		// Update FAQ Preview
		function updateFaqPreview(question, answer, previewId) {
			if (question || answer) {
				var preview = '<div class="faq-preview">';
				if (question) {
					preview += '<h6 class="text-primary mb-2">' + question + '</h6>';
				}
				if (answer) {
					preview += '<div class="bg-light p-3 rounded">' + answer.replace(/\n/g, '<br>') + '</div>';
				}
				preview += '</div>';
				$(previewId).html(preview);
			} else {
				$(previewId).html('<p class="text-mute">Preview will appear here...</p>');
			}
		}
		
		// Load FAQs for reordering
		function loadFaqsForReorder(categoryId) {
			if (!categoryId) {
				$('#faqsReorderContainer').html('<div class="alert alert-info">Please select a category</div>');
				return;
			}
			
			$.ajax({
				url: 'ajax/get_faqs_for_reorder.php',
				type: 'GET',
				data: { category_id: categoryId },
				success: function(response) {
					var data = JSON.parse(response);
					if (data.success) {
						var html = '<form method="POST" id="reorderFaqsForm">';
						html += '<input type="hidden" name="action_type" value="reorder_faqs">';
						html += '<input type="hidden" name="admin_pin" value="<?php echo $admin_pin; ?>">';
						html += '<ul class="list-group sortable" id="faqsSortable">';
						
						data.faqs.forEach(function(faq, index) {
							html += '<li class="list-group-item d-flex justify-content-between align-items-center">';
							html += '<div>';
							html += '<i class="fas fa-grip-vertical text-mute me-3 handle"></i>';
							html += faq.question.substring(0, 50) + (faq.question.length > 50 ? '...' : '');
							html += '</div>';
							html += '<input type="hidden" name="order[]" value="' + faq.id + '">';
							html += '<span class="badge bg-' + (faq.is_active ? 'success' : 'danger') + '">';
							html += faq.is_active ? 'Active' : 'Inactive';
							html += '</span>';
							html += '</li>';
						});
						
						html += '</ul>';
						html += '<div class="mt-3">';
						html += '<button type="submit" class="btn btn-primary">';
						html += '<i class="fas fa-save me-1"></i> Save Order';
						html += '</button>';
						html += '</div>';
						html += '</form>';
						
						$('#faqsReorderContainer').html(html);
						
						// Initialize sortable for FAQs
						var faqsSortable = Sortable.create(document.getElementById('faqsSortable'), {
							handle: '.handle',
							animation: 150,
							onUpdate: function() {
								// Update hidden inputs order
								$('#faqsSortable input[name="order[]"]').each(function(index) {
									$(this).val($(this).closest('li').find('input[name="order[]"]').val());
								});
							}
						});
					} else {
						$('#faqsReorderContainer').html('<div class="alert alert-info">' + data.message + '</div>');
					}
				}
			});
		}
		
		// Confirm Delete Category
		function confirmDeleteCategory(catId) {
			Swal.fire({
				title: 'Delete Category?',
				html: `
					<p>This action cannot be undone. All FAQs in this category will be orphaned.</p>
					<p class="text-danger"><strong>Warning:</strong> Make sure the category is empty before deleting.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalCatPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Category',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalCatPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteCatId').value = catId;
					document.getElementById('deleteCatPin').value = result.value.pin;
					document.getElementById('deleteCategoryForm').submit();
				}
			});
		}
		
		// Confirm Delete FAQ
		function confirmDeleteFaq(faqId) {
			Swal.fire({
				title: 'Delete FAQ Item?',
				html: `
					<p>This action cannot be undone. The FAQ item will be permanently deleted.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalFaqPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete FAQ',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalFaqPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteFaqId').value = faqId;
					document.getElementById('deleteFaqPin').value = result.value.pin;
					document.getElementById('deleteFaqForm').submit();
				}
			});
		}
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_faq_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total_cats);
						$('.bg-gradient-success .fw-500').text(stats.total_faqs);
						$('.bg-gradient-warning .fw-500').text(stats.active_cats);
						$('.bg-gradient-info .fw-500').text(stats.active_faqs);
						
						// Update percentages
						$('.bg-gradient-primary .text-white-50').text(stats.active_cats + ' active');
						$('.bg-gradient-success .text-white-50').text(stats.active_faqs + ' active');
						$('.bg-gradient-warning .text-white-50').text(Math.round((stats.active_cats/stats.total_cats)*100) + '% of total');
						$('.bg-gradient-info .text-white-50').text(Math.round((stats.active_faqs/stats.total_faqs)*100) + '% of total');
					}
				}
			});
		}, 30000); // 30 seconds
		</script>
		
		<style>
		.list-group-item.active {
			background-color: #0d6efd;
			border-color: #0d6efd;
		}
		.accordion-button:not(.collapsed) {
			background-color: rgba(13, 110, 253, 0.1);
			color: #0d6efd;
		}
		.handle {
			cursor: move;
		}
		.sortable-ghost {
			opacity: 0.5;
			background: #f8f9fa;
		}
		.faq-preview {
			font-family: Arial, sans-serif;
		}
		.faq-preview h6 {
			font-weight: 600;
			color: #333;
		}
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
		}
		</style>
		
	</body>
</html>