<?php
/**
 * Admin FAQs
 * Digital Product Store
 */

$page_title = 'FAQs';
include __DIR__ . '/includes/header.php';

$error = '';
$success = '';

// Handle delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $faq_id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM faqs WHERE id = ?");
    if ($stmt->execute([$faq_id])) {
        set_flash_message('FAQ deleted successfully.', 'success');
    } else {
        set_flash_message('Failed to delete FAQ.', 'danger');
    }
    header('Location: faqs.php');
    exit;
}

// Handle status toggle
if (isset($_GET['toggle']) && is_numeric($_GET['toggle'])) {
    $faq_id = (int)$_GET['toggle'];
    $stmt = $pdo->prepare("UPDATE faqs SET is_active = NOT is_active WHERE id = ?");
    if ($stmt->execute([$faq_id])) {
        set_flash_message('FAQ status updated.', 'success');
    }
    header('Location: faqs.php');
    exit;
}

// Handle add/edit FAQ
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $faq_id = isset($_POST['faq_id']) ? (int)$_POST['faq_id'] : 0;
    $question = sanitize($_POST['question'] ?? '');
    $answer = sanitize($_POST['answer'] ?? '');
    $category = sanitize($_POST['category'] ?? 'General');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    if (empty($question)) {
        $error = 'Question is required.';
    } elseif (empty($answer)) {
        $error = 'Answer is required.';
    } else {
        if ($faq_id) {
            // Update
            $stmt = $pdo->prepare("UPDATE faqs SET question = ?, answer = ?, category = ?, sort_order = ?, is_active = ? WHERE id = ?");
            if ($stmt->execute([$question, $answer, $category, $sort_order, $is_active, $faq_id])) {
                $success = 'FAQ updated successfully.';
            } else {
                $error = 'Failed to update FAQ.';
            }
        } else {
            // Insert
            $stmt = $pdo->prepare("INSERT INTO faqs (question, answer, category, sort_order, is_active) VALUES (?, ?, ?, ?, ?)");
            if ($stmt->execute([$question, $answer, $category, $sort_order, $is_active])) {
                $success = 'FAQ created successfully.';
            } else {
                $error = 'Failed to create FAQ.';
            }
        }
    }
}

// Get FAQs
$stmt = $pdo->query("SELECT * FROM faqs ORDER BY category, sort_order, id");
$faqs = $stmt->fetchAll();

// Get unique categories
$categories = array_unique(array_column($faqs, 'category'));

// Get FAQ for edit
$edit_faq = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM faqs WHERE id = ?");
    $stmt->execute([(int)$_GET['edit']]);
    $edit_faq = $stmt->fetch();
}
?>

<div class="row">
    <div class="col-lg-8">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h4 class="mb-0">FAQs</h4>
        </div>
        
        <?php foreach ($categories as $cat): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0"><?php echo sanitize($cat); ?></h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table mb-0">
                        <thead>
                            <tr>
                                <th>Question</th>
                                <th>Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $cat_faqs = array_filter($faqs, function($f) use ($cat) { return $f['category'] === $cat; });
                            if (empty($cat_faqs)): 
                            ?>
                            <tr>
                                <td colspan="4" class="text-center py-3">No FAQs in this category.</td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($cat_faqs as $faq): ?>
                            <tr>
                                <td><?php echo truncate(sanitize($faq['question']), 60); ?></td>
                                <td><?php echo $faq['sort_order']; ?></td>
                                <td>
                                    <a href="?toggle=<?php echo $faq['id']; ?>" class="badge bg-<?php echo $faq['is_active'] ? 'success' : 'secondary'; ?> text-decoration-none">
                                        <?php echo $faq['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </a>
                                </td>
                                <td>
                                    <a href="?edit=<?php echo $faq['id']; ?>" class="btn btn-sm btn-outline-primary btn-action" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete=<?php echo $faq['id']; ?>" class="btn btn-sm btn-outline-danger btn-action" title="Delete" onclick="return confirmDelete('Are you sure you want to delete this FAQ?')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0"><?php echo $edit_faq ? 'Edit FAQ' : 'Add New FAQ'; ?></h5>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                
                <form method="POST">
                    <?php if ($edit_faq): ?>
                    <input type="hidden" name="faq_id" value="<?php echo $edit_faq['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Question *</label>
                        <input type="text" name="question" class="form-control" required
                               value="<?php echo $edit_faq ? sanitize($edit_faq['question']) : ''; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Answer *</label>
                        <textarea name="answer" class="form-control" rows="5" required><?php echo $edit_faq ? sanitize($edit_faq['answer']) : ''; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Category</label>
                        <input type="text" name="category" class="form-control" list="categories"
                               value="<?php echo $edit_faq ? sanitize($edit_faq['category']) : 'General'; ?>">
                        <datalist id="categories">
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo sanitize($cat); ?>">
                            <?php endforeach; ?>
                        </datalist>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="sort_order" class="form-control" min="0"
                               value="<?php echo $edit_faq ? $edit_faq['sort_order'] : '0'; ?>">
                    </div>
                    
                    <div class="form-check mb-3">
                        <input type="checkbox" name="is_active" class="form-check-input" id="is_active" 
                               <?php echo (!$edit_faq || $edit_faq['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> <?php echo $edit_faq ? 'Update' : 'Create'; ?> FAQ
                        </button>
                    </div>
                    
                    <?php if ($edit_faq): ?>
                    <div class="d-grid mt-2">
                        <a href="faqs.php" class="btn btn-outline-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>
</div>

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