<!DOCTYPE html>
<html>
<head>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">
<meta charset="UTF-8">
<title>Cetak Kartu Pelajar - MTsN 1 Wonogiri</title>
<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Segoe UI', 'Arial', sans-serif;
    background: #e2e8f0;
    margin: 0;
    padding: 20px;
}

/* ── PREVIEW HEADER ── */
.preview-header {
    background: #0f3b2c;
    color: white;
    padding: 12px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    position: sticky;
    top: 10px;
    z-index: 100;
}
.preview-header h2 {
    font-size: 1.2rem;
    font-weight: 600;
    margin: 0;
}
.preview-header p {
    font-size: 0.8rem;
    opacity: 0.8;
    margin: 4px 0 0;
}
.btn-back {
    background: #2c5f4c;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 40px;
    cursor: pointer;
    font-size: 0.8rem;
    margin-right: 8px;
    transition: 0.2s;
}
.btn-print {
    background: #e67e22;
    color: white;
    border: none;
    padding: 8px 20px;
    border-radius: 40px;
    cursor: pointer;
    font-size: 0.8rem;
    font-weight: bold;
}
.btn-back:hover {
    background: #1e3e31;
}
.btn-print:hover {
    background: #d35400;
}

/* ── PAGE SETUP ── */
@page {
    size: 200mm 300mm;
    margin: 0;
}

.pvc-sheet {
    width: 200mm;
    height: 300mm;
    background: white;
    position: relative;
    page-break-after: always;
    margin: 0 auto 20px;
    box-shadow: 0 12px 30px rgba(0,0,0,0.2);
}

/* 
   PERHITUNGAN YANG DISEPAKATI:
   ============================
   Horizontal (lebar 200mm):
   - Margin kiri: 7mm
   - Kartu kiri: 86mm
   - Jarak ke garis potong: 7mm
   - GARIS POTONG (100mm)
   - Jarak ke kartu kanan: 7mm
   - Kartu kanan: 86mm
   - Margin kanan: 7mm
   
   Vertikal (tinggi 300mm):
   - Margin atas: 5mm
   - 5 baris kartu @54mm = 270mm
   - 4 jarak antar baris @5mm = 20mm
   - Margin bawah: 5mm
   - Total: 5+270+20+5 = 300mm
*/

.sheet-container {
    width: 100%;
    height: 100%;
    position: relative;
}

/* Container kartu kiri dengan margin 7mm dari kiri */
.card-left-container {
    position: absolute;
    left: 7mm;
    top: 5mm;
    width: 86mm;
    height: calc(100% - 10mm);
    display: flex;
    flex-direction: column;
    gap: 5mm;
}

/* Container kartu kanan dengan jarak 7mm dari garis potong (100mm) */
.card-right-container {
    position: absolute;
    left: calc(100mm + 7mm);
    top: 5mm;
    width: 86mm;
    height: calc(100% - 10mm);
    display: flex;
    flex-direction: column;
    gap: 5mm;
}

/* ── CARD SIDE ── */
.card-side {
    width: 86mm;
    height: 54mm;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    border-radius: 2mm;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

/* Background depan */
.front-bg {
    background: linear-gradient(135deg, #03665c, #0b8b78);
}

/* Background belakang */
.back-bg {
    background: linear-gradient(145deg, #fef9e8, #f4ede1);
}

/* Background custom */
.card-side[style*="background-image"] {
    background-size: cover !important;
    background-position: center !important;
}

/* Area konten dalam kartu - margin internal 3mm setiap sisi */
.card-content {
    width: 80mm;
    height: 48mm;
    padding: 2mm 2.5mm;
    position: relative;
    display: flex;
    flex-direction: column;
}

/* ════════════════════════════════
   DEPAN
════════════════════════════════ */
.deco-c1, .deco-c2, .deco-c3 {
    position: absolute;
    border-radius: 50%;
    opacity: 0.12;
    background: #ffd700;
    pointer-events: none;
}
.deco-c1 {
    width: 30mm;
    height: 30mm;
    top: -6mm;
    right: -8mm;
}
.deco-c2 {
    width: 18mm;
    height: 18mm;
    top: 12mm;
    right: 8mm;
}
.deco-c3 {
    width: 12mm;
    height: 12mm;
    bottom: -3mm;
    left: -2mm;
}

.front-layout {
    display: flex;
    gap: 2mm;
    align-items: center;
    position: relative;
    z-index: 2;
    margin-top: 6mm; /* tambahkan ini untuk dorong ke bawah */
    margin-bottom: auto;
}

.logo-school {
    width: 20mm;
    height: 20mm;
    object-fit: contain;
    background: transparent !important;
    filter: none !important;
    mix-blend-mode: normal;
}

.logo-placeholder {
    width: 14mm;
    height: 14mm;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255,255,255,0.2);
    border-radius: 50%;
    font-size: 10pt;
    color: white;
}

.front-text {
    flex: 1;
    margin-left: 5mm;  /* tambahkan ini */
}

.card-title {
    font-size: 15pt;
    font-weight: 700;
    letter-spacing: 1px;
    color: #00695c;
    text-transform: uppercase;
    margin-bottom: 0.3mm;
}

.school-name {
    font-size: 12pt;
    font-weight: 800;
    color: #00695c;
    line-height: 1.15;
    margin-bottom: 0.3mm;
    text-shadow: 0 1px 1px rgba(0,0,0,0.2);
}

.school-details {
    font-size: 5pt;
    color: rgba(0, 0, 0, 0.8);
    line-height: 1.2;
    margin-bottom: 0.5mm;
}

/* ──────────────────────────────────────────
   DEPAN - MOTTO & QR SEJAJAR
   ────────────────────────────────────────── */
.front-divider {
    height: 0.2mm;
    background: rgba(255,255,255,0.3);
    margin: 0.3mm 0;
}

/* MOTTO strip */
.tagline-strip {
    background: rgba(0,0,0,0.2);
    border: 0.2mm solid rgba(255,255,255,0.25);
    border-radius: 1mm;
    padding: 0.4mm 1mm;
    text-align: center;
    flex: 1;
    min-width: 0;  /* penting agar bisa mengecil */
    word-wrap: break-word;  /* patahkan kata jika panjang */
    white-space: normal;  /* izinkan teks turun ke bawah */
}

.tagline-text {
    font-size: 7pt;
    font-weight: 700;
    color: #f0efce;
    font-style: italic;
    line-height: 1.2;
    word-break: break-word;  /* patahkan kata jika perlu */
}

/* QR Code - override untuk sejajar */
.front-qr {
    flex-shrink: 0;
    text-align: center;
    background: rgba(0,0,0,0.15);
    padding: 0.4mm;
    border-radius: 1.5mm;
    position: relative;
    right: auto;
    bottom: auto;
}
.front-qr img {
    display: block;
    width: 12mm;
    height: 12mm;
    background: white;
    padding: 0.4mm;
    border-radius: 1mm;
}
.front-qr-label {
    font-size: 2.5pt;
    color: rgba(255,255,255,0.7);
}

/* Layout sejajar MOTTO dan QR */
.card-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    position: relative;
}

.front-top {
    /* hapus position absolute */
    margin-bottom: auto;
}

.front-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 2mm;
    position: relative;
    top: -6mm;  /* nilai negatif = naik */
}

/* ════════════════════════════════
   BELAKANG
════════════════════════════════ */
.back-topbar {
    background: linear-gradient(90deg, #03665c, #0b8b78);
    padding: 1mm 2mm;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: -2mm -5.5mm 1.5mm -5.5mm;
    border-radius: 1.5mm 1.5mm 0 0;
}
.back-topbar-l {
    font-size: 3.8pt;
    font-weight: 700;
    letter-spacing: 0.5px;
    color: rgba(255,255,255,0.9);
    margin-left: 2mm;
}
.back-topbar-r {
    font-size: 3.8pt;
    font-weight: 600;
    letter-spacing: 0.5px;
    color: rgba(255,255,255,0.9);
    margin-right: 2mm;
}

.back-layout {
    display: flex;
    gap: 2mm;
    margin-bottom: 0.8mm;
}

.photo-area {
    width: 18mm;
    flex-shrink: 0;
}

.student-photo {
    width: 18mm;
    height: 22mm;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 0.3mm solid #c2b280;
    border-radius: 2mm;
    overflow: hidden;
    background: #e9e2ce;
}
.student-photo img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.data-info {
    flex: 1;
}

.data-row {
    display: flex;
    margin-bottom: 0.5mm;
    line-height: 1.2;
    font-size: 7pt;
}

.data-label {
    width: 11mm;  /* lebar tetap untuk label (NISN, Nama, dll) */
    font-weight: 700;
    color: #2c553e;
    flex-shrink: 0;  /* biar tidak mengecil */
    font-size: 7pt;
}

.data-colon {
    width: 2.5mm;  /* lebar tetap untuk titik dua */
    color: #6b5e3a;
    text-align: center;
    font-size: 7pt;
}

.data-val {
    flex: 1;
    color: #1e2f2a;
    font-size: 7pt;
}

.data-val-sm {
    font-size: 7pt;
    color: #1e2f2a;
    line-height: 1.2;
    flex: 1;  /* tambahkan ini biar sejajar */

}

.back-footer {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-top: auto;
    padding-top: 0.3mm;
    position: relative;
    top: 0mm;  /* tambahkan ini, nilai negatif = naik */
}

.validity-text {
    font-size: 5pt;
    color: #6b5a3e;
    background: #faf0dd;
    padding: 0.4mm 1mm;
    border-radius: 3px;
    max-width: 32mm;
}

.signature-box {
    text-align: center;
    font-size: 3.8pt;
}
.sign-place {
    color: #5a4b2e;
    font-size: 5pt;
    margin-bottom: 0.2mm;
}
.sign-title {
    font-weight: bold;
    margin: 0.2mm 0 0.2mm 0;
    font-size: 5pt;
    color: #2c553e;
}
.sign-area {
    position: relative;
    width: 28mm;
    height: 8mm;
    margin: 0 auto;
}
.stamp-container {
    position: absolute;
    left: -7mm;
    top: -6mm;
    width: 18mm;
    height: 18mm;
}
.stamp-container img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
.stamp-placeholder {
    width: 100%;
    height: 100%;
    border: 0.2mm dashed #cbd5e0;
    border-radius: 50%;
    opacity: 0.4;
}
.ttd-container {
    position: absolute;
    right: 5mm;
    top: -3mm;
    width: 22mm;
    height: 18mm;
}
.ttd-container img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
.sign-name {
    font-weight: 800;
    font-size: 6pt;
    color: #2c553e;
    margin-top: 0.2mm;
}
.sign-nip {
    font-size: 6pt;
    color: #7d6b48;
}

/* ── CUT GUIDES (GARIS POTONG) ── */
.cut-guide-vertical {
    position: absolute;
    left: 100mm;
    top: 0;
    bottom: 0;
    width: 0;
    border-left: 0.2mm dashed #e63946;
    pointer-events: none;
    z-index: 10;
    opacity: 0.6;
}

.cut-guide-horizontal {
    position: absolute;
    left: 0;
    right: 0;
    height: 0;
    border-top: 0.2mm dashed #ffaaa5;
    pointer-events: none;
    z-index: 10;
    opacity: 0.6;
}

/* ── PRINT OVERRIDES ── */
@media print {
    body {
        background: white;
        padding: 0;
        margin: 0;
    }
    .preview-header {
        display: none !important;
    }
    .pvc-sheet {
        margin: 0;
        box-shadow: none;
        page-break-after: always;
    }
    .cut-guide-vertical, .cut-guide-horizontal {
        opacity: 0.4;
        print-color-adjust: exact;
    }
    * {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        color-adjust: exact;
    }
}
</style>
</head>
<body>

<!-- Preview Header -->
<div class="preview-header">
    <div>
        <h2>📇 Cetak Kartu Pelajar</h2>
        <p><?= count($students) ?> siswa &nbsp;·&nbsp; PVC 200×300 mm &nbsp;·&nbsp; 5 kartu / lembar</p>
    </div>
    <div>
        <button class="btn-back" onclick="window.history.back()">← Kembali</button>
        <button class="btn-print" onclick="window.print()">🖨 Cetak / Simpan PDF</button>
    </div>
</div>

<?php
helper('card');

$cardDate = formatCardDate($settings['card_date'] ?? date('d F Y'));
$district = $settings['district'] ?? 'WONOGIRI';
$showQR   = !empty($settings['show_qrcode']);
$motto    = $settings['motto'] ?? 'Berilmu, Berakhlak, Berprestasi';
$pages    = array_chunk($students, 5);
?>

<?php foreach ($pages as $gi => $group): ?>
<div class="pvc-sheet">
    <!-- Garis potong -->
    <div class="cut-guide-vertical"></div>
    <div class="cut-guide-horizontal" style="top: 59mm;"></div>
    <div class="cut-guide-horizontal" style="top: 118mm;"></div>
    <div class="cut-guide-horizontal" style="top: 177mm;"></div>
    <div class="cut-guide-horizontal" style="top: 236mm;"></div>

    <div class="sheet-container">
        <!-- Kolom KIRI (kartu depan) -->
        <div class="card-left-container">
            <?php foreach ($group as $student): ?>
            <div class="card-side front-bg"
                style="<?= !empty($settings['front_background'])
                    ? 'background-image:url(' . base_url('uploads/card/' . $settings['front_background']) . ');background-size:cover;background-position:center'
                    : '' ?>">
                
                <?php if (empty($settings['front_background'])): ?>
                <div class="deco-c1"></div>
                <div class="deco-c2"></div>
                <div class="deco-c3"></div>
                <?php endif; ?>

                <div class="card-content">
                    <!-- Bagian Atas: Logo + Teks -->
                    <div class="front-top">
                        <div class="front-layout">
                            <?php 
                            $logoFile = !empty($settings['logo_image']) ? $settings['logo_image'] : '';
                            $logoUrl = '';
                            if (!empty($logoFile) && file_exists(FCPATH . 'uploads/logos/' . $logoFile)) {
                                $logoUrl = base_url('uploads/logos/' . $logoFile);
                            }
                            ?>
                            <?php if (!empty($logoUrl)): ?>
                            <img src="<?= $logoUrl ?>" class="logo-school" alt="Logo">
                            <?php else: ?>
                            <div class="logo-placeholder">🏫</div>
                            <?php endif; ?>

                            <div class="front-text">
                                <div class="card-title">KARTU PELAJAR</div>
                                <div class="school-name"><?= esc($settings['school_name'] ?? 'MTsN 1 Wonogiri') ?></div>
                                <div class="front-divider"></div>
                                <div class="school-details">
                                    <?php 
                                    $parts = [];
                                    
                                    if (!empty($settings['address'])) $parts[] = $settings['address'];
                                    if (!empty($settings['village'])) $parts[] = $settings['village'];
                                    
                                    $district = $settings['district'] ?? '';
                                    $city = $settings['city'] ?? '';
                                    
                                    if (!empty($district) && !empty($city) && $district === $city) {
                                        $parts[] = $district;
                                    } else {
                                        if (!empty($district)) $parts[] = $district;
                                        if (!empty($city)) $parts[] = $city;
                                    }
                                    
                                    if (!empty($settings['province'])) $parts[] = $settings['province'];
                                    if (!empty($settings['postal_code'])) $parts[] = $settings['postal_code'];
                                    
                                    echo esc(implode(', ', $parts));
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Bagian Bawah: MOTTO (kiri) sejajar dengan QR Code (kanan) -->
                    <div class="front-bottom">
                        <div class="tagline-strip">
                            <div class="tagline-text">"<?= esc($motto) ?>"</div>
                        </div>
                        <?php if ($showQR && !empty($student['nisn'])): ?>
                        <div class="front-qr">
                            <img src="<?= generateQRCode($student['nisn'], 3) ?>" alt="QR">
                            <div class="front-qr-label">NISN</div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Kolom KANAN (kartu belakang) -->
        <div class="card-right-container">
            <?php foreach ($group as $student): ?>
            <div class="card-side back-bg"
                 style="<?= !empty($settings['back_background'])
                    ? 'background-image:url(' . base_url('uploads/card/' . $settings['back_background']) . ');background-size:cover;background-position:center'
                    : '' ?>">
                <div class="card-content">
                    <div class="back-topbar">
                        <span class="back-topbar-l">IDENTITAS SISWA</span>
                        <span class="back-topbar-r"><?= esc($settings['school_name'] ?? '') ?></span>
                    </div>

                    <div class="back-layout">
                        <div class="photo-area">
                            <div class="student-photo">
                                <img src="<?= getStudentPhotoUrl($student['photo'] ?? '') ?>"
                                     alt="Foto"
                                     onerror="this.src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2EwYWVjMCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjZWRmMmY3Ii8+PHBhdGggZD0iTTEyIDEyYzIuMjEgMCA0LTEuNzkgNC00cy0xLjc5LTQtNC00LTQgMS43OS00IDQgMS43OSA0IDQgNHptMCAyYy0yLjY3IDAtOCAxLjM0LTggNHYyaDE2di0yYzAtMi42Ni01LjMzLTQtOC00eiIvPjwvc3ZnPg=='">
                            </div>
                        </div>
                        <div class="data-info">
                            <div class="data-row"><div class="data-label">NISN</div><div class="data-colon">:</div><div class="data-val"><?= esc($student['nisn'] ?? '-') ?></div></div>
                            <div class="data-row"><div class="data-label">Nama</div><div class="data-colon">:</div><div class="data-val"><strong><?= esc($student['full_name'] ?? '-') ?></strong></div></div>
                            <div class="data-row"><div class="data-label">TTL</div><div class="data-colon">:</div><div class="data-val"><?= formatStudentBirthInfo($student) ?></div></div>
                            <div class="data-row"><div class="data-label">L/P</div><div class="data-colon">:</div><div class="data-val"><?= formatGender($student['gender'] ?? 'L') ?></div></div>
                            <div class="data-row"><div class="data-label">Agama</div><div class="data-colon">:</div><div class="data-val"><?= esc($student['religion'] ?? '-') ?></div></div>
                            <div class="data-row"><div class="data-label">Alamat</div><div class="data-colon">:</div><div class="data-val-sm"><?= ucwords(strtolower(formatStudentAddress($student))) ?></div></div>
                        </div>
                    </div>

                    <div class="back-footer">
                        <div class="validity-text"><?= esc($settings['card_validity'] ?? 'Berlaku Selama Menjadi Siswa') ?></div>
                        <div class="signature-box">
                            <div class="sign-place"><?= esc($district) ?>, <?= $cardDate ?></div>
                            <div class="sign-title">Kepala Madrasah,</div>
                            <div class="sign-area">
                                <div class="stamp-container">
                                    <?php if (!empty($settings['school_stamp']) && file_exists(FCPATH . 'uploads/card/' . $settings['school_stamp'])): ?>
                                    <img src="<?= base_url('uploads/card/' . $settings['school_stamp']) ?>" alt="Cap">
                                    <?php else: ?>
                                    <div class="stamp-placeholder"></div>
                                    <?php endif; ?>
                                </div>
                                <div class="ttd-container">
                                    <?php if (!empty($settings['headmaster_signature']) && file_exists(FCPATH . 'uploads/card/' . $settings['headmaster_signature'])): ?>
                                    <img src="<?= base_url('uploads/card/' . $settings['headmaster_signature']) ?>" alt="TTD">
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="sign-name"><?= esc($settings['headmaster_name'] ?? 'H. Kusun Dahari, S.Pd.I., M.Pd') ?></div>
                            <?php if (!empty($settings['headmaster_nip'])): ?>
                            <div class="sign-nip">NIP. <?= esc($settings['headmaster_nip']) ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endforeach; ?>

<script>
document.addEventListener('keydown', e => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
});

window.addEventListener('load', function() {
    document.querySelectorAll('.logo-school').forEach(function(img) {
        img.style.background = 'transparent';
        img.style.backgroundColor = 'transparent';
    });
});
</script>
</body>
</html>