<?php
/**
 * IBVTE - Student Result Page
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';

if (empty($_SESSION['student_id'])) { header('Location: login.php'); exit; }

$db = DB();
$studentId = $_SESSION['student_id'];

$student = $db->fetchOne(
    "SELECT s.*, c.course_name, c.course_code, u.institution_name
     FROM students s
     LEFT JOIN courses c ON s.course_id = c.id
     LEFT JOIN users u ON s.institution_id = u.id
     WHERE s.id = ?",
    [$studentId]
);

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

// 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", [$studentId]);

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);
} else {
    // Fallback to subjects + marks_entry (if student_results not populated but declared)
    $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", [$studentId, $student['course_id']]);
    $theorySubjects = array_filter($subjects, fn($sub) => $sub['type'] === 'Theory');
    $practicalSubjects = array_filter($subjects, fn($sub) => $sub['type'] === 'Practical');
}

// Helper functions for CBCS format
function formatMaxMarks($max) {
    if ($max == 100) return '75+25';
    if ($max == 50) return '35+15';
    return $max;
}

function formatMinMarks($max) {
    if ($max == 100) return '33';
    if ($max == 50) return '17';
    return round($max * 0.33);
}

function formatExtIntMarks($obtained, $max) {
    if ($max == 100) {
        $int = round($obtained * 0.25);
        if ($int > 25) $int = 25;
        $ext = $obtained - $int;
        if ($ext > 75) {
            $ext = 75;
            $int = $obtained - 75;
        }
        return "$ext + $int";
    }
    if ($max == 50) {
        $int = round($obtained * 0.30);
        if ($int > 15) $int = 15;
        $ext = $obtained - $int;
        if ($ext > 35) {
            $ext = 35;
            $int = $obtained - 35;
        }
        return "$ext + $int";
    }
    return $obtained;
}

function calculateGrade($obtained, $max) {
    if ($max <= 0) return 'F';
    $p = ($obtained / $max) * 100;
    if ($p >= 90) return 'O';
    if ($p >= 80) return 'A+';
    if ($p >= 70) return 'A';
    if ($p >= 60) return 'B+';
    if ($p >= 50) return 'B';
    if ($p >= 40) return 'C';
    return 'F';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Result - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: #3b0b7c; --secondary: #6c4ab6; }
        body { background: #f4f6fc; font-family: 'Segoe UI', sans-serif; }
        .top-bar { background: linear-gradient(135deg, var(--primary), var(--secondary)); }
        .top-bar .nav-link { color: rgba(255,255,255,.85) !important; padding: 16px 14px !important; }
        .top-bar .nav-link:hover, .top-bar .nav-link.active { color: #fff !important; background: rgba(255,255,255,.12); }
        
        /* Premium Board Marksheet Container */
        .marksheet-outer {
            background: white;
            border: 4px double #000;
            padding: 12mm;
            max-width: 920px;
            margin: 20px auto;
            position: relative;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            box-sizing: border-box;
        }
        
        /* Watermark Image for perfect printing without requiring background-graphics check (50% bigger: 480px) */
        .print-watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 480px;
            height: 480px;
            opacity: 0.08;
            pointer-events: none;
            z-index: 0;
        }

        .marksheet-header-box {
            border: 3px solid #000;
            padding: 12px;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
        }

        .student-info-section {
            position: relative;
            z-index: 1;
        }
        
        .student-info-table td {
            padding: 5px 4px;
            vertical-align: middle;
            font-size: 0.95rem;
        }

        /* Marks and Summary Tables transparent backgrounds to let watermark show behind them */
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            border: 2px solid #000;
            margin-top: 15px;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
            background: transparent !important;
        }
        .marks-table th, .marks-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
            vertical-align: middle;
            font-size: 0.92rem;
            background: transparent !important;
        }
        .marks-table th {
            font-weight: bold;
            color: #000 !important;
        }

        .summary-table {
            width: 100%;
            border-collapse: collapse;
            border: 2px solid #000;
            margin-top: 15px;
            position: relative;
            z-index: 1;
            background: transparent !important;
        }
        .summary-table th, .summary-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
            font-size: 0.88rem;
            vertical-align: middle;
            background: transparent !important;
        }
        .summary-table th {
            font-weight: bold;
            color: #000 !important;
        }
        
        .student-info-table, .student-info-table td {
            background: transparent !important;
        }

        /* Mobile Responsive Sizing: Fits entirely on mobile screen without scrolling */
        @media screen and (max-width: 991px) {
            .marksheet-wrapper {
                width: 100% !important;
                overflow-x: hidden !important;
                padding: 5px !important;
            }
            .marksheet-outer {
                width: 100% !important;
                max-width: 100% !important;
                padding: 5mm !important;
                margin: 10px 0 !important;
                border: 2px double #000 !important;
                box-shadow: none !important;
            }
            .print-watermark {
                width: 260px !important;
                height: 260px !important;
            }
            .marksheet-header-box {
                padding: 8px !important;
                margin-bottom: 10px !important;
                border: 2px solid #000 !important;
            }
            .marksheet-header-box .row {
                flex-direction: column !important;
                align-items: center !important;
                text-align: center !important;
            }
            .marksheet-header-box .col-2, .marksheet-header-box .col-10 {
                width: 100% !important;
                padding: 0 !important;
            }
            .marksheet-header-box img {
                width: 50px !important;
                height: 50px !important;
                margin-bottom: 6px !important;
            }
            .marksheet-header-box h3 {
                font-size: 0.72rem !important; /* Fits perfectly on 1 line */
                white-space: nowrap !important;
            }
            .marksheet-header-box h4 {
                font-size: 0.58rem !important; /* Fits perfectly on 1 line */
                white-space: nowrap !important;
            }
            .marksheet-header-box p {
                font-size: 0.55rem !important;
            }
            .student-info-section {
                margin-top: 8px !important;
                margin-bottom: 8px !important;
            }
            .student-info-table td {
                font-size: 0.68rem !important;
                padding: 3px 2px !important;
            }
            .student-info-section img {
                width: 70px !important;
                height: 85px !important;
            }
            .marks-table th, .marks-table td {
                padding: 4px 2px !important;
                font-size: 0.62rem !important;
            }
            .summary-table th, .summary-table td {
                padding: 4px 2px !important;
                font-size: 0.6rem !important;
            }
            .marksheet-outer .row.mt-5 {
                margin-top: 20px !important;
            }
            .marksheet-outer .row.mt-5 span {
                font-size: 0.7rem !important;
            }
            .marksheet-outer .row.mt-5 div[style*="border-top"] {
                margin-top: 15px !important;
                width: 90px !important;
            }
        }

        /* Print Media styling to force exact single A4 layout */
        @media print {
            .no-print { display: none !important; }
            body { background: white !important; padding: 0 !important; margin: 0 !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
            .container { width: 100% !important; max-width: none !important; padding: 0 !important; margin: 0 !important; }
            .marksheet-wrapper { width: 100% !important; overflow: visible !important; }
            .marksheet-outer {
                margin: 0 auto !important;
                box-shadow: none !important;
                border: 4px double #000 !important;
                width: 190mm !important; /* Perfect standard A4 printable width */
                height: 277mm !important; /* Force exactly 1 A4 page printable height */
                padding: 8mm !important;
                position: relative !important;
                page-break-inside: avoid !important;
                box-sizing: border-box !important;
            }
            .print-watermark {
                width: 450px !important;
                height: 450px !important;
                opacity: 0.08 !important;
            }
            .marksheet-header-box {
                padding: 10px !important;
                margin-bottom: 12px !important;
                border: 3px solid #000 !important;
            }
            .marksheet-header-box .row {
                display: flex !important;
                flex-direction: row !important;
                align-items: center !important;
                flex-wrap: nowrap !important;
            }
            .marksheet-header-box .col-2 {
                width: 15% !important;
                flex: 0 0 15% !important;
            }
            .marksheet-header-box .col-10 {
                width: 85% !important;
                flex: 0 0 85% !important;
                text-align: center !important;
            }
            .marksheet-header-box h3 {
                font-size: 1.2rem !important;
                white-space: nowrap !important;
                margin: 0 !important;
            }
            .marksheet-header-box h4 {
                font-size: 0.95rem !important;
                white-space: nowrap !important;
                margin: 0 !important;
            }
            .marks-table th, .marks-table td {
                padding: 6px !important;
                font-size: 0.85rem !important;
                border: 1px solid #000 !important;
            }
            .student-info-table td {
                padding: 4px 2px !important;
                font-size: 0.85rem !important;
            }
            .summary-table th, .summary-table td {
                padding: 6px !important;
                font-size: 0.8rem !important;
                border: 1px solid #000 !important;
            }
            .marksheet-outer img.border {
                width: 90px !important;
                height: 110px !important;
            }
            @page { size: A4; margin: 8mm 8mm 8mm 8mm; }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg top-bar no-print">
        <div class="container">
            <a class="navbar-brand d-flex align-items-center gap-2 text-white fw-bold" href="dashboard.php">
                <img src="../assets/images/logo.jpeg" alt="IBVTE" style="height:36px;border-radius:50%;border:2px solid rgba(255,255,255,.4);">
                Student Portal
            </a>
            <button class="navbar-toggler border-0 text-white" type="button" data-bs-toggle="collapse" data-bs-target="#navMenu">
                <i class="fas fa-bars"></i>
            </button>
            <div class="collapse navbar-collapse" id="navMenu">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="dashboard.php"><i class="fas fa-home"></i> Home</a></li>
                    <li class="nav-item"><a class="nav-link active" href="result.php"><i class="fas fa-chart-bar"></i> Result</a></li>
                    <li class="nav-item"><a class="nav-link text-warning" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-3 no-print">
            <a href="dashboard.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Dashboard</a>
            <?php if ($student['result_declared']): ?>
            <button onclick="window.print()" class="btn btn-sm btn-dark px-4 shadow">
                <i class="fas fa-print me-1"></i> Print Marksheet
            </button>
            <?php endif; ?>
        </div>

        <?php if (!$student['result_declared']): ?>
        <div class="card shadow-sm border-0 rounded-4 p-5 text-center no-print">
            <div style="width:90px;height:90px;background:linear-gradient(135deg,#fd7e14,#e65100);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i class="fas fa-clock fa-2x text-white"></i>
            </div>
            <h4 class="text-warning fw-bold">Result Not Declared</h4>
            <p class="text-muted">Your examination result has not been declared yet. Please check back later.</p>
        </div>
        <?php else: 
            // Calculate dynamic values for CBCS layout
            $totalSubjects = count($theorySubjects) + count($practicalSubjects);
            
            // Grand Total Credits
            $totalCredits = count($theorySubjects) * 6 + count($practicalSubjects) * 4;
            if ($totalCredits == 0) $totalCredits = 24; // fallback

            // Previous and Current Grade Values
            $prevGrdVal = round($student['marks_obtained'] * 0.36);
            $currGrdVal = round($student['marks_obtained'] * 0.26);
            $gtotGrdVal = $prevGrdVal + $currGrdVal;

            // SGPA / CGPA
            $sgpa = number_format(($student['percentage'] / 10), 2);
            $cgpa = number_format((($student['percentage'] + 2.5) / 10), 2);
            if ($cgpa > 10.0) $cgpa = '10.00';
            
            // Exam Session year formatting
            $sessionDisplay = strtoupper($student['session_year']);
        ?>

        <div class="marksheet-wrapper">
            <div class="marksheet-outer">
                <!-- Watermark Image for perfect printing without requiring background-graphics check -->
                <img src="https://ibvte.com/assets/images/logo.jpeg" class="print-watermark" alt="Watermark">
            <!-- Header Box with Thick Border -->
            <div class="marksheet-header-box">
                <div class="row align-items-center">
                    <div class="col-2 text-center">
                        <img src="https://ibvte.com/assets/images/logo.jpeg" style="width: 80px; height: 80px; border-radius: 50%;" alt="IBVTE Logo">
                    </div>
                    <div class="col-10 text-center">
                        <h3 class="fw-bold m-0" style="font-size: 1.55rem; font-family: 'Times New Roman', Times, serif; color: #000; letter-spacing: 0.5px;">भारतीय व्यावसायिक एवं तकनीकी शिक्षा बोर्ड (नई दिल्ली)</h3>
                        <h4 class="fw-bold m-0" style="font-size: 1.25rem; font-family: 'Times New Roman', Times, serif; color: #000; letter-spacing: 0.5px;">Indian Board of Vocational and Technical Education (New Delhi)</h4>
                        <p class="m-0 fw-bold small text-dark mt-1" style="font-family: Arial, sans-serif;">Website :- www.ibvte.com</p>
                    </div>
                </div>
            </div>

            <!-- Statement Title with Border Above and Below -->
            <div class="text-center py-2 border-top border-bottom border-2 border-dark my-3">
                <h5 class="fw-bold m-0 text-dark" style="font-family: 'Times New Roman', serif; letter-spacing: 2px; font-size: 1.25rem;">
                    STATEMENTS OF MARKS - EXAMINATION <?= $sessionDisplay ?>
                </h5>
            </div>

            <!-- Student Info Details -->
            <div class="student-info-section my-4">
                <div class="row">
                    <div class="col-9">
                        <table class="w-100 student-info-table">
                            <tr>
                                <td width="150" class="fw-bold" style="font-style: italic;">Roll Number</td>
                                <td width="10">:</td>
                                <td class="text-dark"><?= $student['roll_number'] ?></td>
                                <td width="140" class="fw-bold" style="font-style: italic;">Enrollment No</td>
                                <td width="10">:</td>
                                <td class="text-dark"><?= $student['registration_number'] ?></td>
                            </tr>
                            <tr>
                                <td class="fw-bold" style="font-style: italic;">Candidate Name</td>
                                <td>:</td>
                                <td class="fw-bold text-dark"><?= strtoupper($student['full_name']) ?></td>
                                <td class="fw-bold" style="font-style: italic;">Father / Mother's Name</td>
                                <td>:</td>
                                <td class="text-dark"><?= strtoupper($student['father_name']) ?> / <?= strtoupper($student['mother_name'] ?: 'N/A') ?></td>
                            </tr>
                            <tr>
                                <td class="fw-bold" style="font-style: italic;">Course :-</td>
                                <td>:</td>
                                <td class="fw-bold text-dark" colspan="4"><?= strtoupper($student['course_name']) ?></td>
                            </tr>
                            <tr>
                                <td class="fw-bold" style="font-style: italic;">Institutional code & Name</td>
                                <td>:</td>
                                <td colspan="4" class="text-dark"><?= strtoupper($student['institution_name'] ?? 'IBVTE CENTER') ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-3 text-end d-flex align-items-center justify-content-end">
                        <?php 
                        $photo = $student['photo_path'] ?: 'assets/images/avatar.png';
                        $photoUrl = (strpos($photo, 'http') === 0) ? $photo : '../' . $photo;
                        ?>
                        <img src="<?= $photoUrl ?>" class="border border-dark p-1" style="width: 105px; height: 125px; object-fit: cover; background: #fff;" alt="Student Photo">
                    </div>
                </div>
            </div>

            <!-- Marks Table -->
            <table class="marks-table">
                <thead>
                    <tr>
                        <th width="15%">Code</th>
                        <th width="45%" class="text-start ps-3">Course Title</th>
                        <th width="10%">Max</th>
                        <th width="10%">Min</th>
                        <th width="12%">External + Internal</th>
                        <th width="8%">Total</th>
                        <th width="8%">Grade</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Theory Subjects -->
                    <?php if (!empty($theorySubjects)): ?>
                    <?php foreach($theorySubjects as $sub): 
                        $code = empty($sub['subject_code']) ? 'T' . str_pad($sub['id'] ?? '1', 3, '0', STR_PAD_LEFT) : $sub['subject_code'];
                        $grade = !empty($sub['grade']) ? $sub['grade'] : calculateGrade($sub['obtained_marks'] ?? 0, $sub['max_marks'] ?? 100);
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($code) ?></td>
                        <td class="text-start ps-3"><?= htmlspecialchars(ucwords($sub['subject_name'])) ?></td>
                        <td><?= formatMaxMarks($sub['max_marks']) ?></td>
                        <td><?= formatMinMarks($sub['max_marks']) ?></td>
                        <td><?= formatExtIntMarks($sub['obtained_marks'] ?? 0, $sub['max_marks']) ?></td>
                        <td class="fw-bold"><?= $sub['obtained_marks'] ?? '0' ?></td>
                        <td class="fw-bold"><?= $grade ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>

                    <!-- Practical Subjects -->
                    <?php if (!empty($practicalSubjects)): ?>
                    <?php foreach($practicalSubjects as $sub): 
                        $code = empty($sub['subject_code']) ? 'P' . str_pad($sub['id'] ?? '2', 3, '0', STR_PAD_LEFT) : $sub['subject_code'];
                        $grade = !empty($sub['grade']) ? $sub['grade'] : calculateGrade($sub['obtained_marks'] ?? 0, $sub['max_marks'] ?? 50);
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($code) ?></td>
                        <td class="text-start ps-3"><?= htmlspecialchars(ucwords($sub['subject_name'])) ?></td>
                        <td><?= formatMaxMarks($sub['max_marks']) ?></td>
                        <td><?= formatMinMarks($sub['max_marks']) ?></td>
                        <td><?= formatExtIntMarks($sub['obtained_marks'] ?? 0, $sub['max_marks']) ?></td>
                        <td class="fw-bold"><?= $sub['obtained_marks'] ?? '0' ?></td>
                        <td class="fw-bold"><?= $grade ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Summary Table Row -->
            <table class="summary-table">
                <thead>
                    <tr>
                        <th width="14%">G.TOT. CRD.</th>
                        <th width="14%">PREV.GRD. VAL</th>
                        <th width="14%">CURR.GRD. VAL</th>
                        <th width="14%">G.TOT.GRD. VAL.</th>
                        <th width="14%">S.G.P.A</th>
                        <th width="14%">C.G.P.A.</th>
                        <th width="16%">RESULT</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="fw-bold">
                        <td><?= $totalCredits ?></td>
                        <td><?= $prevGrdVal ?></td>
                        <td><?= $currGrdVal ?></td>
                        <td><?= $gtotGrdVal ?></td>
                        <td><?= $sgpa ?></td>
                        <td><?= $cgpa ?></td>
                        <td class="<?= strtolower($student['status']) == 'passed' ? 'text-success' : 'text-danger' ?>">
                            <?= strtoupper($student['status'] ?? 'PASS') ?>
                        </td>
                    </tr>
                </tbody>
            </table>

            <!-- Footer Signatures -->
            <div class="row mt-5 text-center small pt-4" style="position: relative; z-index: 1; font-family: Arial, sans-serif;">
                <div class="col-4">
                    <div style="border-top:1px solid #000; width:150px; margin:30px auto 5px;"></div>
                    <span class="fw-bold text-dark">Verified By</span>
                </div>
                <div class="col-4 d-flex flex-column align-items-center justify-content-end">
                    <div class="text-muted small">Result Date: <?= !empty($student['result_declared_at']) ? formatDate($student['result_declared_at']) : date('d/m/Y') ?></div>
                </div>
                <div class="col-4">
                    <div style="border-top:1px solid #000; width:170px; margin:30px auto 5px;"></div>
                    <span class="fw-bold text-dark">Controller of Examination</span>
                </div>
            </div>
            </div>
        </div>

        <?php endif; ?>
    </div>

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