<?php 
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

// 1. Database Connection
if (!file_exists('db_connect.php')) {
    die("Error: db_connect.php file is missing.");
}
require_once 'db_connect.php';

// Security Check
if (!isset($_SESSION['student_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$result_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$student_id = $_SESSION['student_id'];

if ($result_id === 0) {
    die("Invalid Result ID!");
}

try {
    // 1. Fetch Result and Exam Name
    $stmt = $pdo->prepare("
        SELECT r.*, e.exam_title 
        FROM exam_result r 
        JOIN exams e ON r.exam_id = e.id 
        WHERE r.id = ? AND r.student_id = ?
    ");
    $stmt->execute([$result_id, $student_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!$result) {
        die("<div class='alert alert-danger text-center m-5 shadow-sm fw-bold'>Sorry, this result could not be found or it does not belong to you.</div>");
    }

    // 2. Fetch Questions and Student's Answers
    $q_stmt = $pdo->prepare("
        SELECT q.*, res.selected_option 
        FROM questions q 
        LEFT JOIN student_responses res ON q.id = res.question_id AND res.result_id = ?
        WHERE q.exam_id = ?
    ");
    $q_stmt->execute([$result_id, $result['exam_id']]);
    $questions = $q_stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) { 
    die("Database Error: " . $e->getMessage()); 
}

// Include Header & Sidebar
if(file_exists('includes/user_header.php')) { include 'includes/user_header.php'; } 
elseif(file_exists('header.php')) { include 'header.php'; }

if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 
elseif(file_exists('sidebar.php')) { include 'sidebar.php'; }
?>

<style>
    :root {
        --primary: #064e3b;
        --primary-dark: #022c22;
        --accent: #d4af37; /* Golden */
    }

    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    
    .question-card { transition: 0.3s; border: 1px solid #e2e8f0; background: #fff; }
    .question-card:hover { box-shadow: 0 10px 25px rgba(0,0,0,0.05) !important; transform: translateY(-2px); }
    
    .option-box { 
        transition: 0.2s; 
        border: 2px solid #f1f5f9; 
        background: #f8fafc; 
        padding: 12px 15px; 
        border-radius: 12px; 
        display: flex; 
        align-items: center; 
        justify-content: space-between; 
        height: 100%; 
        font-size: 15px; 
    }
    
    /* Dynamic Style Classes for Answers */
    .option-box.correct { background: #ecfdf5; border-color: #10b981; color: #065f46; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.1); }
    .option-box.wrong { background: #fef2f2; border-color: #ef4444; color: #991b1b; box-shadow: 0 4px 10px rgba(239, 68, 68, 0.1); }
    .option-box.correct-answer { border-color: #10b981; border-style: dashed; border-width: 2px; background: #f0fdf4; color: #064e3b; }
    
    /* Unattempted Border Style */
    .border-unattempted { border-color: var(--accent) !important; }
    .text-unattempted { color: #b48a1d !important; }
    .bg-unattempted-light { background-color: rgba(212, 175, 55, 0.1) !important; border-color: rgba(212, 175, 55, 0.3) !important; }
</style>

<div class="main-content p-4" style="background: #f8fafc; min-height: 100vh;">
    
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 fade-up">
        <div class="mb-3 mb-md-0">
            <h4 class="fw-bold mb-1" style="color: var(--primary);"><i class="fas fa-clipboard-check me-2" style="color: var(--accent);"></i> Review Answer Sheet</h4>
            <p class="text-muted small fw-bold mb-0">Exam: <?= htmlspecialchars($result['exam_title']); ?></p>
        </div>
        <a href="exam_result.php?id=<?= $result_id; ?>" class="btn btn-white border shadow-sm rounded-pill fw-bold text-dark px-4 py-2" style="transition: 0.3s;" onmouseover="this.style.backgroundColor='var(--primary)'; this.style.color='white';" onmouseout="this.style.backgroundColor='white'; this.style.color='#212529';">
            <i class="fas fa-arrow-left me-2"></i> Back to Result
        </a>
    </div>

    <div class="row justify-content-center fade-up" style="animation-delay: 0.1s;">
        <div class="col-lg-10">
            
            <?php if(empty($questions)): ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm border">
                    <i class="fas fa-exclamation-circle fa-3x text-muted mb-3 opacity-50"></i>
                    <h5 class="text-muted fw-bold">Answer details not found.</h5>
                    <p class="small text-muted">It seems the answers for this exam were not saved in the database.</p>
                </div>
            <?php else: ?>
            
                <?php $i = 1; foreach($questions as $q): 
                    // Case-insensitive comparison (A == a)
                    $selected = strtolower(trim($q['selected_option'] ?? ''));
                    $correct = strtolower(trim($q['correct_option'] ?? ''));
                    
                    $is_correct = ($selected === $correct);
                    $has_answered = !empty($selected);
                    
                    // Border Color Logic for the Left Side of the Card
                    $border_class = $has_answered ? ($is_correct ? 'border-success' : 'border-danger') : 'border-unattempted';
                ?>
                <div class="card question-card shadow-sm rounded-4 p-4 mb-4 border-start border-5 <?= $border_class; ?>">
                    
                    <h5 class="fw-bold mb-4 text-dark" style="line-height: 1.5; font-size: 17px;">
                        <span style="color: var(--primary);" class="me-2"><?= $i++; ?>.</span> <?= htmlspecialchars($q['question_text']); ?>
                        
                        <?php if($has_answered): ?>
                            <?php if($is_correct): ?>
                                <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 ms-2 px-3 py-1 align-middle" style="font-size: 11px;"><i class="fas fa-check me-1"></i> Correct Answer</span>
                            <?php else: ?>
                                <span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 ms-2 px-3 py-1 align-middle" style="font-size: 11px;"><i class="fas fa-times me-1"></i> Wrong Answer</span>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="badge bg-unattempted-light text-unattempted ms-2 px-3 py-1 align-middle" style="font-size: 11px;"><i class="fas fa-minus me-1"></i> Not Attempted</span>
                        <?php endif; ?>
                    </h5>
                    
                    <div class="row g-3">
                        <?php 
                        $opts = ['a' => $q['option_a'], 'b' => $q['option_b'], 'c' => $q['option_c'], 'd' => $q['option_d']];
                        foreach($opts as $key => $val): 
                            if(empty(trim($val))) continue; // Skip empty options
                            
                            $bg = ''; $icon = '';
                            $current_key = strtolower($key);
                            
                            // 1. If student selected the correct answer
                            if ($current_key === $correct && $current_key === $selected) { 
                                $bg = 'correct'; 
                                $icon = '<i class="fas fa-check-circle fs-5"></i>'; 
                            } 
                            // 2. If student selected the wrong answer
                            elseif ($current_key === $selected && !$is_correct) {
                                $bg = 'wrong'; 
                                $icon = '<i class="fas fa-times-circle fs-5"></i>';
                            }
                            // 3. Highlight the correct answer if the student was wrong or skipped it
                            elseif ($current_key === $correct) {
                                $bg = 'correct-answer';
                                $icon = '<i class="fas fa-lightbulb text-success fs-5 opacity-75" title="This was the correct answer"></i>';
                            }
                        ?>
                        <div class="col-md-6">
                            <div class="option-box <?= $bg; ?>">
                                <div>
                                    <span class="fw-bold me-2 text-uppercase badge bg-dark bg-opacity-10 text-dark rounded-circle px-2 py-1"><?= $key; ?></span> 
                                    <span style="font-weight: 500;"><?= htmlspecialchars($val); ?></span>
                                </div>
                                <?= $icon; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            
            <?php endif; ?>
            
            <div class="text-center mt-5 mb-4">
                <a href="exams.php" class="btn rounded-pill px-5 py-3 fw-bold shadow-sm" style="background: var(--primary); color: white; border: none; transition: 0.3s;" onmouseover="this.style.transform='translateY(-2px)'; this.style.backgroundColor='var(--accent)'; this.style.color='var(--primary-dark)';" onmouseout="this.style.transform='translateY(0)'; this.style.backgroundColor='var(--primary)'; this.style.color='white';">
                    <i class="fas fa-list-ul me-2"></i> View Other Exams
                </a>
            </div>

        </div>
    </div>
</div>

<?php 
// Include Footer 
if(file_exists('includes/user_footer.php')) { include 'includes/user_footer.php'; } 
elseif(file_exists('footer.php')) { include 'footer.php'; } 
?>