<?php
// student/view_result.php
require_once '../includes/auth_check.php';
checkAccess('student');
require_once '../config/database.php';
require_once '../includes/result_calculator.php';

$student_id = $_SESSION['student_id'];
$session = $_GET['session'];
$term = $_GET['term'];

// Fetch student details
$stmt = $pdo->prepare("SELECT s.*, c.class_name FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

// Fetch approved results only
$stmt = $pdo->prepare("SELECT r.*, sub.subject_name 
                       FROM results r 
                       JOIN subjects sub ON r.subject_id = sub.id 
                       WHERE r.student_id = ? AND r.session = ? AND r.term = ? AND r.status = 'approved'");
$stmt->execute([$student_id, $session, $term]);
$results = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html>
<head><title>Report Card - <?php echo $student['fullname']; ?></title></head>
<body>
    <div style="width:800px; margin:auto; border:2px solid #000; padding:20px;">
        <table width="100%">
            <tr>
                <td><img src="../uploads/students/<?php echo $student['photo']; ?>" width="100"></td>
                <td align="center">
                    <h2>OFFICIAL RESULT SHEET</h2>
                    <p><?php echo $session; ?> | <?php echo $term; ?></p>
                </td>
            </tr>
        </table>
        <hr>
        <p><strong>Name:</strong> <?php echo $student['fullname']; ?> | <strong>Reg No:</strong> <?php echo $student['reg_number']; ?></p>
        <p><strong>Class:</strong> <?php echo $student['class_name']; ?></p>

        <table border="1" width="100%" cellpadding="10" style="border-collapse:collapse;">
            <thead>
                <tr>
                    <th>Subject</th>
                    <th>CA (40)</th>
                    <th>Exam (60)</th>
                    <th>Total</th>
                    <th>Grade</th>
                    <th>Remark</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($results as $res): 
                    $gradeInfo = getGrade($res['total_score']); 
                ?>
                <tr>
                    <td><?php echo $res['subject_name']; ?></td>
                    <td><?php echo $res['ca_score']; ?></td>
                    <td><?php echo $res['exam_score']; ?></td>
                    <td><?php echo $res['total_score']; ?></td>
                    <td><?php echo $gradeInfo[0]; ?></td>
                    <td><?php echo $gradeInfo[1]; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <br>
        <button onclick="window.print()">Print Result</button>
    </div>
</body>
</html>