<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

Auth()->requireRole(['college', 'admin', 'super_admin']);
$db = DB();

$id = intval($_GET['id'] ?? 0);
$s = $db->fetchOne("SELECT s.*, c.course_name, c.course_code FROM students s JOIN courses c ON s.course_id = c.id WHERE s.id = ?", [$id]);

// Check if published results exist in student_results table
$subjectResults = $db->fetchAll("SELECT * FROM student_results WHERE student_id = ? AND is_published = 1 ORDER BY created_at DESC", [$id]);

if (!empty($subjectResults)) {
    // Use published data
    $theorySubjects = array_filter($subjectResults, fn($sub) => stripos($sub['subject_name'], 'Practical') === false);
    $practicalSubjects = array_filter($subjectResults, fn($sub) => stripos($sub['subject_name'], 'Practical') !== false);
    // Note: The above filter is a bit heuristic, but student_results doesn't have a 'type' column
} else {
    // Fallback to subjects + marks_entry (draft mode)
    $subjects = $db->fetchAll("SELECT s.*, m.obtained_marks 
                              FROM subjects s 
                              LEFT JOIN marks_entry m ON s.id = m.subject_id AND m.student_id = ? 
                              WHERE s.course_id = ? 
                              ORDER BY s.type, s.subject_name", [$id, $s['course_id']]);
    $theorySubjects = array_filter($subjects, fn($sub) => $sub['type'] === 'Theory');
    $practicalSubjects = array_filter($subjects, fn($sub) => $sub['type'] === 'Practical');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mark Sheet - <?= $s['registration_number'] ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&display=swap');
        body { background: #f0f0f0; font-family: 'Roboto', sans-serif; }
        .marksheet-container {
            width: 210mm;
            min-height: 297mm;
            padding: 20mm;
            margin: 20px auto;
            background: white;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            position: relative;
            border: 2px solid #3b0b7c;
        }
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 8rem;
            color: rgba(59, 11, 124, 0.03);
            white-space: nowrap;
            pointer-events: none;
            font-weight: 900;
        }
        .header-logo { width: 100px; height: 100px; object-fit: contain; }
        .board-title { color: #3b0b7c; font-weight: 900; letter-spacing: 0.5px; line-height: 1.2; }
        .marks-table th { background: #f8f9fa !important; border-bottom: 2px solid #3b0b7c; font-size: 13px; text-transform: uppercase; }
        .marks-table td { font-size: 14px; padding: 8px !important; }
        .footer-sign { margin-top: 40px; }
        .sign-box { border-top: 1px solid #333; width: 180px; display: inline-block; padding-top: 5px; font-weight: 700; font-size: 12px; }
        
        @media print {
            body { background: none; padding: 0; }
            .marksheet-container { margin: 0; box-shadow: none; border: 2px solid #3b0b7c; width: 100%; }
            .btn-print { display: none; }
            @page { size: A4; margin: 0; }
        }
    </style>
</head>
<body>

<div class="text-center mt-3 mb-3">
    <button onclick="window.print()" class="btn btn-primary btn-lg px-5 fw-bold btn-print"><i class="fas fa-print me-2"></i>Print Mark Sheet</button>
</div>

<div class="marksheet-container">
    <div class="watermark">IBVTE</div>

    <!-- Header -->
    <div class="row align-items-center mb-4 pb-3 border-bottom border-2 border-primary">
        <div class="col-2 text-center">
            <img src="../assets/images/logo.jpeg" class="header-logo" alt="IBVTE Logo">
        </div>
        <div class="col-10 text-center pe-5">
            <h2 class="board-title mb-1">INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION</h2>
            <p class="mb-0 text-muted small fw-bold">Autonomous Board Registered under NCT of Delhi, Government of India</p>
            <p class="mb-0 text-muted small">60 Futa Road, Samar Garden Colony, Meerut (UP) – 250002</p>
            <h5 class="mt-3 fw-bold text-decoration-underline text-primary">OFFICIAL STATEMENT OF MARKS</h5>
        </div>
    </div>

    <!-- Student Info -->
    <div class="row mb-4">
        <div class="col-9">
            <table class="table table-borderless table-sm">
                <tr><td width="160"><strong>Roll Number:</strong></td><td><?= formatRollNumber($s['roll_number'] ?? '') ?></td></tr>
                <tr><td><strong>Registration No.:</strong></td><td><?= $s['registration_number'] ?></td></tr>
                <tr><td><strong>Student Name:</strong></td><td class="fw-bold"><?= strtoupper($s['full_name']) ?></td></tr>
                <tr><td><strong>Father's Name:</strong></td><td>MR. <?= strtoupper($s['father_name']) ?></td></tr>
                <tr><td><strong>Course Name:</strong></td><td class="fw-bold"><?= strtoupper($s['course_name']) ?></td></tr>
                <tr><td><strong>Institution:</strong></td><td class="small"><?= strtoupper($s['institution_name'] ?? $s['training_center'] ?? '') ?></td></tr>
                <tr><td><strong>Exam Session:</strong></td><td><?= $s['session_year'] ?></td></tr>
            </table>
        </div>
        <div class="col-3 text-center">
            <?php 
            $photo = $s['photo_path'] ?: 'assets/images/avatar.png';
            $photoUrl = (strpos($photo, 'http') === 0) ? $photo : '../' . $photo;
            ?>
            <img src="<?= $photoUrl ?>" class="border p-1" style="width:110px;height:130px;object-fit:cover;background:#fff;">
        </div>
    </div>

    <!-- Marks Table -->
    <table class="table table-bordered marks-table text-center align-middle mb-4">
        <thead>
            <tr>
                <th width="50">S.No.</th>
                <th class="text-start">Subject Name</th>
                <th width="100">Max Marks</th>
                <th width="100">Min Pass</th>
                <th width="120">Obtained</th>
            </tr>
        </thead>
        <tbody>
            <!-- Theory Section -->
            <?php if (!empty($theorySubjects)): ?>
            <tr><td colspan="5" class="bg-light text-start ps-3 fw-bold small">PART A: THEORY SUBJECTS</td></tr>
            <?php $sn = 1; foreach($theorySubjects as $sub): ?>
            <tr>
                <td><?= $sn++ ?></td>
                <td class="text-start"><?= $sub['subject_name'] ?></td>
                <td><?= $sub['max_marks'] ?></td>
                <td><?= $sub['pass_marks'] ?? round($sub['max_marks'] * 0.33) ?></td>
                <td class="fw-bold text-primary"><?= $sub['obtained_marks'] ?? '0' ?></td>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>

            <!-- Practical Section -->
            <?php if (!empty($practicalSubjects)): ?>
            <tr><td colspan="5" class="bg-light text-start ps-3 fw-bold small">PART B: PRACTICAL / VIVA-VOCE</td></tr>
            <?php foreach($practicalSubjects as $sub): ?>
            <tr>
                <td><?= $sn++ ?></td>
                <td class="text-start"><?= $sub['subject_name'] ?></td>
                <td><?= $sub['max_marks'] ?></td>
                <td><?= $sub['pass_marks'] ?? round($sub['max_marks'] * 0.40) ?></td>
                <td class="fw-bold text-primary"><?= $sub['obtained_marks'] ?? '0' ?></td>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
        <tfoot class="bg-light h5 fw-bold">
            <tr>
                <td colspan="2" class="text-end pe-4">GRAND TOTAL</td>
                <td><?= $s['total_marks'] ?></td>
                <td>-</td>
                <td class="text-primary"><?= $s['marks_obtained'] ?></td>
            </tr>
        </tfoot>
    </table>

    <!-- Result Summary -->
    <div class="row mt-4">
        <div class="col-4">
            <div class="p-3 border rounded text-center">
                <div class="small text-muted">PERCENTAGE</div>
                <div class="h4 fw-bold mb-0"><?= number_format($s['percentage'], 2) ?>%</div>
            </div>
        </div>
        <div class="col-4">
            <div class="p-3 border rounded text-center">
                <div class="small text-muted">DIVISION</div>
                <div class="h4 fw-bold mb-0"><?= strtoupper($s['division']) ?></div>
            </div>
        </div>
        <div class="col-4">
            <div class="p-3 border rounded text-center">
                <div class="small text-muted">RESULT STATUS</div>
                <div class="h4 fw-bold mb-0 <?= $s['status']=='passed'?'text-success':'text-danger' ?>">
                    <?= $s['status'] == 'passed' ? 'PASS' : 'FAIL' ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <div class="row footer-sign text-center">
        <div class="col-4">
            <div class="sign-box mt-5">Verified By</div>
        </div>
        <div class="col-4">
            <div class="mt-4"><img src="../assets/img/qr-placeholder.png" style="width:80px;opacity:0.3;"></div>
            <small class="text-muted d-block">Result Declared Date: <?= formatDate($s['updated_at']) ?></small>
        </div>
        <div class="col-4">
            <div class="sign-box mt-5">Controller of Examination</div>
        </div>
    </div>

    <div class="mt-5 pt-3 border-top text-center small text-muted">
        For verification - Send documents to <strong>ibvtenewdelhi@gmail.com</strong> | Website: www.ibvte.com
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
</body>
</html>
