<?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; 
}

$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : null;
$student_id = $_SESSION['student_id'];

try {
    // 1. Fetch the list of all exams
    $all_exams = $pdo->query("SELECT id, exam_title FROM exams ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

    if (!$exam_id && !empty($all_exams)) {
        $exam_id = $all_exams[0]['id']; // Default to the latest exam
    }

    // 2. Generate rankings for the specific exam
    $stmt = $pdo->prepare("
        SELECT r.*, s.name as student_name, s.id as std_id
        FROM exam_result r 
        JOIN students s ON r.student_id = s.id 
        WHERE r.exam_id = ? 
        ORDER BY r.score DESC, r.percentage DESC
    ");
    $stmt->execute([$exam_id]);
    $rankings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch the current exam title
    $current_exam_title = "Select an Exam";
    if ($exam_id) {
        $exam_info = $pdo->prepare("SELECT exam_title FROM exams WHERE id = ?");
        $exam_info->execute([$exam_id]);
        $current_exam_title = $exam_info->fetchColumn() ?: "Unknown Exam";
    }

} 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 */
    }

    /* Entrance Animation */
    .fade-up { animation: fadeInUp 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
    @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    
    /* Desktop Table Styles */
    .table-custom { 
        background: #fff; 
        border-radius: 15px; 
        overflow: hidden; 
        box-shadow: 0 10px 30px rgba(0,0,0,0.03); 
        border-top: 4px solid var(--accent); 
    }
    .table-custom thead { 
        background: var(--primary); 
        color: #fff; 
        font-weight: 700; 
        font-size: 13px; 
        letter-spacing: 0.5px; 
    }
    .table-custom tbody tr { transition: 0.3s; }
    .table-custom tbody tr:hover { background-color: rgba(212, 175, 55, 0.05); transform: scale(1.002); }
    
    .rank-badge { 
        width: 35px; height: 35px; 
        display: inline-flex; align-items: center; justify-content: center; 
        font-weight: 800; font-size: 14px; 
    }
    .highlight-me { 
        background-color: rgba(212, 175, 55, 0.08) !important; 
        border-left: 4px solid var(--accent) !important; 
    }

    /* Mobile Responsive Card View (Hidden on Desktop) */
    .mobile-card-view { display: none; }

    @media (max-width: 767.98px) {
        .main-content { padding: 1.25rem !important; }
        .desktop-table-view { display: none; }
        .mobile-card-view { display: block; }
        
        .rank-card { transition: 0.3s; border-radius: 15px; border: 1px solid #e2e8f0; }
        .rank-card.highlight-me { 
            border: 2px solid var(--accent); 
            background-color: rgba(212, 175, 55, 0.05); 
        }
    }
</style>

<div class="main-content p-4" style="background: #f8fafc; min-height: 100vh;">
    
    <div class="row align-items-center mb-4 g-3 fade-up">
        <div class="col-md-7">
            <h4 class="fw-bold mb-1" style="color: var(--primary);"><i class="fas fa-trophy me-2" style="color: var(--accent);"></i> Merit List</h4>
            <p class="text-muted small mb-0 fw-bold">Exam: <span class="text-dark"><?= htmlspecialchars($current_exam_title); ?></span></p>
        </div>
        <div class="col-md-5">
            <form action="" method="GET" class="d-flex">
                <select name="exam_id" class="form-select rounded-pill shadow-sm border-0 fw-bold text-dark py-2" onchange="this.form.submit()" style="background-color: #fff; box-shadow: 0 5px 15px rgba(0,0,0,0.05);">
                    <?php foreach($all_exams as $ex): ?>
                        <option value="<?= $ex['id']; ?>" <?= $exam_id == $ex['id'] ? 'selected' : ''; ?>>
                            <?= htmlspecialchars($ex['exam_title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
    </div>

    <?php if(empty($rankings)): ?>
        <div class="card border-0 shadow-sm rounded-4 p-5 text-center fade-up" style="animation-delay: 0.1s;">
            <div class="opacity-50 mb-4">
                <i class="fas fa-medal text-muted" style="font-size: 80px;"></i>
            </div>
            <h5 class="text-dark fw-bold mb-2">No Results Found!</h5>
            <p class="text-muted small">No one has participated in this exam yet.</p>
        </div>
    <?php else: ?>

        <div class="table-custom table-responsive desktop-table-view fade-up" style="animation-delay: 0.1s;">
            <table class="table align-middle mb-0">
                <thead>
                    <tr>
                        <th class="ps-4 py-3 border-0">Rank</th>
                        <th class="py-3 border-0">Student Name</th>
                        <th class="text-center py-3 border-0">Score</th>
                        <th class="text-center py-3 border-0">Correct</th>
                        <th class="text-center py-3 border-0">Wrong</th>
                        <th class="text-end pe-4 py-3 border-0">Submitted At</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $rank = 1;
                    foreach ($rankings as $row): 
                        $student_name = $row['student_name'] ?? 'Unknown Student';
                        $score = $row['score'] ?? $row['obtained_marks'] ?? 0;
                        $correct = $row['correct_answers'] ?? $row['total_correct'] ?? 0;
                        $wrong = $row['wrong_answers'] ?? $row['total_wrong'] ?? 0;
                        
                        $raw_date = $row['submitted_at'] ?? $row['created_at'] ?? null;
                        $submitted_at = $raw_date ? date('d M, h:i A', strtotime($raw_date)) : 'N/A';
                        
                        $is_me = ($row['std_id'] == $student_id);
                        $row_class = $is_me ? 'highlight-me' : '';
                        
                        // Dynamic Colors for Top 3 Ranks
                        if($rank == 1) $rank_style = 'background: #d4af37; color: #fff; box-shadow: 0 3px 10px rgba(212, 175, 55, 0.4);'; // Golden
                        elseif($rank == 2) $rank_style = 'background: #94a3b8; color: #fff; box-shadow: 0 3px 10px rgba(148, 163, 184, 0.4);'; // Silver
                        elseif($rank == 3) $rank_style = 'background: #b45309; color: #fff; box-shadow: 0 3px 10px rgba(180, 83, 9, 0.4);'; // Bronze
                        else $rank_style = 'background: #f1f5f9; color: #64748b;';
                    ?>
                    <tr class="<?= $row_class; ?> border-bottom">
                        <td class="ps-4">
                            <span class="badge rounded-circle rank-badge" style="<?= $rank_style; ?>"><?= $rank++; ?></span>
                        </td>
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="https://ui-avatars.com/api/?name=<?= urlencode($student_name); ?>&background=064e3b&color=fff&bold=true" class="rounded-circle me-3 shadow-sm" width="35" height="35">
                                <div class="fw-bold text-dark" style="font-size: 15px;">
                                    <?= htmlspecialchars($student_name); ?>
                                    <?php if($is_me) echo '<span class="ms-2 badge px-2 rounded-pill" style="font-size:10px; background-color: var(--accent); color: var(--primary-dark);">You</span>'; ?>
                                </div>
                            </div>
                        </td>
                        <td class="text-center fw-bold" style="font-size: 16px; color: var(--primary);"><?= number_format($score, 2); ?></td>
                        <td class="text-center fw-bold text-success"><?= $correct; ?></td>
                        <td class="text-center fw-bold text-danger"><?= $wrong; ?></td>
                        <td class="text-end pe-4 small text-muted fw-bold"><i class="far fa-clock me-1"></i> <?= $submitted_at; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="mobile-card-view fade-up" style="animation-delay: 0.1s;">
            <div class="row g-3">
                <?php 
                $rank = 1;
                foreach ($rankings as $row): 
                    $student_name = $row['student_name'] ?? 'Unknown Student';
                    $score = $row['score'] ?? $row['obtained_marks'] ?? 0;
                    $correct = $row['correct_answers'] ?? $row['total_correct'] ?? 0;
                    $wrong = $row['wrong_answers'] ?? $row['total_wrong'] ?? 0;
                    $is_me = ($row['std_id'] == $student_id);
                    
                    // Rank Badge Colors for Mobile
                    if($rank == 1) $r_bg = '#d4af37';
                    elseif($rank == 2) $r_bg = '#94a3b8';
                    elseif($rank == 3) $r_bg = '#b45309';
                    else $r_bg = '#e2e8f0';
                ?>
                <div class="col-12">
                    <div class="card rank-card border-0 shadow-sm p-3 bg-white <?= $is_me ? 'highlight-me' : ''; ?>">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div class="d-flex align-items-center gap-3">
                                <div class="rank-badge rounded-circle text-white shadow-sm" style="background: <?= $r_bg; ?>; font-size: 13px; width: 35px; height: 35px; <?= $rank > 3 ? 'color:#64748b!important; font-weight:bold;' : '' ?>">
                                    #<?= $rank++; ?>
                                </div>
                                
                                <div class="fw-bold text-dark" style="font-size: 15px; line-height: 1.2;">
                                    <?= htmlspecialchars($student_name); ?>
                                    <?php if($is_me) echo '<div style="font-size:11px; font-weight:800; color: var(--accent); margin-top:2px;">(This is You)</div>'; ?>
                                </div>
                            </div>
                            
                            <div class="text-end">
                                <h5 class="fw-bold mb-0" style="color: var(--primary);"><?= number_format($score, 2); ?></h5>
                                <small class="text-muted fw-bold" style="font-size: 11px;">Score</small>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-between bg-light p-2 rounded-3 text-center border">
                            <div class="flex-fill border-end">
                                <small class="text-muted fw-bold d-block" style="font-size: 11px;">Correct</small>
                                <span class="fw-bold text-success fs-6"><?= $correct; ?></span>
                            </div>
                            <div class="flex-fill">
                                <small class="text-muted fw-bold d-block" style="font-size: 11px;">Wrong</small>
                                <span class="fw-bold text-danger fs-6"><?= $wrong; ?></span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

    <?php endif; ?>
</div>

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