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

session_start();

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

$student_id = $_SESSION['student_id'];

try {
    // SQL Query to fetch exam results
    $stmt = $pdo->prepare("
        SELECT er.*, e.exam_title, e.total_questions 
        FROM exam_result er 
        JOIN exams e ON er.exam_id = e.id 
        WHERE er.student_id = ? 
        ORDER BY er.id DESC
    ");
    $stmt->execute([$student_id]);
    $all_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Result Fetch Error: " . $e->getMessage());
}

// Include Header & Sidebar
include 'includes/user_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(--primary); 
    }
    .table-custom thead { 
        background: #f8fafc; 
        color: #475569; 
        font-weight: 700; 
        text-transform: uppercase; 
        font-size: 12px; 
        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); }
    
    .status-badge { 
        padding: 6px 16px; 
        border-radius: 50px; 
        font-size: 11px; 
        font-weight: 800; 
        text-transform: uppercase; 
    }
    
    .btn-detail { 
        border-color: var(--primary); 
        color: var(--primary); 
        transition: 0.3s; 
    }
    .btn-detail:hover { 
        background: var(--primary); 
        color: var(--accent); 
        border-color: var(--primary);
        box-shadow: 0 5px 15px rgba(6, 78, 59, 0.2);
    }

    /* 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; }
        .result-card { border-left: 4px solid var(--primary); transition: 0.3s; }
        .result-card:active { transform: scale(0.98); }
    }
</style>

<div class="main-content p-4" style="background: #f8fafc; min-height: 100vh;">
    
    <div class="mb-4 pb-2 fade-up">
        <h4 class="fw-bold text-dark mb-1"><i class="fas fa-medal me-2" style="color: var(--accent);"></i> My Exam Results</h4>
        <p class="text-muted fw-semibold mb-0" style="font-size: 14px;">A detailed list of all your attempted exams and scores</p>
    </div>

    <?php if(empty($all_results)): ?>
        <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-folder-open 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 mb-4">You haven't participated in any exams yet.</p>
            <a href="exams.php" class="btn btn-lg rounded-pill px-5 fw-bold shadow-sm" style="background: var(--primary); color: white; border: none; font-size: 15px; transition: 0.3s;">
                Explore Live Exams
            </a>
        </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 border-white">
                <thead>
                    <tr>
                        <th class="py-4 ps-4 border-0">Date</th>
                        <th class="py-4 border-0">Exam Title</th>
                        <th class="py-4 text-center border-0">Score</th>
                        <th class="py-4 text-center border-0">Percentage (%)</th>
                        <th class="py-4 text-center border-0">Status</th>
                        <th class="py-4 text-end pe-4 border-0">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($all_results as $row): 
                        $obtained = $row['obtained_marks'] ?? $row['score'] ?? $row['marks'] ?? 0;
                        $total = $row['total_marks'] ?? $row['total_questions'] ?? 0;
                        $percentage = $row['percentage'] ?? ($total > 0 ? round(($obtained / $total) * 100, 2) : 0);
                        $percentage = max(0, $percentage); 
                        $is_passed = ($percentage >= 40); // Assuming 40% is the passing mark
                        
                        $raw_date = $row['submitted_at'] ?? $row['created_at'] ?? $row['exam_date'] ?? $row['date'] ?? null;
                        $date = $raw_date ? date('d M, Y', strtotime($raw_date)) : 'No Date';
                        $time = $raw_date ? date('h:i A', strtotime($raw_date)) : '';
                        $result_id = $row['id'] ?? 0;
                    ?>
                    <tr class="border-bottom">
                        <td class="ps-4">
                            <div class="fw-bold text-dark" style="font-size: 14px;"><i class="far fa-calendar-alt me-1 text-muted"></i> <?= $date; ?></div>
                            <small class="text-muted"><i class="far fa-clock me-1"></i> <?= $time; ?></small>
                        </td>
                        <td>
                            <div class="fw-bold" style="font-size: 15px; color: var(--primary);"><?= htmlspecialchars($row['exam_title'] ?? 'Unknown Exam'); ?></div>
                            <small class="text-muted"><i class="fas fa-list-ol me-1"></i> <?= $row['total_questions']; ?> Questions</small>
                        </td>
                        <td class="text-center">
                            <span class="fw-bold" style="font-size: 16px; color: var(--primary-dark);">
                                <?= number_format($obtained, 2); ?> <span class="text-muted opacity-50" style="font-size: 12px;">/ <?= $total; ?></span>
                            </span>
                        </td>
                        <td class="text-center">
                            <div class="fw-bold <?= $is_passed ? 'text-success' : 'text-danger' ?>" style="font-size: 15px;"><?= $percentage; ?>%</div>
                        </td>
                        <td class="text-center">
                            <span class="status-badge <?= $is_passed ? 'bg-success bg-opacity-10 text-success border border-success border-opacity-25' : 'bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25' ?>">
                                <i class="fas <?= $is_passed ? 'fa-check-circle' : 'fa-times-circle' ?> me-1"></i> <?= $is_passed ? 'Passed' : 'Failed' ?>
                            </span>
                        </td>
                        <td class="text-end pe-4">
                            <a href="exam_result.php?id=<?= $result_id; ?>" class="btn btn-sm rounded-pill px-4 py-2 fw-bold shadow-sm btn-detail">
                                Details <i class="fas fa-chevron-right ms-1 small"></i>
                            </a>
                        </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 foreach($all_results as $row): 
                    $obtained = $row['obtained_marks'] ?? $row['score'] ?? $row['marks'] ?? 0;
                    $total = $row['total_marks'] ?? $row['total_questions'] ?? 0;
                    $percentage = $row['percentage'] ?? ($total > 0 ? round(($obtained / $total) * 100, 2) : 0);
                    $percentage = max(0, $percentage); 
                    $is_passed = ($percentage >= 40);
                    
                    $raw_date = $row['submitted_at'] ?? $row['created_at'] ?? $row['exam_date'] ?? $row['date'] ?? null;
                    $date = $raw_date ? date('d M, Y', strtotime($raw_date)) : 'No Date';
                    $result_id = $row['id'] ?? 0;
                    
                    $border_color = $is_passed ? '#10b981' : '#ef4444'; // Green for pass, Red for fail
                ?>
                <div class="col-12">
                    <div class="card result-card border-0 shadow-sm rounded-4 p-3 bg-white" style="border-left-color: <?= $border_color ?>;">
                        
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div class="fw-bold" style="font-size: 15px; line-height: 1.4; color: var(--primary);">
                                <?= htmlspecialchars($row['exam_title'] ?? 'Unknown Exam'); ?>
                            </div>
                            <span class="status-badge <?= $is_passed ? 'bg-success bg-opacity-10 text-success' : 'bg-danger bg-opacity-10 text-danger' ?> ms-2 px-2 py-1" style="font-size: 10px;">
                                <?= $is_passed ? 'Passed' : 'Failed' ?>
                            </span>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="text-muted small fw-semibold">
                                <i class="far fa-calendar-alt me-1"></i> <?= $date; ?>
                            </div>
                            <div class="fw-bold" style="font-size: 15px; color: var(--primary-dark);">
                                Score: <?= number_format($obtained, 2); ?> <span class="text-muted small">/ <?= $total; ?></span>
                            </div>
                        </div>
                        
                        <a href="exam_result.php?id=<?= $result_id; ?>" class="btn btn-light w-100 rounded-pill py-2 fw-bold text-dark" style="font-size: 14px; border: 1px solid #e2e8f0; transition: 0.3s;">
                            View Details <i class="fas fa-chevron-right ms-2 text-muted small"></i>
                        </a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

    <?php endif; ?>
</div>

<script>
    // Sidebar Toggle (Fallback script for Mobile)
    document.getElementById('sidebarToggle')?.addEventListener('click', function() {
        document.querySelector('.sidebar')?.classList.toggle('active');
    });
</script>

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