<?php
session_start();

// Check if user is logged in and is a student
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'student') {
    header('Location: ../login.php');
    exit();
}

require_once '../config/database.php';

// Get student details
$stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section as class_section FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
$stmt->execute([$_SESSION['student_id']]);
$student = $stmt->fetch();

if (!$student) {
    header('Location: ../login.php');
    exit();
}

// Get student results
$results = [];
$result_stmt = $pdo->prepare("
    SELECT r.*, e.name as exam_name, e.exam_date, sub.name as subject_name, sub.code as subject_code
    FROM results r 
    LEFT JOIN exams e ON r.exam_id = e.id 
    LEFT JOIN subjects sub ON r.subject_id = sub.id 
    WHERE r.student_id = ? 
    ORDER BY e.exam_date DESC, sub.name ASC
");
$result_stmt->execute([$student['id']]);
$results = $result_stmt->fetchAll();

// Group results by exam
$grouped_results = [];
foreach ($results as $result) {
    $exam_key = $result['exam_name'] . '_' . $result['exam_date'];
    if (!isset($grouped_results[$exam_key])) {
        $grouped_results[$exam_key] = [
            'exam_name' => $result['exam_name'],
            'exam_date' => $result['exam_date'],
            'subjects' => []
        ];
    }
    $grouped_results[$exam_key]['subjects'][] = $result;
}

// Get student subjects for grading calculation
$subjects = [];
$subject_stmt = $pdo->prepare("SELECT sub.name, sub.code FROM student_subjects ss JOIN subjects sub ON ss.subject_id = sub.id WHERE ss.student_id = ?");
$subject_stmt->execute([$student['id']]);
$subjects = $subject_stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>মার্কশীট - <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif; 
            background-color: #f8f9fa;
        }
        .marksheet-card {
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .subject-row {
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }
        .subject-row:last-child {
            border-bottom: none;
        }
        .marks-obtained {
            font-weight: bold;
            color: #006747;
        }
        .marks-total {
            color: #666;
            font-size: 0.9em;
        }
        .print-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../student_dashboard.php"><i class="fas fa-arrow-left"></i> ছাত্র ড্যাশবোর্ড</a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    <i class="fas fa-user-graduate"></i> <?php echo htmlspecialchars($_SESSION['user_name']); ?>
                </span>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <button class="btn btn-primary print-btn" onclick="window.print()">
            <i class="fas fa-print"></i> প্রিন্ট করুন
        </button>

        <div class="row">
            <div class="col-md-12">
                <h2><i class="fas fa-certificate"></i> মার্কশীট</h2>
                <p>ছাত্র নাম: <strong><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></strong> | 
                   ছাত্র আইডি: <strong><?php echo htmlspecialchars($student['student_id']); ?></strong> |
                   ক্লাস: <strong><?php echo htmlspecialchars($student['class_name'] . ' - ' . $student['class_section']); ?></strong> |
                   রোল: <strong><?php echo htmlspecialchars($student['roll_number']); ?></strong></p>
            </div>
        </div>

        <?php if (!empty($grouped_results)): ?>
            <?php foreach ($grouped_results as $exam_key => $exam_data): ?>
                <div class="card marksheet-card">
                    <div class="card-header bg-success text-white">
                        <h5>
                            <i class="fas fa-clipboard-list"></i> 
                            <?php echo htmlspecialchars($exam_data['exam_name']); ?>
                            <small class="float-end"><?php echo date('d/m/Y', strtotime($exam_data['exam_date'])); ?></small>
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th>বিষয়</th>
                                        <th>কোড</th>
                                        <th>নম্বর</th>
                                        <th>গ্রেড</th>
                                        <th>পাস/ফেইল</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $total_marks = 0;
                                    $total_subjects = 0;
                                    $passed_subjects = 0;
                                    
                                    foreach ($exam_data['subjects'] as $result): 
                                        $total_marks += $result['marks_obtained'];
                                        $total_subjects++;
                                        if ($result['is_passed']) {
                                            $passed_subjects++;
                                        }
                                    ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($result['subject_name']); ?></td>
                                            <td><?php echo htmlspecialchars($result['subject_code']); ?></td>
                                            <td>
                                                <span class="marks-obtained"><?php echo htmlspecialchars($result['marks_obtained']); ?></span>
                                                <span class="marks-total">/<?php echo htmlspecialchars($result['total_marks']); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($result['grade']): ?>
                                                    <span class="badge bg-primary"><?php echo htmlspecialchars($result['grade']); ?></span>
                                                <?php else: ?>
                                                    -
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($result['is_passed']): ?>
                                                    <span class="badge bg-success">পাস</span>
                                                    <?php else: ?>
                                                    <span class="badge bg-danger">ফেইল</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if ($total_subjects > 0): ?>
                                        <tr class="table-info">
                                            <td colspan="2"><strong>মোট</strong></td>
                                            <td><strong><?php echo $total_marks; ?>/<?php echo $total_subjects * 100; ?></strong></td>
                                            <td><strong>গড়: <?php echo $total_subjects > 0 ? round($total_marks / $total_subjects, 2) : 0; ?></strong></td>
                                            <td><strong><?php echo $passed_subjects; ?>/<?php echo $total_subjects; ?> পাস</strong></td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i> এখনও কোন ফলাফল পাওয়া যায়নি।
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>