<?php
/**
 * View / Print Student Result (Custom Format based on Image)
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin', 'college']);

$db = DB();
$id = $_GET['id'] ?? 0;

// Fetch student details
$student = $db->fetchOne("
    SELECT s.*, c.course_name, c.duration, u.institution_name, u.institution_code 
    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 = ?
", [$id]);

if (!$student) {
    die("Student not found.");
}

// Ensure dummy subjects matching the style
$dummySubjects = [
    ['name' => 'ANATOMY & PHYSIOLOGY', 'th_max' => 200, 'th_min' => 100, 'pr_max' => 100, 'pr_min' => 50, 'th_obt' => 12, 'ia_obt' => 73, 'pr_obt' => 56],
    ['name' => 'BIOCHEMISTRY',         'th_max' => 200, 'th_min' => 100, 'pr_max' => 100, 'pr_min' => 50, 'th_obt' => 13, 'ia_obt' => 70, 'pr_obt' => 60],
    ['name' => 'PATHOLOGY-I',          'th_max' => 200, 'th_min' => 100, 'pr_max' => 100, 'pr_min' => 50, 'th_obt' => 'A', 'ia_obt' => 80, 'pr_obt' => 50],
    ['name' => 'PATHOLOGY-II',         'th_max' => 200, 'th_min' => 100, 'pr_max' => 100, 'pr_min' => 50, 'th_obt' => 10, 'ia_obt' => 70, 'pr_obt' => 66]
];

// Determine total values
$total_th_max = 0;
$total_pr_max = 0;
$total_th_min = 0;
$total_pr_min = 0;
$grand_total_obtained = 0;

foreach ($dummySubjects as &$sub) {
    $th = ($sub['th_obt'] === 'A') ? 0 : intval($sub['th_obt']);
    $ia = intval($sub['ia_obt']);
    $sub['th_tot'] = $th + $ia;
    $sub['sub_tot'] = $sub['th_tot'] + intval($sub['pr_obt']);
    
    $total_th_max += $sub['th_max'];
    $total_pr_max += $sub['pr_max'];
    $total_th_min += $sub['th_min'];
    $total_pr_min += $sub['pr_min'];
    $grand_total_obtained += $sub['sub_tot'];
}
unset($sub);

$overall_max = $total_th_max + $total_pr_max;
$overall_min = $total_th_min + $total_pr_min;

// Function to convert number to words
function numberToWords($num) {
    $words = array('ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN');
    $tens = array('', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY');
    
    if ($num < 20) return $words[$num];
    if ($num < 100) return $tens[floor($num/10)] . ($num%10 ? ' ' . $words[$num%10] : '');
    if ($num < 1000) return $words[floor($num/100)] . ' HUNDRED' . ($num%100 ? ' ' . numberToWords($num%100) : '');
    return '...';
}
$words = numberToWords($grand_total_obtained);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Result - <?= htmlspecialchars($student['full_name']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f4f4f4; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; font-family: 'Arial', sans-serif; }
        .page-a4 {
            width: 210mm; min-height: 297mm; padding: 15mm; margin: 10mm auto;
            border: 1px #D3D3D3 solid; background: white;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); position: relative;
        }
        .header-title { font-size: 26px; font-weight: 900; text-align: center; margin-bottom: 5px; color: #000; }
        .sub-header { font-size: 14px; text-align: center; text-transform: uppercase; margin-bottom: 5px; }
        .session-header { font-size: 16px; text-align: center; margin-bottom: 20px; }
        
        .info-table { width: 100%; margin-bottom: 20px; font-size: 14px; font-weight: bold; }
        .info-table td { padding: 3px 0; }
        .info-label { width: 160px; text-transform: uppercase; }
        
        table.marks-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 13px; }
        table.marks-table th, table.marks-table td { border: 1px solid #000; text-align: center; padding: 5px; vertical-align: middle; }
        table.marks-table th { font-weight: bold; text-transform: uppercase; }
        .align-left { text-align: left !important; }
        
        .footer-text { font-size: 12px; margin-bottom: 10px; line-height: 1.5; font-weight: bold; }
        .disclaimer-text { font-size: 12px; line-height: 1.4; color: #333; margin-top: 30px; border-top: 1px dashed #ccc; padding-top: 10px; }
        .disclaimer-title { color: #dc3545; font-weight: bold; }
        
        @media print {
            body { background: none; margin: 0; padding: 0; }
            .page-a4 { margin: 0; border: none; box-shadow: none; width: 100%; padding: 0; }
            .no-print { display: none !important; }
        }
    </style>
</head>
<body>
    <div class="text-center mt-3 mb-3 no-print">
        <button class="btn btn-primary shadow" onclick="window.print()">Print Result</button>
        <a href="results.php" class="btn btn-outline-secondary ms-2">Back</a>
    </div>

    <div class="page-a4">
        
        <div class="header-title">Indian Board of Vocational & Technical Education</div>
        <div class="sub-header"><?= htmlspecialchars($student['course_name'] ?? 'DIPLOMA IN MEDICAL LAB TECHNOLOGY FIRST YEAR (2YDC)') ?></div>
        <div class="session-header">SESSION <?= htmlspecialchars($student['session_year'] ?? '2019-20') ?></div>

        <table class="info-table">
            <tr>
                <td class="info-label">TR Roll No</td>
                <td style="width: 20px;">:</td>
                <td style="font-size: 16px;"><?= htmlspecialchars($student['roll_number'] ?: '457845') ?></td>
            </tr>
            <tr>
                <td class="info-label">TR Enrolment No</td>
                <td>:</td>
                <td style="font-size: 16px;"><?= htmlspecialchars($student['registration_number'] ?: 'ASU145781A0S420') ?></td>
            </tr>
            <tr>
                <td class="info-label">STUDENT'S NAME</td>
                <td>:</td>
                <td style="font-size: 16px;"><?= htmlspecialchars($student['full_name']) ?></td>
            </tr>
            <tr>
                <td class="info-label">FATHER NAME</td>
                <td>:</td>
                <td style="font-size: 16px;"><?= htmlspecialchars($student['father_name'] ?: 'GAURAV KUMAR SINGH') ?></td>
            </tr>
            <tr>
                <td class="info-label">DOB</td>
                <td>:</td>
                <td style="font-size: 16px;"><?= $student['date_of_birth'] ? date('d-m-Y', strtotime($student['date_of_birth'])) : '24-05-1996' ?></td>
            </tr>
            <tr>
                <td class="info-label">EXAM CENTRE</td>
                <td>:</td>
                <td style="font-size: 16px;"><?= htmlspecialchars($student['institution_name'] ?? 'Indian Institue Of Para Medical Sciences') ?></td>
            </tr>
        </table>

        <table class="marks-table">
            <thead>
                <tr>
                    <th rowspan="3">S.N</th>
                    <th rowspan="3" class="align-left">SUBJECT</th>
                    <th colspan="4">SCHEME OF MARKS</th>
                    <th colspan="4">Marks OBTAINED</th>
                    <th rowspan="3">SUBJECT-TOTAL</th>
                    <th rowspan="3">RE-MARK</th>
                </tr>
                <tr>
                    <th colspan="2">THEORY+IA</th>
                    <th colspan="2">PRACTICAL</th>
                    <th rowspan="2">TH</th>
                    <th rowspan="2">IA</th>
                    <th rowspan="2">TH TOT</th>
                    <th rowspan="2">PR TOT</th>
                </tr>
                <tr>
                    <th>MAX</th>
                    <th>MIN</th>
                    <th>MAX</th>
                    <th>MIN</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($dummySubjects as $idx => $sub): ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td class="align-left fw-bold"><?= $sub['name'] ?></td>
                    <td><?= $sub['th_max'] ?></td>
                    <td><?= $sub['th_min'] ?></td>
                    <td><?= $sub['pr_max'] ?></td>
                    <td><?= $sub['pr_min'] ?></td>
                    <td class="fw-bold"><?= $sub['th_obt'] ?></td>
                    <td class="fw-bold"><?= $sub['ia_obt'] ?></td>
                    <td class="fw-bold"><?= $sub['th_tot'] ?></td>
                    <td class="fw-bold"><?= $sub['pr_obt'] ?></td>
                    <td class="fw-bold"><?= $sub['sub_tot'] ?></td>
                    <td>-</td>
                </tr>
                <?php endforeach; ?>
                <tr>
                    <td class="align-left fw-bold">#</td>
                    <td class="align-left fw-bold">TOTAL</td>
                    <td colspan="4" class="fw-bold"><?= $overall_min ?>/<?= $overall_max ?></td>
                    <td colspan="4" class="fw-bold text-center"><?= $grand_total_obtained ?>/<?= $overall_max ?></td>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>

        <div class="footer-text fw-normal">Abbreviation uesd—TH= THOERY, PR= PRACTICAL, TOT= TOTAL, MIN= MINIMUM, MAX= MAXIMUM, P=PAPER, G= GRACE, F= FAIL</div>
        
        <div class="footer-text mt-3">RESULT:- Compt in Human Anatomy & Physiology, Biochemistry, Pathology-1, Pathology-2</div>
        
        <div class="footer-text mt-3">TOTAL ( In Words):- <?= $words ?></div>
        
        <div class="footer-text mt-3">DATE OF RESULT - <?= $student['result_declared_at'] ? date('d F Y', strtotime($student['result_declared_at'])) : '25 December 2020' ?></div>

        <div class="disclaimer-text">
            <span class="disclaimer-title">DISCLAIMER (NOT OFFICIAL COPY):</span> Neither webmaster nor Result Hosting is responsible for any inadvertent error that may crept in the results being published on NET. The results published on net are immediate information for Students. This cannot be treated as original mark sheet. Original mark sheets will be issued by the Controller Of Examination office separately.
        </div>
        
    </div>
</body>
</html>
