<?php
/**
 * FAQs Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $question = sanitizeInput($_POST['question'] ?? '');
    $answer = sanitizeInput($_POST['answer'] ?? '');
    $category = sanitizeInput($_POST['category'] ?? '');
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    if (empty($question) || empty($answer)) {
        $message = 'Question and answer are required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO faqs (question, answer, category, display_order, status)
                VALUES (:question, :answer, :category, :order, :status)
            ");
            $stmt->execute([
                ':question' => $question,
                ':answer' => $answer,
                ':category' => $category,
                ':order' => $displayOrder,
                ':status' => $status
            ]);
            $message = 'FAQ created successfully!';
        } elseif ($action === 'update' && $id > 0) {
            $stmt = $pdo->prepare("
                UPDATE faqs SET question = :question, answer = :answer, category = :category, 
                display_order = :order, status = :status WHERE id = :id
            ");
            $stmt->execute([
                ':question' => $question,
                ':answer' => $answer,
                ':category' => $category,
                ':order' => $displayOrder,
                ':status' => $status,
                ':id' => $id
            ]);
            $message = 'FAQ updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $pdo->prepare("DELETE FROM faqs WHERE id = :id")->execute([':id' => $id]);
    $message = 'FAQ deleted successfully!';
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM faqs WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $editItem = $stmt->fetch();
}

// Get all FAQs
$faqs = $pdo->query("
    SELECT * FROM faqs ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'FAQs';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 1.5rem;">
                <!-- Form -->
                <div class="card slide-up">
                    <div class="card-header">
                        <h3 class="card-title"><?php echo $editItem ? 'Edit' : 'Add'; ?> FAQ</h3>
                    </div>
                    <form method="POST">
                        <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                        <?php if ($editItem): ?>
                            <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="form-group">
                            <label class="form-label">Question *</label>
                            <input type="text" name="question" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['question'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Answer *</label>
                            <textarea name="answer" class="form-control" rows="6" required><?php echo htmlspecialchars($editItem['answer'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Category</label>
                            <input type="text" name="category" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['category'] ?? ''); ?>"
                                   placeholder="e.g., General, Services, Pricing">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Display Order</label>
                            <input type="number" name="display_order" class="form-control" 
                                   value="<?php echo $editItem['display_order'] ?? 0; ?>" min="0">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                        
                        <div style="display: flex; gap: 0.75rem;">
                            <button type="submit" class="btn btn-primary"><?php echo $editItem ? 'Update' : 'Create'; ?></button>
                            <?php if ($editItem): ?>
                                <a href="faqs.php" class="btn btn-secondary">Cancel</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
                
                <!-- List -->
                <div class="card slide-up" style="animation-delay: 0.2s">
                    <div class="card-header">
                        <h3 class="card-title">All FAQs</h3>
                    </div>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php if (empty($faqs)): ?>
                            <p style="text-align: center; padding: 2rem; color: var(--text-secondary);">No FAQs yet</p>
                        <?php else: ?>
                            <?php foreach ($faqs as $faq): ?>
                            <div style="padding: 1rem; border-bottom: 1px solid var(--border-color);">
                                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 0.5rem;">
                                            <?php echo htmlspecialchars($faq['question']); ?>
                                        </div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">
                                            <?php echo htmlspecialchars(substr($faq['answer'], 0, 100)); ?><?php echo strlen($faq['answer']) > 100 ? '...' : ''; ?>
                                        </div>
                                        <?php if ($faq['category']): ?>
                                            <span class="badge badge-info" style="margin-top: 0.5rem; display: inline-block;">
                                                <?php echo htmlspecialchars($faq['category']); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <div style="display: flex; gap: 0.5rem; margin-left: 1rem;">
                                        <span class="badge badge-<?php echo $faq['status'] === 'active' ? 'success' : 'danger'; ?>">
                                            <?php echo ucfirst($faq['status']); ?>
                                        </span>
                                    </div>
                                </div>
                                <div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
                                    <a href="?edit=<?php echo $faq['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                    <a href="?delete=<?php echo $faq['id']; ?>" 
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('Delete this FAQ?')">Delete</a>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

