<?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;
    }
}

// Handle delete all questions for an exam
if (isset($_GET['delete_all']) && isset($_GET['exam_id'])) {
    $exam_id = (int)$_GET['exam_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM questions WHERE exam_id = ?");
        $stmt->execute([$exam_id]);
        $_SESSION['success'] = "All questions for this exam deleted successfully";
        header("Location: questions.php");
        exit;
    } catch (PDOException $e) {
        error_log("Error deleting all questions: " . $e->getMessage());
        $_SESSION['error'] = "Failed to delete questions";
        header("Location: questions.php");
        exit;
    }
}

// Fetch all exams for filter
$exams = [];
try {
    $exams = $pdo->query("SELECT id, exam_name FROM exams ORDER BY exam_name")->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching exams: " . $e->getMessage());
}

// 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());
}

// Initialize filter variables
$examFilter = $_GET['exam_id'] ?? '';
$subjectFilter = $_GET['subject_id'] ?? '';
$questions = [];

// Build base query
$query = "
    SELECT q.*, s.name as subject_name, e.exam_name 
    FROM questions q
    JOIN subjects s ON q.subject_id = s.id
    JOIN exams e ON q.exam_id = e.id
    WHERE 1=1
";

$params = [];

// Apply filters
if (!empty($examFilter)) {
    $query .= " AND q.exam_id = ?";
    $params[] = $examFilter;
}

if (!empty($subjectFilter)) {
    $query .= " AND q.subject_id = ?";
    $params[] = $subjectFilter;
}

$query .= " ORDER BY e.exam_name, s.name, q.question_number";

// Fetch filtered questions
try {
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $questions = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching questions: " . $e->getMessage());
    $_SESSION['error'] = "Failed to load questions";
}

// Get question counts by exam for the exam list
$examCounts = [];
try {
    $stmt = $pdo->query("
        SELECT e.id, e.exam_name, COUNT(q.id) as question_count 
        FROM exams e 
        LEFT JOIN questions q ON e.id = q.exam_id 
        GROUP BY e.id 
        ORDER BY e.exam_name
    ");
    $examCounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching exam counts: " . $e->getMessage());
}

// 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),
    'total_exams' => count($exams)
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Questions - 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;
            --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 thead th {
            background-color: var(--primary);
            color: white;
            border: none;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(40, 167, 69, 0.05);
        }
        
        .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;
        }
        
        .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;
        }
        
        .stat-card.bg-info {
            background: linear-gradient(135deg, var(--info) 0%, #138496 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);
        }
        
        .exam-card {
            transition: transform 0.2s ease;
            border-left: 4px solid var(--primary);
        }
        
        .exam-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: var(--dark);
            font-weight: 500;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary);
            border-bottom: 3px solid var(--primary);
            background: transparent;
        }
    </style>
</head>
<body>
    <!-- Top Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
        <div class="container">
            <a class="navbar-brand fw-bold text-primary" href="admin_dashboard.php">
                <i class="bi bi-mortarboard me-2"></i>Exam Portal
            </a>
            <div class="d-flex align-items-center">
                <div class="me-3">
                    <span class="text-muted small">Welcome,</span>
                    <span class="fw-bold ms-1 small"><?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 py-4">
        <!-- Dashboard Header -->
        <div class="dashboard-header">
            <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 text-primary"></i>
                        Question Management
                    </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-4 col-md-4">
                <div class="stat-card card bg-primary text-white">
                    <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-4 col-md-4">
                <div class="stat-card card bg-success text-white">
                    <div class="card-body">
                        <i class="bi bi-book card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Subjects</h5>
                        <h2 class="mb-0 fw-bold"><?= $stats['total_subjects'] ?></h2>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-4 col-md-4">
                <div class="stat-card card bg-info text-white">
                    <div class="card-body">
                        <i class="bi bi-journal-text card-icon"></i>
                        <h5 class="card-title text-uppercase mb-2">Exams</h5>
                        <h2 class="mb-0 fw-bold"><?= $stats['total_exams'] ?></h2>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs Navigation -->
        <ul class="nav nav-tabs mb-4" id="questionsTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="exams-tab" data-bs-toggle="tab" data-bs-target="#exams" type="button" role="tab">
                    <i class="bi bi-journal-text me-1"></i> Exams
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="questions-tab" data-bs-toggle="tab" data-bs-target="#questions" type="button" role="tab">
                    <i class="bi bi-question-circle me-1"></i> Questions
                </button>
            </li>
        </ul>

        <div class="tab-content" id="questionsTabsContent">
            <!-- Exams Tab -->
            <div class="tab-pane fade show active" id="exams" role="tabpanel">
                <div class="row">
                    <?php foreach ($examCounts as $exam): ?>
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card exam-card h-100">
                                <div class="card-body">
                                    <h5 class="card-title"><?= htmlspecialchars($exam['exam_name']) ?></h5>
                                    <p class="card-text text-muted">
                                        <i class="bi bi-question-circle me-1"></i>
                                        <?= $exam['question_count'] ?> question(s)
                                    </p>
                                </div>
                                <div class="card-footer bg-transparent">
                                    <div class="d-flex justify-content-between">
                                        <a href="questions.php?exam_id=<?= $exam['id'] ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-eye me-1"></i> View
                                        </a>
                                        <a href="question_form.php?exam_id=<?= $exam['id'] ?>" class="btn btn-sm btn-outline-success">
                                            <i class="bi bi-pencil me-1"></i> Edit All
                                        </a>
                                        <a href="question_form.php?exam_id=<?= $exam['id'] ?>&add_more=true" class="btn btn-sm btn-outline-info">
                                            <i class="bi bi-plus-circle me-1"></i> Add More
                                        </a>
                                        <?php if ($exam['question_count'] > 0): ?>
                                            <a href="questions.php?delete_all=1&exam_id=<?= $exam['id'] ?>" 
                                               class="btn btn-sm btn-outline-danger"
                                               onclick="return confirm('Are you sure you want to delete ALL questions for this exam? This action cannot be undone.')">
                                                <i class="bi bi-trash me-1"></i> Delete All
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Questions Tab -->
            <div class="tab-pane fade" id="questions" role="tabpanel">
                <!-- Filter Form -->
                <div class="card shadow-sm mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-5">
                                <label for="exam_id" class="form-label">Filter by Exam</label>
                                <select class="form-select" id="exam_id" name="exam_id">
                                    <option value="">All Exams</option>
                                    <?php foreach ($exams as $exam): ?>
                                        <option value="<?= $exam['id'] ?>" <?= $examFilter == $exam['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($exam['exam_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-5">
                                <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'] ?>" <?= $subjectFilter == $subject['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($subject['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2 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 ($examFilter || $subjectFilter): ?>
                                    <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">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Question</th>
                                        <th>Exam</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="7" class="text-center py-4 text-muted">
                                                <i class="bi bi-info-circle fs-4 d-block mb-2"></i>
                                                No questions found. <?= ($examFilter || $subjectFilter) ? 'Try changing your filter' : 'Click "Add New Question" to create one' ?>.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($questions as $question): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($question['question_number']) ?></td>
                                                <td class="question-text" title="<?= htmlspecialchars($question['question_text']) ?>">
                                                    <?= htmlspecialchars($question['question_text']) ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info">
                                                        <?= htmlspecialchars($question['exam_name']) ?>
                                                    </span>
                                                </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_option']) ?>
                                                    </span>
                                                </td>
                                                <td class="text-end action-btns">
                                                    <a href="question_form.php?edit=1&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>
            </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() {
            // 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'; 
                });
            });

            // Remember active tab
            const activeTab = localStorage.getItem('activeQuestionsTab');
            if (activeTab) {
                const tab = new bootstrap.Tab(document.querySelector(activeTab));
                tab.show();
            }

            // Save active tab on change
            document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
                tab.addEventListener('shown.bs.tab', function (e) {
                    localStorage.setItem('activeQuestionsTab', e.target.getAttribute('data-bs-target'));
                });
            });
        });
    </script>
</body>
</html>