<?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;
}

// Check if exam_id is provided
if (!isset($_GET['exam_id']) || !is_numeric($_GET['exam_id'])) {
    die("Invalid exam ID");
}

$exam_id = (int)$_GET['exam_id'];

// Fetch exam details
$exam = [];
try {
    $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
    $stmt->execute([$exam_id]);
    $exam = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$exam) {
        die("Exam not found");
    }
} catch (PDOException $e) {
    error_log("Error fetching exam: " . $e->getMessage());
    die("Failed to load exam details");
}

// Fetch all questions for this exam with subject names
$questions = [];
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.exam_id = ?
        ORDER BY s.name, q.question_number
    ");
    $stmt->execute([$exam_id]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching questions: " . $e->getMessage());
    die("Failed to load questions");
}

// Fetch admin username
$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());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Questions - <?= htmlspecialchars($exam['exam_name']) ?> - 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">
    <style>
        :root {
            --primary: #28a745;
            --secondary: #6c757d;
            --success: #28a745;
            --info: #17a2b8;
            --warning: #ffc107;
            --danger: #dc3545;
        }
        
        body {
            background-color: #f8f9fc;
            font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            padding: 20px;
        }
        
        .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);
            margin-bottom: 1.5rem;
        }
        
        .question-card {
            border-left: 4px solid var(--primary);
            margin-bottom: 1rem;
        }
        
        .subject-header {
            background: linear-gradient(135deg, var(--primary) 0%, #218838 100%);
            color: white;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .option-correct {
            background-color: #d4edda;
            border-left: 4px solid var(--success);
        }
        
        .option-incorrect {
            background-color: #f8d7da;
        }
        
        .print-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }
        
        @media print {
            .print-btn, .header .btn {
                display: none !important;
            }
            
            .card {
                box-shadow: none !important;
                border: 1px solid #dee2e6 !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- Header -->
        <div class="header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="h3 fw-bold text-dark mb-2">
                        <i class="bi bi-journal-text me-2 text-primary"></i>
                        <?= htmlspecialchars($exam['exam_name']) ?>
                    </h1>
                    <p class="text-muted mb-0">
                        <strong>Date:</strong> <?= date('F j, Y', strtotime($exam['exam_date'])) ?> | 
                        <strong>Duration:</strong> <?= $exam['duration_minutes'] ?> minutes | 
                        <strong>Questions:</strong> <?= count($questions) ?>
                    </p>
                    <?php if ($exam['description']): ?>
                        <p class="text-muted mt-2"><?= htmlspecialchars($exam['description']) ?></p>
                    <?php endif; ?>
                </div>
                <div class="col-md-4 text-md-end">
                    <button onclick="window.print()" class="btn btn-primary me-2">
                        <i class="bi bi-printer me-1"></i> Print
                    </button>
                    <button onclick="window.close()" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle me-1"></i> Close
                    </button>
                </div>
            </div>
        </div>

        <!-- Questions by Subject -->
        <?php
        // Group questions by subject
        $questionsBySubject = [];
        foreach ($questions as $question) {
            $subjectName = $question['subject_name'];
            if (!isset($questionsBySubject[$subjectName])) {
                $questionsBySubject[$subjectName] = [];
            }
            $questionsBySubject[$subjectName][] = $question;
        }
        ?>

        <?php if (empty($questions)): ?>
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="bi bi-question-circle display-1 text-muted"></i>
                    <h4 class="text-muted mt-3">No questions found for this exam</h4>
                    <p class="text-muted">Questions will appear here once they are added to the exam.</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($questionsBySubject as $subjectName => $subjectQuestions): ?>
                <div class="card">
                    <div class="card-body">
                        <div class="subject-header">
                            <h3 class="h5 mb-0">
                                <i class="bi bi-book me-2"></i>
                                <?= htmlspecialchars($subjectName) ?>
                                <span class="badge bg-light text-dark ms-2"><?= count($subjectQuestions) ?> questions</span>
                            </h3>
                        </div>

                        <?php foreach ($subjectQuestions as $index => $question): ?>
                            <div class="card question-card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <h5 class="card-title mb-0">
                                            <span class="badge bg-primary me-2">Q<?= $question['question_number'] ?></span>
                                            <?= htmlspecialchars($question['question_text']) ?>
                                        </h5>
                                        <span class="badge bg-info">
                                            <?= $question['marks'] ?> mark(s)
                                        </span>
                                    </div>

                                    <?php if (!empty($question['picture_url'])): ?>
                                        <div class="text-center mb-3">
                                            <img src="../uploads/questions/<?= htmlspecialchars($question['picture_url']) ?>" 
                                                 class="img-fluid rounded" style="max-height: 200px;">
                                        </div>
                                    <?php endif; ?>

                                    <div class="options">
                                        <?php foreach (['A', 'B', 'C', 'D'] as $option): ?>
                                            <?php if (!empty($question['option_' . strtolower($option)])): ?>
                                                <div class="card mb-2 <?= $question['correct_option'] == $option ? 'option-correct' : 'option-incorrect' ?>">
                                                    <div class="card-body py-2">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="radio" 
                                                                   <?= $question['correct_option'] == $option ? 'checked' : 'disabled' ?>>
                                                            <label class="form-check-label">
                                                                <strong><?= $option ?>.</strong> 
                                                                <?= htmlspecialchars($question['option_' . strtolower($option)]) ?>
                                                                <?php if ($question['correct_option'] == $option): ?>
                                                                    <span class="badge bg-success ms-2">Correct</span>
                                                                <?php endif; ?>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Print Button -->
    <button onclick="window.print()" class="btn btn-primary print-btn">
        <i class="bi bi-printer me-1"></i> Print Questions
    </button>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>