<?php
/**
 * Print individual student ID card.
 * Access: any authenticated user (shared link from student profile).
 * Query: ?id=STUDENT_ID
 */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

$student_id = (int) ($_GET['id'] ?? 0);
if (!$student_id) {
    http_response_code(400);
    exit('Missing student ID.');
}

$conn = getDBConnection();

$stmt = $conn->prepare(
    "SELECT id, first_name, last_name, class, student_id AS student_code,
            photo_path, identity_qr_token
     FROM students WHERE id = ? LIMIT 1"
);
$stmt->bind_param('i', $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    http_response_code(404);
    exit('Student not found.');
}

// Auto-generate identity QR if missing
if (empty($student['identity_qr_token'])) {
    $token = canteen_generate_identity_token($student['id']);
    $now   = date('Y-m-d H:i:s');
    $uStmt = $conn->prepare(
        "UPDATE students SET identity_qr_token = ?, identity_qr_generated_at = ? WHERE id = ?"
    );
    $uStmt->bind_param('ssi', $token, $now, $student['id']);
    $uStmt->execute();
    $uStmt->close();
    $student['identity_qr_token'] = $token;
}

// School name
$school_name = 'School';
$school_logo = null;
$sRes = $conn->query("SELECT setting_key, setting_value FROM settings
                      WHERE setting_key IN ('school_name','school_logo')");
while ($r = $sRes->fetch_assoc()) $school_info[$r['setting_key']] = $r['setting_value'];
$school_name = $school_info['school_name'] ?? 'School';
$school_logo = $school_info['school_logo'] ?? null;

$conn->close();

$full_name    = htmlspecialchars($student['first_name'] . ' ' . $student['last_name']);
$class_name   = htmlspecialchars($student['class'] ?? '');
$student_code = htmlspecialchars($student['student_code'] ?? '');
$qr_token     = htmlspecialchars($student['identity_qr_token']);

$photo_url = '';
if (!empty($student['photo_path']) && file_exists('../' . $student['photo_path'])) {
    $photo_url = '../' . $student['photo_path'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ID Card — <?php echo $full_name; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f1f5f9; font-family: 'Arial', sans-serif; display: flex; flex-direction: column; align-items: center; min-height: 100vh; padding: 2rem 1rem; }

        .print-btn {
            margin-bottom: 1.5rem;
            padding: .6rem 1.5rem;
            background: #1e3a5f;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            cursor: pointer;
            display: flex; align-items: center; gap: .5rem;
        }
        .print-btn:hover { background: #1e40af; }

        /* A6 card */
        .id-card {
            width: 105mm;
            min-height: 148mm;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0,0,0,.15);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        .card-header {
            background: linear-gradient(135deg, #1e3a5f, #1e40af);
            color: #fff;
            padding: 12px 16px;
            display: flex; align-items: center; gap: 10px;
        }
        .card-header .logo { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; background: #fff; }
        .card-header .logo-placeholder { width: 36px; height: 36px; border-radius: 50%; background: rgba(255,255,255,.2); display: flex; align-items: center; justify-content: center; font-size: 1.2rem; }
        .card-header .school-name { font-size: .75rem; font-weight: 700; line-height: 1.2; }
        .card-header .card-type { font-size: .6rem; opacity: .8; }

        .card-body { flex: 1; padding: 16px; display: flex; flex-direction: column; align-items: center; }
        .student-photo {
            width: 70px; height: 70px; border-radius: 50%;
            object-fit: cover; border: 3px solid #1e3a5f;
            margin-bottom: 10px;
        }
        .photo-placeholder {
            width: 70px; height: 70px; border-radius: 50%;
            background: #e2e8f0; display: flex; align-items: center;
            justify-content: center; font-size: 2rem; color: #94a3b8;
            border: 3px solid #1e3a5f; margin-bottom: 10px;
        }
        .student-name { font-size: .95rem; font-weight: 700; color: #1e293b; text-align: center; margin-bottom: 4px; }
        .student-meta { font-size: .72rem; color: #475569; text-align: center; margin-bottom: 12px; }
        .student-meta span { background: #f1f5f9; padding: 2px 8px; border-radius: 20px; margin: 2px; display: inline-block; }

        #qrcode { margin: 8px 0; }
        #qrcode canvas, #qrcode img { display: block !important; }

        .qr-note { font-size: .6rem; color: #64748b; text-align: center; margin-top: 6px; }

        .card-footer-bar {
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            padding: 8px 16px;
            font-size: .6rem;
            color: #94a3b8;
            text-align: center;
        }

        @media print {
            @page { size: A6 portrait; margin: 0; }
            body { background: #fff; padding: 0; }
            .print-btn { display: none; }
            .id-card { box-shadow: none; border-radius: 0; width: 105mm; min-height: 148mm; page-break-after: always; }
        }
    </style>
</head>
<body>

<button class="print-btn" onclick="window.print()">
    <i class="fas fa-print"></i> Print ID Card
</button>

<div class="id-card">
    <div class="card-header">
        <?php if ($school_logo && file_exists('../' . $school_logo)): ?>
            <img src="../<?php echo htmlspecialchars($school_logo); ?>" class="logo" alt="">
        <?php else: ?>
            <div class="logo-placeholder"><i class="fas fa-school"></i></div>
        <?php endif; ?>
        <div>
            <div class="school-name"><?php echo htmlspecialchars($school_name); ?></div>
            <div class="card-type">Student ID Card</div>
        </div>
    </div>

    <div class="card-body">
        <?php if ($photo_url): ?>
            <img src="<?php echo htmlspecialchars($photo_url); ?>" class="student-photo" alt="">
        <?php else: ?>
            <div class="photo-placeholder"><i class="fas fa-user"></i></div>
        <?php endif; ?>

        <div class="student-name"><?php echo $full_name; ?></div>
        <div class="student-meta">
            <span><?php echo $class_name; ?></span>
            <span><?php echo $student_code; ?></span>
        </div>

        <div id="qrcode"></div>
        <div class="qr-note">Show at the fee collection window</div>
    </div>

    <div class="card-footer-bar">
        <?php echo htmlspecialchars($school_name); ?> &nbsp;·&nbsp; <?php echo date('Y'); ?>
    </div>
</div>

<script>
new QRCode(document.getElementById('qrcode'), {
    text: <?php echo json_encode($qr_token); ?>,
    width: 140,
    height: 140,
    colorDark: '#1e293b',
    colorLight: '#ffffff',
    correctLevel: QRCode.CorrectLevel.M
});
// Auto-print after QR renders
setTimeout(() => window.print(), 700);
</script>
</body>
</html>
