<?php
// Enable error reporting
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '../logs/php_errors.log');

require_once '../includes/db_connect.php';

// Check admin session
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit;
}

// Handle question deletion
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    try {
        $stmt = $pdo->prepare("DELETE FROM questions WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $_SESSION['success'] = "Question deleted successfully";
        header("Location: questions.php");
        exit;
    } catch (PDOException $e) {
        error_log("Error deleting question: " . $e->getMessage());
        $_SESSION['error'] = "Failed to delete question";
        header("Location: questions.php");
        exit;
    }
}

// Fetch all questions with subject names
$questions = [];
try {
    $questions = $pdo->query("
        SELECT q.*, s.name as subject_name 
        FROM questions q
        JOIN subjects s ON q.subject_id = s.id
        ORDER BY s.name, q.question_number
    ")->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching questions: " . $e->getMessage());
    $_SESSION['error'] = "Failed to load questions";
}

// Fetch all subjects for filter
$subjects = [];
try {
    $subjects = $pdo->query("SELECT id, name FROM subjects ORDER BY name")->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching subjects: " . $e->getMessage());
}

// Filter questions by subject if requested
if (isset($_GET['subject_id']) && !empty($_GET['subject_id'])) {
    $subjectId = $_GET['subject_id'];
    try {
        $stmt = $pdo->prepare("
            SELECT q.*, s.name as subject_name 
            FROM questions q
            JOIN subjects s ON q.subject_id = s.id
            WHERE q.subject_id = ?
            ORDER BY q.question_number
        ");
        $stmt->execute([$subjectId]);
        $questions = $stmt->fetchAll();
    } catch (PDOException $e) {
        error_log("Error filtering questions: " . $e->getMessage());
        $_SESSION['error'] = "Failed to filter questions";
    }
}

// Fetch admin username for the navbar
$admin_name = 'Admin';
try {
    $stmt = $pdo->prepare("SELECT username FROM admins WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($admin) {
        $admin_name = $admin['username'];
    }
} catch (PDOException $e) {
    error_log("Error fetching admin username: " . $e->getMessage());
}

// Get counts for dashboard
$stats = [
    'total_questions' => count($questions),
    'total_subjects' => count($subjects)
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Questions - Verbum Dei Academy & College Entrance Exam Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <style>
        :root {
            --primary: #28a745; /* Light green */
            --secondary: #6c757d;
            --success: #28a745;
            --info: #17a2b8;
            --warning: #ffc107;
            --danger: #dc3545;
            --light: #f8f9fa;
            --dark: #343a40;
            --light-green: #d4edda;
        }
        
        body {
            background-color: #f8f9fc;
            font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .dashboard-header {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            border-left: 5px solid var(--primary);
        }
        
        .card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        }
        
        .table-responsive {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table thead th {
            background-color: var(--primary);
            color: white;
            border: none;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(40, 167, 69, 0.05);
        }
        
        .section-title {
            position: relative;
            padding-bottom: 10px;
            margin-bottom: 1.5rem;
        }
        
        .section-title:after {
            content: "";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 50px;
            height: 3px;
            background: var(--primary);
        }
        
        .navbar {
            background: white;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            border-radius: 15px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        
        .breadcrumb {
            background: transparent;
            padding: 0;
        }
        
        .breadcrumb-item a {
            color: var(--primary);
            text-decoration: none;
        }
        
        .action-btns .btn {
            border-radius: 50px;
            padding: 0.375rem 0.75rem;
        }
        
        .stat-card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
            transition: all 0.3s;
            overflow: hidden;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1.5rem 0 rgba(58, 59, 69, 0.2);
        }
        
        .stat-card .card-icon {
            font-size: 2rem;
            opacity: 0.3;
            position: absolute;
            right: 20px;
            top: 20px;
        }
        
        .stat-card.bg-primary {
            background: linear-gradient(135deg, var(--primary) 0%, #218838 100%) !important;
            color: white;
        }
        
        .stat-card.bg-success {
            background: linear-gradient(135deg, var(--success) 0%, #218838 100%) !important;
            color: white;
        }
        
        .question-text {
            max-width: 400px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .subject-badge {
            background-color: var(--light-green);
            color: var(--dark);
        }
    </style>
</head>
<body>
    <!-- Top Navigation Bar -->
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <a class="navbar-brand fw-bold" href="admin_dashboard.php" style="color: var(--primary);">
                <i class="bi bi-mortarboard me-2"></i>Verbum Dei Academy & College Entrance Exam Portal
            </a>
            <div class="d-flex align-items-center">
                <div class="me-3">
                    <span class="text-muted">Welcome,</span>
                    <span class="fw-bold ms-1"><?php echo htmlspecialchars($admin_name); ?></span>
                </div>
                <div class="user-avatar me-2">
                    <?php echo strtoupper(substr($admin_name, 0, 1)); ?>
                </div>
                <a href="../logout.php" class="btn btn-sm btn-outline-danger">
                    <i class="bi bi-box-arrow-right"></i>
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <!-- Dashboard Header -->
        <div class="dashboard-header animate__animated animate__fadeIn">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h1 class="h3 fw-bold text-dark mb-2">
                        <i class="bi bi-question-circle me-2" style="color: var(--primary);"></i>
                        Manage Questions
                    </h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="admin_dashboard.php"><i class="bi bi-house-door"></i> Dashboard</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Questions</li>
                        </ol>
                    </nav>
                </div>
                <div class="col-md-6 text-md-end">
                    <a href="question_form.php" class="btn btn-primary">
                        <i class="bi bi-plus-circle me-2"></i>Add New Question
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger animate__animated animate__shakeX mb-4">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                <?= $_SESSION['error']; unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success animate__animated animate__fadeIn mb-4">
                <i class="bi bi-check-circle-fill me-2"></i>
                <?= $_SESSION['success']; unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>

        <!-- Questions Stats -->
        <div class="row g-4 mb-4">
            <div class="col-xl-6 col-md-6">
                <div class="stat-card card bg-primary text-white animate__animated animate__fadeInUp">
                    <div class="card-body">
                        <i class="bi bi-question-square card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Total Questions</h5>
                        <h2 class="mb-0 fw-bold"><?= $stats['total_questions'] ?></h2>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-6 col-md-6">
                <div class="stat-card card bg-success text-white animate__animated animate__fadeInUp animate__delay-1s">
                    <div class="card-body">
                        <i class="bi bi-book card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Subjects Available</h5>
                        <h2 class="mb-0 fw-bold"><?= $stats['total_subjects'] ?></h2>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Form -->
        <div class="card shadow-sm mb-4 animate__animated animate__fadeIn">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-8">
                        <label for="subject_id" class="form-label">Filter by Subject</label>
                        <select class="form-select" id="subject_id" name="subject_id">
                            <option value="">All Subjects</option>
                            <?php foreach ($subjects as $subject): ?>
                                <option value="<?= $subject['id'] ?>" <?= isset($_GET['subject_id']) && $_GET['subject_id'] == $subject['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($subject['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="bi bi-funnel me-1"></i> Filter
                        </button>
                        <?php if (isset($_GET['subject_id'])): ?>
                            <a href="questions.php" class="btn btn-outline-secondary">
                                <i class="bi bi-x-circle me-1"></i> Clear
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Questions Table -->
        <div class="card shadow-sm animate__animated animate__fadeIn">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Question</th>
                                <th>Subject</th>
                                <th>Options</th>
                                <th>Answer</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($questions)): ?>
                                <tr>
                                    <td colspan="6" class="text-center py-4 text-muted">
                                        <i class="bi bi-info-circle fs-4 d-block mb-2"></i>
                                        No questions found. <?= isset($_GET['subject_id']) ? 'Try changing your filter' : 'Click "Add New Question" to create one' ?>.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($questions as $question): ?>
                                    <tr class="animate__animated animate__fadeIn">
                                        <td><?= htmlspecialchars($question['question_number']) ?></td>
                                        <td class="question-text" title="<?= htmlspecialchars($question['question_text']) ?>">
                                            <?= htmlspecialchars($question['question_text']) ?>
                                        </td>
                                        <td>
                                            <span class="badge subject-badge rounded-pill">
                                                <?= htmlspecialchars($question['subject_name']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php 
                                                $options = [
                                                    $question['option_a'],
                                                    $question['option_b'],
                                                    $question['option_c'],
                                                    $question['option_d']
                                                ];
                                                echo count(array_filter($options, function($opt) { return !empty($opt); }));
                                            ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-success">
                                                <?= strtoupper($question['correct_answer']) ?>
                                            </span>
                                        </td>
                                        <td class="text-end action-btns">
                                            <a href="question_form.php?id=<?= $question['id'] ?>" class="btn btn-sm btn-outline-primary me-1" title="Edit">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <a href="?action=delete&id=<?= $question['id'] ?>" class="btn btn-sm btn-outline-danger" title="Delete" onclick="return confirm('Are you sure you want to delete this question? This action cannot be undone.');">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Management Tips -->
        <div class="card shadow-sm mt-4 animate__animated animate__fadeIn animate__delay-1s">
            <div class="card-body">
                <h5 class="card-title text-primary">
                    <i class="bi bi-lightbulb me-2"></i>Question Management Tips
                </h5>
                <ul class="mb-0">
                    <li>Questions are organized by subject and question number</li>
                    <li>Use the filter to view questions for a specific subject</li>
                    <li>Add questions systematically to maintain proper numbering</li>
                    <li>Edit questions to update content or correct answers</li>
                    <li>Export questions to backup or share with other educators</li>
                </ul>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Add animation to table rows on scroll
            const observer = new IntersectionObserver((entries) => {
                entries.forEach((entry, index) => {
                    if (entry.isIntersecting) {
                        setTimeout(() => {
                            entry.target.classList.add('animate__fadeIn');
                        }, index * 100);
                    }
                });
            }, {threshold: 0.1});
            
            document.querySelectorAll('tbody tr').forEach(row => {
                observer.observe(row);
            });
            
            // Show full question text on hover
            const questionCells = document.querySelectorAll('.question-text');
            questionCells.forEach(cell => {
                cell.addEventListener('mouseenter', function() {
                    this.style.whiteSpace = 'normal';
                    this.style.overflow = 'visible';
                });
                cell.addEventListener('mouseleave', function() {
                    this.style.whiteSpace = 'nowrap';
                    this.style.overflow = 'hidden';
                });
            });
        });
    </script>
</body>
</html>