<?php

declare(strict_types=1);

require_once __DIR__ . '/../library/auth.php';

allow_roles(['admin', 'teacher']);

$school_id = (int) $_SESSION['school_id'];
$session_id = (int) ($_SESSION['session_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| REQUEST VALIDATION
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    exit('Invalid Request!');
}

/*
|--------------------------------------------------------------------------
| CSRF VALIDATION
|--------------------------------------------------------------------------
*/

if (
    empty($_POST['csrf_token']) ||
    $_POST['csrf_token'] !== $_SESSION['csrf_token']
) {

    exit('Invalid CSRF Token!');
}

$student_ids = $_POST['student_ids'] ?? [];
$exam_id     = (int) ($_POST['exam_id'] ?? 0);

if (
    empty($student_ids) ||
    $exam_id <= 0
) {

    exit('Required fields missing!');
}

/*
|--------------------------------------------------------------------------
| CLEAN STUDENT IDS
|--------------------------------------------------------------------------
*/

$student_ids = array_map('intval', $student_ids);

$student_ids = array_filter($student_ids);

$student_ids = array_unique($student_ids);

if (empty($student_ids)) {

    exit('Invalid students selected!');
}

/*
|--------------------------------------------------------------------------
| FETCH SCHOOL
|--------------------------------------------------------------------------
*/

$schoolStmt = $pdo->prepare("
    SELECT
        school_name,
        school_logo,
        school_address,
        school_phone
    FROM school_settings
    WHERE school_id = ?
    LIMIT 1
");

$schoolStmt->execute([$school_id]);

$school = $schoolStmt->fetch(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| FETCH EXAM
|--------------------------------------------------------------------------
*/

$examStmt = $pdo->prepare("
    SELECT
        id,
        exam_name
    FROM exam_types
    WHERE id = ?
    AND school_id = ?
    LIMIT 1
");

$examStmt->execute([
    $exam_id,
    $school_id
]);

$exam = $examStmt->fetch(PDO::FETCH_ASSOC);

if (!$exam) {

    exit('Invalid exam selected!');
}

/*
|--------------------------------------------------------------------------
| FETCH SESSION
|--------------------------------------------------------------------------
*/

$sessionStmt = $pdo->prepare("
    SELECT
        session_name
    FROM academic_sessions
    WHERE id = ?
    AND school_id = ?
    LIMIT 1
");

$sessionStmt->execute([
    $session_id,
    $school_id
]);

$currentSession = $sessionStmt->fetch(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| PLACEHOLDERS
|--------------------------------------------------------------------------
*/

$placeholders = implode(',', array_fill(0, count($student_ids), '?'));

$params = array_merge([
    $school_id,
    $session_id
], $student_ids);

/*
|--------------------------------------------------------------------------
| FETCH STUDENTS
|--------------------------------------------------------------------------
*/

$studentStmt = $pdo->prepare("
    SELECT

        s.id,
        s.name,
        s.photo,

        ss.roll_no,

        c.class_name,
        c.section,

        sp.father_name

    FROM student_sessions ss

    INNER JOIN students s
        ON s.id = ss.student_id

    INNER JOIN classes c
        ON c.id = ss.class_id

    LEFT JOIN student_parents sp
        ON sp.student_id = s.id
        AND sp.session_id = ss.session_id

    WHERE ss.school_id = ?
    AND ss.session_id = ?
    AND ss.student_id IN ($placeholders)
    AND ss.status = 'Active'

    ORDER BY ss.roll_no ASC
");

$studentStmt->execute($params);

$students = $studentStmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($students)) {

    exit('No students found!');
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>

        Print Admit Card

    </title>

    <style>

        @page {

            size: A4;
            margin: 8mm;

        }

        * {

            box-sizing: border-box;

        }

        body {

            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background: #f4f6f9;
            color: #222;

        }

        .page {

            width: 100%;
            page-break-after: always;

        }

        .admit-card {

            position: relative;

            width: 100%;
            min-height: 48%;

            background: #fff;

            border: 2px solid #1f2937;

            border-radius: 14px;

            padding: 22px;

            margin-bottom: 18px;

            overflow: hidden;

        }

        .top-bar {

            position: absolute;

            top: 0;
            left: 0;

            width: 100%;
            height: 10px;

            background: linear-gradient(
                90deg,
                #007bff,
                #6610f2
            );

        }

        .watermark {

            position: absolute;

            top: 50%;
            left: 50%;

            transform: translate(-50%, -50%);

            font-size: 70px;

            font-weight: bold;

            color: rgba(0,0,0,0.03);

            white-space: nowrap;

            pointer-events: none;

        }

        .header {

            display: flex;

            justify-content: space-between;

            align-items: center;

            border-bottom: 1px dashed #bbb;

            padding-bottom: 14px;

            margin-bottom: 18px;

        }

        .school-details {

            flex: 1;

        }

        .school-name {

            margin: 0;

            font-size: 28px;

            font-weight: 700;

            color: #111827;

        }

        .school-meta {

            margin-top: 6px;

            font-size: 13px;

            color: #555;

            line-height: 1.5;

        }

        .logo-box {

            width: 90px;
            height: 90px;

            border: 1px solid #ddd;

            border-radius: 10px;

            overflow: hidden;

            display: flex;

            align-items: center;

            justify-content: center;

            background: #fff;

        }

        .logo-box img {

            width: 100%;
            height: 100%;
            object-fit: contain;

        }

        .exam-title {

            text-align: center;

            margin-bottom: 20px;

        }

        .exam-title h2 {

            margin: 0;

            font-size: 24px;

            color: #007bff;

            letter-spacing: 1px;

        }

        .exam-title p {

            margin-top: 6px;

            color: #555;

            font-size: 14px;

        }

        .student-section {

            display: flex;

            gap: 20px;

        }

        .student-photo {

            width: 120px;
            height: 140px;

            border: 1px solid #ccc;

            border-radius: 8px;

            overflow: hidden;

            background: #fafafa;

            flex-shrink: 0;

            display: flex;

            align-items: center;

            justify-content: center;

        }

        .student-photo img {

            width: 100%;
            height: 100%;
            object-fit: cover;

        }

        .photo-placeholder {

            font-size: 12px;

            color: #999;

            text-align: center;

            padding: 10px;

        }

        .student-info {

            flex: 1;

        }

        .info-table {

            width: 100%;

            border-collapse: collapse;

        }

        .info-table td {

            padding: 10px 8px;

            border-bottom: 1px solid #eee;

            font-size: 14px;

        }

        .info-table td.label {

            width: 180px;

            font-weight: 700;

            color: #111827;

        }

        .badge {

            display: inline-block;

            padding: 4px 10px;

            background: #e9f2ff;

            border-radius: 30px;

            font-size: 12px;

            font-weight: 600;

            color: #007bff;

        }

        .footer {

            margin-top: 30px;

        }

        .signature-section {

            display: flex;

            justify-content: space-between;

            align-items: flex-end;

            margin-top: 40px;

        }

        .sign-box {

            width: 180px;

            text-align: center;

            font-size: 13px;

            color: #444;

        }

        .sign-line {

            border-top: 1px solid #333;

            margin-bottom: 8px;

            padding-top: 6px;

        }

        .card-id {

            position: absolute;

            top: 18px;
            right: 20px;

            font-size: 12px;

            color: #666;

            font-weight: bold;

        }

        .qr-box {

            position: absolute;

            bottom: 20px;
            right: 20px;

            width: 70px;
            height: 70px;

            border: 1px dashed #aaa;

            border-radius: 6px;

            display: flex;

            align-items: center;

            justify-content: center;

            font-size: 11px;

            color: #999;

        }

        @media print {

            body {

                background: #fff;

            }

        }

    </style>

</head>

<body onload="window.print()">

<?php

$chunks = array_chunk($students, 2);

foreach ($chunks as $chunk):

?>

<div class="page">

    <?php foreach ($chunk as $student): ?>

        <div class="admit-card">

            <div class="top-bar"></div>

            <div class="watermark">

                <?= htmlspecialchars($school['school_name'] ?? 'SCHOOL'); ?>

            </div>

            <div class="card-id">

                Admit ID :
                <?= (int) $student['id']; ?>

            </div>

            <!-- HEADER -->

            <div class="header">

                <div class="school-details">

                    <h1 class="school-name">

                        <?= htmlspecialchars($school['school_name'] ?? 'School'); ?>

                    </h1>

                    <div class="school-meta">

                        <?= htmlspecialchars($school['address'] ?? ''); ?>

                        <br>

                        Phone :
                        <?= htmlspecialchars($school['phone'] ?? ''); ?>

                    </div>

                </div>

                <div class="logo-box">

                    <?php if (!empty($school['school_logo'])): ?>

                        <img
                            src="../uploads/school/<?= htmlspecialchars($school['school_logo']); ?>"
                            alt="Logo"
                        >

                    <?php else: ?>

                        LOGO

                    <?php endif; ?>

                </div>

            </div>

            <!-- EXAM TITLE -->

            <div class="exam-title">

                <h2>

                    EXAM ADMIT CARD

                </h2>

                <p>

                    <?= htmlspecialchars($exam['exam_name']); ?>

                    |
                    Session :
                    <?= htmlspecialchars($currentSession['session_name'] ?? ''); ?>

                </p>

            </div>

            <!-- STUDENT -->

            <div class="student-section">

                <div class="student-photo">

                    <?php if (!empty($student['photo'])): ?>

                        <img
                            src="../uploads/student/<?= htmlspecialchars($student['photo']); ?>"
                            alt="Student"
                        >

                    <?php else: ?>

                        <div class="photo-placeholder">

                            Student Photo

                        </div>

                    <?php endif; ?>

                </div>

                <div class="student-info">

                    <table class="info-table">

                        <tr>

                            <td class="label">

                                Student Name

                            </td>

                            <td>

                                <strong>
                                    <?= htmlspecialchars($student['name']); ?>
                                </strong>

                            </td>

                        </tr>

                        <tr>

                            <td class="label">

                                Father Name

                            </td>

                            <td>

                                <?= htmlspecialchars($student['father_name'] ?? '-'); ?>

                            </td>

                        </tr>

                        <tr>

                            <td class="label">

                                Roll Number

                            </td>

                            <td>

                                <span class="badge">

                                    <?= htmlspecialchars($student['roll_no'] ?? '-'); ?>

                                </span>

                            </td>

                        </tr>

                        <tr>

                            <td class="label">

                                Class

                            </td>

                            <td>

                                <?= htmlspecialchars(
                                    $student['class_name'] .
                                    (!empty($student['section'])
                                        ? ' - ' . $student['section']
                                        : '')
                                ); ?>

                            </td>

                        </tr>

                    </table>

                </div>

            </div>

            <!-- FOOTER -->

            <div class="footer">

                <div class="signature-section">

                    <div class="sign-box">

                        <div class="sign-line"></div>

                        Student Signature

                    </div>

                    <div class="sign-box">

                        <div class="sign-line"></div>

                        Exam Controller

                    </div>

                    <div class="sign-box">

                        <div class="sign-line"></div>

                        Principal Signature

                    </div>

                </div>

            </div>

            <div class="qr-box">

                QR CODE

            </div>

        </div>

    <?php endforeach; ?>

</div>

<?php endforeach; ?>

</body>

</html>