<?php
/**
 * Print Student ID Card — parent portal
 * Print-optimised, no nav/footer. A6 format.
 */
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/../includes/canteen_helpers.php';

if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }

$conn     = portalGetConnection();
$parentId = (int)$_SESSION['parent_id'];
$studentId = (int)($_GET['id'] ?? 0);

if ($studentId <= 0) { header('Location: dashboard.php'); exit; }

$student = portalGetStudent($conn, $studentId, $parentId);
if (!$student) { header('Location: dashboard.php?error=unauthorized'); exit; }

$identityToken = (string)($student['identity_qr_token'] ?? '');
$studentName   = portalStudentDisplayName($student);
$studentCode   = (string)($student['student_id'] ?? '');
$studentClass  = (string)($student['class'] ?? '');
$photoUrl      = portalStudentPhoto($student);

// School settings
$settings = [];
$sRes = $conn->query("SELECT setting_key, setting_value FROM settings");
if ($sRes) {
    while ($row = $sRes->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}
$schoolName = (string)($settings['school_name'] ?? 'School');
$schoolLogo = (string)($settings['school_logo'] ?? '');
$logoUrl    = $schoolLogo ? (rtrim(BASE_URL, '/') . '/' . ltrim($schoolLogo, '/')) : '';

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ID Card — <?= htmlspecialchars($studentName) ?></title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
        }

        .card-wrap {
            background: #fff;
            width: 105mm;
            min-height: 148mm;
            border-radius: 8px;
            padding: 8mm;
            box-shadow: 0 4px 20px rgba(0,0,0,.15);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5mm;
        }

        .school-header {
            display: flex;
            align-items: center;
            gap: 8px;
            width: 100%;
        }
        .school-logo {
            width: 40px; height: 40px;
            border-radius: 6px; object-fit: cover;
        }
        .school-logo-placeholder {
            width: 40px; height: 40px;
            border-radius: 6px;
            background: linear-gradient(135deg, #16a34a, #0d6efd);
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-weight: 700; font-size: 1rem;
        }
        .school-name {
            font-size: .85rem; font-weight: 700;
            color: #111; line-height: 1.2; flex: 1;
        }

        .divider {
            width: 100%; height: 2px;
            background: linear-gradient(90deg, #16a34a, #0d6efd);
            border-radius: 2px;
        }

        .student-photo {
            width: 70px; height: 70px;
            border-radius: 50%; object-fit: cover;
            border: 3px solid #16a34a;
        }

        .student-name {
            font-size: 1.05rem; font-weight: 700;
            color: #111; text-align: center;
        }
        .student-meta {
            font-size: .78rem; color: #555;
            text-align: center; line-height: 1.8;
        }

        .qr-box {
            background: #fff;
            padding: 6px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
        }

        .card-note {
            font-size: .7rem; color: #777;
            text-align: center; line-height: 1.5;
            border-top: 1px solid #eee;
            padding-top: 4mm; width: 100%;
        }

        .print-btn {
            position: fixed; bottom: 20px; right: 20px;
            background: #16a34a; color: #fff; border: none;
            border-radius: 24px; padding: 10px 20px;
            font-size: .9rem; font-weight: 600; cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,0,0,.2);
        }

        @media print {
            body {
                background: #fff;
                padding: 0;
                display: block;
            }
            .card-wrap {
                box-shadow: none;
                width: 105mm;
                min-height: 148mm;
                margin: 0;
            }
            .print-btn { display: none; }

            @page {
                size: A6 portrait;
                margin: 0;
            }
        }
    </style>
</head>
<body>

<div class="card-wrap" id="idCard">

    <!-- School header -->
    <div class="school-header">
        <?php if ($logoUrl): ?>
        <img src="<?= htmlspecialchars($logoUrl) ?>" alt="School Logo" class="school-logo">
        <?php else: ?>
        <div class="school-logo-placeholder"><?= htmlspecialchars(mb_substr($schoolName, 0, 1)) ?></div>
        <?php endif; ?>
        <div class="school-name"><?= htmlspecialchars($schoolName) ?></div>
    </div>

    <div class="divider"></div>

    <!-- Student photo -->
    <img src="<?= htmlspecialchars($photoUrl) ?>" alt="Student photo" class="student-photo"
         onerror="this.src='https://placehold.co/70x70/16a34a/ffffff?text=<?= urlencode(mb_substr($studentName, 0, 1)) ?>'">

    <!-- Student info -->
    <div class="student-name"><?= htmlspecialchars($studentName) ?></div>
    <div class="student-meta">
        ID: <strong><?= htmlspecialchars($studentCode) ?></strong><br>
        Class: <?= htmlspecialchars($studentClass) ?>
    </div>

    <!-- QR code -->
    <?php if ($identityToken !== ''): ?>
    <div class="qr-box" id="qrPrint"></div>
    <?php else: ?>
    <div style="font-size:.8rem;color:#dc2626;text-align:center">
        No QR token generated yet.<br>Ask an admin to generate identity QR codes.
    </div>
    <?php endif; ?>

    <div class="card-note">
        Show this card at the school fee collection window.
    </div>

</div>

<button class="print-btn" onclick="window.print()">
    <i style="margin-right:6px">🖨</i> Print
</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<?php if ($identityToken !== ''): ?>
<script>
window.addEventListener('load', function () {
    var el = document.getElementById('qrPrint');
    if (el && typeof QRCode !== 'undefined') {
        new QRCode(el, {
            text:         <?= json_encode($identityToken) ?>,
            width:        200,
            height:       200,
            colorDark:    '#000',
            colorLight:   '#fff',
            correctLevel: QRCode.CorrectLevel.M
        });
    }
    // Auto-open print dialog after QR renders
    setTimeout(function () { window.print(); }, 600);
});
</script>
<?php endif; ?>
</body>
</html>
