<?php
// generate_outpass.php
session_start();
require_once 'db.php';
require_once 'otp_sms_helper.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php'); exit;
}

$admin_full_name = isset($_SESSION['admin_name']) ? $_SESSION['admin_name'] : "Admin";

if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {
    die('Invalid request');
}
$id = (int)$_GET['id'];
// Fetch outpass + student details
$sql = "SELECT o.id, o.unique_reg_number, o.reason, o.photo_path, o.otp_verified, o.created_at,
               s.full_name, s.class_grade, s.section, s.admission_number, s.gender, s.dob,
               s.father_guardian_mobile, s.mother_mobile, s.school, o.returndate 
        FROM student_outpass o
        JOIN students s ON s.unique_reg_number = o.unique_reg_number
        WHERE o.id = ?";
$st = $conn->prepare($sql);
$st->bind_param("i", $id);
$st->execute();
$outpass = $st->get_result()->fetch_assoc();
$st->close();
if (!$outpass) { die('Outpass not found'); }
if ((int)$outpass['otp_verified'] !== 1) {
    die('OTP not verified for this outpass.');
}
$pageTitle = "Outpass - " . htmlspecialchars($outpass['full_name']);
require_once 'config.php';
include_once '_header.php';
include_once '_sidebar.php';
?>
<main class="container-fluid" id="appContent">
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap">
        <h5 class="mb-2">Student Outpass</h5>
        <div class="mb-2">
            <button class="btn btn-outline-primary me-2" id="printBtn">Print</button>
            <button class="btn btn-outline-success me-2" id="exportPdf">Export PDF</button>
            <button class="btn btn-outline-info" id="exportPng">Export PNG</button>
        </div>
    </div>

    <div class="card shadow" id="outpassCard" style="font-size: 10px; max-width: 540px; margin: auto;">
        <div class="card-body">
            <!-- Header Section with Logo -->
            <div class="text-center mb-2">
                <!-- <img src="./img/logo.png" alt="Logo" style="max-height:70px; margin-bottom:5px;"> -->
                
                <h2 class="fw-bold">Hostel Outpass</h2>
                <strong>LBS Boarding School, RIICO Institutional Area Ranpur, Kota, Rajasthan 324009</strong><br>
                <strong>Helpline: 7420899222 | lbsschool.in</strong>
                <hr class="my-2">
            </div>

            <div class="row g-3 mb-1">
                <div class="col-md-9">
                    <h5 class="mb-1"><?= htmlspecialchars($outpass['full_name']) ?></h5>
                    <table class="table table-borderless table-sm">
                        <tr>
                            <th>Reg No</th>
                            <td><?= htmlspecialchars($outpass['unique_reg_number']) ?></td>
                            <th>Admission No</th>
                            <td><?= htmlspecialchars($outpass['admission_number']) ?></td>
                        </tr>
                        <tr>
                            <th>School</th>
                            <td><?= htmlspecialchars($outpass['school']) ?></td>
                            <th>Class</th>
                            <td><?= htmlspecialchars($outpass['class_grade']) ?> <?= htmlspecialchars($outpass['section']) ?></td>
                        </tr>
                        <tr>
                            <th>Gender</th>
                            <td><?= htmlspecialchars($outpass['gender']) ?></td>
                            <th>DOB</th>
                            <td><?= htmlspecialchars($outpass['dob']) ?></td>
                        </tr>
                        <tr>
                            <th>Father Mobile</th>
                            <td><?= mask_middle4(htmlspecialchars($outpass['father_guardian_mobile'])) ?></td>
                            <th>Mother Mobile</th>
                            <td><?= mask_middle4(htmlspecialchars($outpass['mother_mobile'])) ?></td>
                        </tr>
                        <tr>
                            <th>Issued On</th>
                            <td><?= htmlspecialchars($outpass['created_at']) ?></td>
                             <th>Return Date</th>
                            <td><?= htmlspecialchars($outpass['returndate']) ?></td>
                        </tr>
                         <tr>
                            <th>Reason </th>
                            <td colspan="3"><div class="border rounded p-2 bg-light"><?= nl2br(htmlspecialchars($outpass['reason'])) ?></div></td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-3 text-center d-flex align-items-center">
                    <div class="border rounded p-2 w-100" style="min-height:120px">
                        <?php if (!empty($outpass['photo_path'])): ?>
                            <img src="<?= htmlspecialchars($outpass['photo_path']) ?>" style="max-width:100%;max-height:110px" alt="Current Photo">
                        <?php else: ?>
                            <small class="text-muted">No current photo</small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

    

            <!-- Signatures -->
            <div class="row mt-2">
                <div class="col-md-6 text-center">
                    <div class="mt-2">
                      <strong><?= htmlspecialchars($admin_full_name) ?></strong><br>
                        Authorized By (Sign & Stamp)
                    </div>
                </div>
                <div class="col-md-6 text-center">
                    <div class="mt-2">
                        ____________________________<br>
                        Warden/Administrator
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- Print Styles -->
<style>
@media print {
    #appContent .btn, nav, aside { display: none !important; }
    body { background: #fff; }
    .card { border: none !important; max-width: 450px; }
    img[alt="Logo"] { max-height: 50px; }
    a { color: blue !important; text-decoration: underline !important; }
}
</style>

<!-- jsPDF + html2canvas -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
// PDF Export (A5 single page with 10px top margin)
// PDF Export (A5 single page, compressed, 10px top margin)
document.getElementById('exportPdf').addEventListener('click', () => {
    const { jsPDF } = window.jspdf;
    const outpassElement = document.querySelector("#outpassCard");

    html2canvas(outpassElement, { scale: 1.5, useCORS: true }).then(canvas => {
        const imgData = canvas.toDataURL("image/jpeg", 0.7); // JPEG + 70% quality

        const pdf = new jsPDF('p', 'pt', 'a5');
        const pageWidth = pdf.internal.pageSize.getWidth();

        // Fit image to page width, keep aspect ratio
        const imgWidth = pageWidth - 20;   // 10px margin left/right
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        // Top margin = 10px
        pdf.addImage(imgData, "JPEG", 10, 10, imgWidth, imgHeight, undefined, "FAST");

        // Add clickable school link at bottom
        const pageHeight = pdf.internal.pageSize.getHeight();
        pdf.setTextColor(0, 0, 255);

        pdf.save("outpass_<?= $outpass['unique_reg_number'] ?>.pdf");
    });
});

// PNG Export (A5 portrait)
document.getElementById('exportPng').addEventListener('click', () => {
    const outpassElement = document.querySelector("#outpassCard");
    html2canvas(outpassElement, { scale: 2, useCORS: true }).then(canvas => {
        const targetWidth = 794;
        const targetHeight = 1123;

        const resizedCanvas = document.createElement("canvas");
        resizedCanvas.width = targetWidth;
        resizedCanvas.height = targetHeight;
        const ctx = resizedCanvas.getContext("2d");

        const imgHeight = (canvas.height * targetWidth) / canvas.width;
        const yPos = (targetHeight - imgHeight) / 2;
        ctx.drawImage(canvas, 0, yPos, targetWidth, imgHeight);

        let link = document.createElement("a");
        link.download = "outpass_<?= $outpass['unique_reg_number'] ?>.png";
        link.href = resizedCanvas.toDataURL("image/png");
        link.click();
    });
});




</script>
<script>
document.getElementById("printBtn").addEventListener("click", () => {
    if (window.AndroidApp) {
        // WebView → call native
        AndroidApp.triggerPrint();
    } else {
        // Browser → fallback
        window.print();
    }
});
</script>
<?php include_once 'footer.php'; ?>
