<?php
/**
 * ADMIN FAQs MANAGEMENT PAGE V2.0
 * File: admin/faqs.php
 * - Drag and drop reordering
 * - Grouped by category
 * - Fixed flash messages
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "FAQs Management";
$active_menu = "faqs";

// Initialize models
$db = Database::getInstance();
$faq_model = new Faq();

// Handle AJAX reorder
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reorder') {
    header('Content-Type: application/json');
    
    $order = $_POST['order'] ?? [];
    
    try {
        foreach ($order as $index => $id) {
            $faq_model->update((int)$id, ['display_order' => $index]);
        }
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'create':
            $question = trim($_POST['question'] ?? '');
            $answer = trim($_POST['answer'] ?? '');
            $category = trim($_POST['category'] ?? 'general');
            $is_featured = isset($_POST['is_featured']) ? 1 : 0;
            
            if (empty($question) || empty($answer)) {
                flash('error', 'Question and answer are required');
            } else {
                try {
                    $faq_model->create([
                        'question' => $question,
                        'answer' => $answer,
                        'category' => $category,
                        'is_featured' => $is_featured,
                        'is_active' => 1,
                        'display_order' => 999
                    ]);
                    
                    flash('success', 'FAQ created successfully');
                    header('Location: faqs.php');
                    exit;
                } catch (Exception $e) {
                    flash('error', 'Error creating FAQ: ' . $e->getMessage());
                }
            }
            break;
            
        case 'update':
            $id = (int)$_POST['id'];
            $question = trim($_POST['question'] ?? '');
            $answer = trim($_POST['answer'] ?? '');
            $category = trim($_POST['category'] ?? 'general');
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $is_featured = isset($_POST['is_featured']) ? 1 : 0;
            
            if (empty($question) || empty($answer)) {
                flash('error', 'Question and answer are required');
            } else {
                try {
                    $faq_model->update($id, [
                        'question' => $question,
                        'answer' => $answer,
                        'category' => $category,
                        'is_active' => $is_active,
                        'is_featured' => $is_featured
                    ]);
                    
                    flash('success', 'FAQ updated successfully');
                    header('Location: faqs.php');
                    exit;
                } catch (Exception $e) {
                    flash('error', 'Error updating FAQ: ' . $e->getMessage());
                }
            }
            break;
            
        case 'delete':
            $id = (int)$_POST['id'];
            
            try {
                $faq_model->delete($id);
                flash('success', 'FAQ deleted successfully');
                header('Location: faqs.php');
                exit;
            } catch (Exception $e) {
                flash('error', 'Error deleting FAQ: ' . $e->getMessage());
            }
            break;
    }
}

// Get all FAQs grouped by category
$all_faqs = $faq_model->getAll();
$faqs_by_category = [];
foreach ($all_faqs as $faq) {
    $faqs_by_category[$faq['category']][] = $faq;
}

// Get FAQ statistics
$stats = $faq_model->getStats();

// Get categories
$categories = ['general', 'customer', 'booking', 'payment', 'vendor', 'returns', 'security', 'support'];

// Flash messages
$success_message = get_flash('success');
$error_message = get_flash('error');

// Include header
include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
            <i class="fas fa-tags"></i> FAQs
        </h1>
        <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
            <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
            <span>/</span>
            <span>FAQs</span>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>
                <?= htmlspecialchars(is_array($success_message) ? $success_message['message'] : $success_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?= htmlspecialchars(is_array($error_message) ? $error_message['message'] : $error_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <p class="text-muted mb-1">Total FAQs</p>
                                <h3 class="mb-0"><?= $stats['total_faqs'] ?></h3>
                            </div>
                            <i class="fas fa-question-circle fa-2x text-primary"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <p class="text-muted mb-1">Active</p>
                                <h3 class="mb-0"><?= $stats['active_faqs'] ?></h3>
                            </div>
                            <i class="fas fa-check-circle fa-2x text-success"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <p class="text-muted mb-1">Featured</p>
                                <h3 class="mb-0"><?= $stats['featured_faqs'] ?></h3>
                            </div>
                            <i class="fas fa-star fa-2x text-warning"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <p class="text-muted mb-1">Categories</p>
                                <h3 class="mb-0"><?= $stats['total_categories'] ?></h3>
                            </div>
                            <i class="fas fa-tags fa-2x text-info"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Action Button -->
        <div style="margin-bottom: 30px;">
            <button type="button" onclick="showCreateModal()" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add New FAQ
            </button>
        </div>
        
        <!-- FAQs Grouped by Category -->
        <?php if (empty($faqs_by_category)): ?>
            <div style="background: white; border-radius: 12px; padding: 50px; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <i class="fas fa-question-circle fa-3x mb-3 text-muted"></i>
                <h4>No FAQs found</h4>
                <p class="text-muted">Create your first FAQ to get started</p>
                <button type="button" onclick="showCreateModal()" class="btn btn-primary mt-3">
                    <i class="fas fa-plus"></i> Create First FAQ
                </button>
            </div>
        <?php else: ?>
            <?php foreach ($faqs_by_category as $category => $faqs): ?>
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                        <h5 class="mb-0">
                            <i class="fas fa-folder-open me-2"></i>
                            <?= ucfirst($category) ?> (<?= count($faqs) ?>)
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-hover mb-0">
                            <thead style="background: #f8f9fa;">
                                <tr>
                                    <th style="width: 30px; padding: 12px 15px;">
                                        <i class="fas fa-grip-vertical text-muted"></i>
                                    </th>
                                    <th style="padding: 12px 15px;">Question</th>
                                    <th style="width: 100px; padding: 12px 15px; text-align: center;">Status</th>
                                    <th style="width: 80px; padding: 12px 15px; text-align: center;">Featured</th>
                                    <th style="width: 150px; padding: 12px 15px; text-align: center;">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="faq-sortable" data-category="<?= $category ?>">
                                <?php foreach ($faqs as $faq): ?>
                                    <tr data-id="<?= $faq['id'] ?>" style="cursor: move;">
                                        <td style="padding: 15px;">
                                            <i class="fas fa-grip-vertical text-muted"></i>
                                        </td>
                                        <td style="padding: 15px;">
                                            <div style="font-weight: 600;">
                                                <?= htmlspecialchars(str_limit($faq['question'], 100)) ?>
                                            </div>
                                            <small class="text-muted">
                                                <?= htmlspecialchars(str_limit($faq['answer'], 150)) ?>
                                            </small>
                                        </td>
                                        <td style="padding: 15px; text-align: center;">
                                            <?php if ($faq['is_active']): ?>
                                                <span class="badge bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="padding: 15px; text-align: center;">
                                            <?php if ($faq['is_featured']): ?>
                                                <i class="fas fa-star text-warning fa-lg"></i>
                                            <?php else: ?>
                                                <i class="far fa-star text-muted"></i>
                                            <?php endif; ?>
                                        </td>
                                        <td style="padding: 15px; text-align: center;">
                                            <button onclick="editFaq(<?= $faq['id'] ?>)" 
                                                    class="btn btn-sm btn-primary" 
                                                    title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="deleteFaq(<?= $faq['id'] ?>)" 
                                                    class="btn btn-sm btn-danger" 
                                                    title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Create/Edit FAQ Modal -->
<div id="faqModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 50px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 700px; max-height: 90vh; overflow-y: auto;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
            <h3 id="modalTitle" style="margin: 0; font-size: 20px; font-weight: 600;">Add New FAQ</h3>
            <button onclick="closeModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
        </div>
        
        <form method="POST" id="faqForm">
            <input type="hidden" name="action" value="create" id="formAction">
            <input type="hidden" name="id" value="" id="faqId">
            
            <div class="form-group mb-3">
                <label class="form-label fw-bold">Question *</label>
                <input type="text" 
                       name="question" 
                       id="question"
                       class="form-control" 
                       placeholder="Enter FAQ question"
                       required>
            </div>
            
            <div class="form-group mb-3">
                <label class="form-label fw-bold">Answer *</label>
                <textarea name="answer" 
                          id="answer"
                          class="form-control" 
                          rows="5" 
                          placeholder="Enter detailed answer"
                          required></textarea>
            </div>
            
            <div class="form-group mb-3">
                <label class="form-label fw-bold">Category</label>
                <select name="category" id="category" class="form-control">
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat ?>"><?= ucfirst($cat) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group mb-3" id="editOnlyFields" style="display: none;">
                <div class="form-check">
                    <input type="checkbox" 
                           name="is_active" 
                           id="is_active"
                           class="form-check-input" 
                           value="1">
                    <label class="form-check-label" for="is_active">Active</label>
                </div>
            </div>
            
            <div class="form-group mb-3">
                <div class="form-check">
                    <input type="checkbox" 
                           name="is_featured" 
                           id="is_featured"
                           class="form-check-input" 
                           value="1">
                    <label class="form-check-label" for="is_featured">
                        <i class="fas fa-star text-warning"></i> Feature on Homepage
                    </label>
                </div>
            </div>
            
            <div class="d-flex gap-2 justify-content-end">
                <button type="button" onclick="closeModal()" class="btn btn-secondary">
                    Cancel
                </button>
                <button type="submit" class="btn btn-primary">
                    <span id="submitBtnText">Create FAQ</span>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Include jQuery and jQuery UI for drag and drop -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<script>
// Initialize sortable
$(document).ready(function() {
    $('.faq-sortable').sortable({
        handle: '.fa-grip-vertical',
        cursor: 'move',
        opacity: 0.6,
        update: function(event, ui) {
            const category = $(this).data('category');
            const order = [];
            
            $(this).find('tr').each(function() {
                order.push($(this).data('id'));
            });
            
            // Save new order via AJAX
            $.post('faqs.php', {
                action: 'reorder',
                order: order
            }, function(response) {
                if (response.success) {
                    // Optional: Show success message
                    console.log('Order updated');
                } else {
                    alert('Failed to update order');
                }
            }, 'json');
        }
    });
});

function showCreateModal() {
    document.getElementById('faqModal').style.display = 'block';
    document.getElementById('modalTitle').textContent = 'Add New FAQ';
    document.getElementById('formAction').value = 'create';
    document.getElementById('submitBtnText').textContent = 'Create FAQ';
    document.getElementById('editOnlyFields').style.display = 'none';
    document.getElementById('faqForm').reset();
    document.body.style.overflow = 'hidden';
}

function editFaq(id) {
    fetch(`faq-get.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const faq = data.faq;
                
                document.getElementById('modalTitle').textContent = 'Edit FAQ';
                document.getElementById('formAction').value = 'update';
                document.getElementById('submitBtnText').textContent = 'Update FAQ';
                document.getElementById('faqId').value = faq.id;
                document.getElementById('question').value = faq.question;
                document.getElementById('answer').value = faq.answer;
                document.getElementById('category').value = faq.category;
                document.getElementById('is_active').checked = faq.is_active == 1;
                document.getElementById('is_featured').checked = faq.is_featured == 1;
                
                document.getElementById('editOnlyFields').style.display = 'block';
                document.getElementById('faqModal').style.display = 'block';
                document.body.style.overflow = 'hidden';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading FAQ data');
        });
}

function deleteFaq(id) {
    if (confirm('Are you sure you want to delete this FAQ?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

function closeModal() {
    document.getElementById('faqModal').style.display = 'none';
    document.body.style.overflow = 'auto';
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('faqModal');
    if (event.target === modal) {
        closeModal();
    }
}
</script>

<style>
.modal {
    animation: fadeIn 0.3s;
}

.modal-content {
    animation: slideIn 0.3s;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateY(-50px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.faq-sortable tr {
    background: white;
}

.faq-sortable tr:hover {
    background: #f8f9fa;
}

.ui-sortable-helper {
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}
</style>

<?php include '../templates/layouts/admin/footer.php'; ?>