<?php
session_start();

// Set the correct path to db_connect.php (located in entrance/includes)
require_once __DIR__ . '/../includes/db_connect.php';

// Check if user is logged in as student
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'student') {
    header("Location: ../login.php");
    exit();
}

// Get student information
$student_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM applicants WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    session_destroy();
    header("Location: ../login.php");
    exit();
}

// Get student's class
$class_id = $student['class_id'];

// Get upcoming exams for the student's class
$upcoming_exams = [];
$stmt = $pdo->prepare("SELECT e.* FROM exams e 
                      JOIN exam_classes ec ON e.id = ec.exam_id 
                      WHERE ec.class_id = ? AND e.exam_date >= CURDATE() AND e.is_active = 1
                      ORDER BY e.exam_date ASC");
$stmt->execute([$class_id]);
$upcoming_exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get completed exams with results - FIXED VERSION
$completed_exams = [];
$stmt = $pdo->prepare("SELECT e.*, r.score, r.total_questions, r.completed_at 
                      FROM exams e 
                      JOIN exam_classes ec ON e.id = ec.exam_id 
                      JOIN cbt_results r ON e.id = r.subject_id 
                      WHERE ec.class_id = ? AND r.applicant_id = ? AND e.exam_date < CURDATE()
                      ORDER BY e.exam_date DESC");
$stmt->execute([$class_id, $student_id]);
$completed_exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Count total exams taken
$total_exams_taken = count($completed_exams);

// Calculate average score
$average_score = 0;
if ($total_exams_taken > 0) {
    $total_score = 0;
    foreach ($completed_exams as $exam) {
        $total_score += ($exam['score'] / $exam['total_questions']) * 100;
    }
    $average_score = round($total_score / $total_exams_taken, 2);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Dashboard - CBT System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .profile-img {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            transition: transform 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .exam-card {
            border-left: 5px solid #0d6efd;
        }
        .result-card {
            border-left: 5px solid #198754;
        }
        .stat-card {
            text-align: center;
            padding: 20px;
        }
        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
        }
        .stat-label {
            color: #6c757d;
            font-size: 1rem;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">CBT System</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="student_dashboard.php">Dashboard</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="exam_history.php">Exam History</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../profile.php">Profile</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../logout.php">Logout</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container py-5">
        <!-- Welcome Section -->
        <div class="row mb-5">
            <div class="col-md-4 text-center">
                <img src="<?php echo !empty($student['image_path']) ? '../' . htmlspecialchars($student['image_path']) : '../assets/default-profile.jpg'; ?>" 
                     alt="Profile Image" class="profile-img mb-3">
                <h4><?php echo htmlspecialchars($student['full_name']); ?></h4>
                <p class="text-muted"><?php echo htmlspecialchars($student['email']); ?></p>
                <a href="../profile.php" class="btn btn-outline-primary btn-sm">Edit Profile</a>
            </div>
            <div class="col-md-8">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <div class="card stat-card bg-light">
                            <div class="stat-value text-primary"><?php echo $total_exams_taken; ?></div>
                            <div class="stat-label">Exams Taken</div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card stat-card bg-light">
                            <div class="stat-value text-success"><?php echo $average_score; ?>%</div>
                            <div class="stat-label">Average Score</div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card stat-card bg-light">
                            <div class="stat-value text-info"><?php echo count($upcoming_exams); ?></div>
                            <div class="stat-label">Upcoming Exams</div>
                        </div>
                    </div>
                </div>
                <div class="card mt-3">
                    <div class="card-body">
                        <h5 class="card-title">Student Information</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Applicant ID:</strong> <?php echo htmlspecialchars($student['applicant_id']); ?></p>
                                <p><strong>Class:</strong> <?php echo htmlspecialchars($student['class_id']); ?></p>
                                <p><strong>Phone:</strong> <?php echo htmlspecialchars($student['phone']); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Date of Birth:</strong> <?php echo htmlspecialchars($student['dob']); ?></p>
                                <p><strong>Gender:</strong> <?php echo htmlspecialchars($student['gender']); ?></p>
                                <p><strong>Address:</strong> <?php echo htmlspecialchars($student['address']); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Upcoming Exams -->
        <div class="row mb-5">
            <div class="col-12">
                <h3 class="mb-4">Upcoming Exams</h3>
                <?php if (empty($upcoming_exams)): ?>
                    <div class="alert alert-info">No upcoming exams scheduled.</div>
                <?php else: ?>
                    <div class="row">
                        <?php foreach ($upcoming_exams as $exam): ?>
                            <div class="col-md-6">
                                <div class="card exam-card h-100">
                                    <div class="card-body">
                                        <h5 class="card-title"><?php echo htmlspecialchars($exam['exam_name']); ?></h5>
                                        <p class="card-text"><?php echo htmlspecialchars($exam['description']); ?></p>
                                        <ul class="list-group list-group-flush mb-3">
                                            <li class="list-group-item">
                                                <strong>Date:</strong> <?php echo date('F j, Y', strtotime($exam['exam_date'])); ?>
                                            </li>
                                            <li class="list-group-item">
                                                <strong>Duration:</strong> <?php echo htmlspecialchars($exam['duration_minutes']); ?> minutes
                                            </li>
                                            <li class="list-group-item">
                                                <strong>Passing Score:</strong> <?php echo htmlspecialchars($exam['passing_score']); ?>%
                                            </li>
                                        </ul>
                                        <a href="exam_details.php?id=<?php echo htmlspecialchars($exam['id']); ?>" class="btn btn-primary">View Details</a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Recent Exam Results -->
        <div class="row">
            <div class="col-12">
                <h3 class="mb-4">Recent Exam Results</h3>
                <?php if (empty($completed_exams)): ?>
                    <div class="alert alert-info">No exam results available.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th>Exam Name</th>
                                    <th>Date Taken</th>
                                    <th>Score</th>
                                    <th>Total Questions</th>
                                    <th>Percentage</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($completed_exams as $exam): 
                                    $percentage = round(($exam['score'] / $exam['total_questions']) * 100, 2);
                                    $status = $percentage >= $exam['passing_score'] ? 'Passed' : 'Failed';
                                    $status_class = $status === 'Passed' ? 'success' : 'danger';
                                ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($exam['exam_name']); ?></td>
                                        <td><?php echo date('F j, Y', strtotime($exam['completed_at'])); ?></td>
                                        <td><?php echo htmlspecialchars($exam['score']); ?></td>
                                        <td><?php echo htmlspecialchars($exam['total_questions']); ?></td>
                                        <td><?php echo $percentage; ?>%</td>
                                        <td><span class="badge bg-<?php echo $status_class; ?>"><?php echo $status; ?></span></td>
                                        <td>
                                            <a href="exam_result.php?id=<?php echo htmlspecialchars($exam['id']); ?>" class="btn btn-sm btn-outline-primary">View Details</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <footer class="bg-light py-4 mt-5">
        <div class="container text-center">
            <p class="text-muted mb-0">© <?php echo date('Y'); ?> CBT System. All rights reserved.</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>