<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<style>
/* ── QR Code Page ─────────────────────────────────────── */
.qr-card {
    border: none;
    border-radius: 16px;
    overflow: hidden;
    transition: box-shadow .2s, transform .2s;
    box-shadow: 0 2px 12px rgba(0,0,0,.07);
}
.qr-card:hover {
    box-shadow: 0 8px 28px rgba(0,0,0,.13);
    transform: translateY(-2px);
}

/* gradient banner */
.qr-card-header {
    background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
    padding: 20px 16px 48px;
    position: relative;
    text-align: center;
}
.qr-card-header .profile-name {
    color: #fff;
    font-size: .92rem;
    font-weight: 600;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.qr-card-header .profile-sub {
    color: rgba(255,255,255,.75);
    font-size: .75rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.qr-card-header .badge-status {
    position: absolute;
    top: 12px; right: 12px;
    font-size: .68rem;
    border-radius: 20px;
    padding: 3px 9px;
}

/* avatar — overlaps header/body */
.qr-avatar-wrap {
    position: absolute;
    bottom: -36px; left: 50%;
    transform: translateX(-50%);
}
.qr-avatar {
    width: 72px; height: 72px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #fff;
    box-shadow: 0 4px 14px rgba(0,0,0,.18);
    background: #e9ecef;
}

/* card body */
.qr-card-body {
    padding: 48px 16px 12px;
    text-align: center;
    background: #fff;
}

/* ── QR preview thumbnail ────────────────────────────── */
/* Clickable — opens the scan modal */
.qr-thumb-wrap {
    display: inline-block;
    cursor: pointer;
    border: 2px solid #e0e4ff;
    border-radius: 8px;
    background: #fff;
    padding: 4px;
    margin-bottom: 8px;
    transition: border-color .2s, box-shadow .2s;
}
.qr-thumb-wrap:hover {
    border-color: #6366f1;
    box-shadow: 0 0 0 3px rgba(99,102,241,.15);
}
.qr-thumb-wrap img {
    width: 180px;
    height: 180px;
    display: block;
    /* No border-radius — finder corners must reach the edge */
    border-radius: 0;
    /* Crisp downscale rendering */
    image-rendering: -webkit-optimize-contrast;
    image-rendering: crisp-edges;
    image-rendering: pixelated;
}
.qr-thumb-wrap .qr-scan-hint {
    font-size: .65rem;
    color: #6366f1;
    margin-top: 3px;
    letter-spacing: .01em;
}
.qr-empty-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 180px; height: 180px;
    border: 2px dashed #d0d5f5;
    border-radius: 8px;
    background: #f8f9ff;
    color: #adb5bd;
    margin: 0 auto 8px;
}

/* pills / meta */
.qr-date-pill {
    display: inline-block;
    background: #f0f4ff;
    color: #6366f1;
    font-size: .7rem;
    font-weight: 500;
    border-radius: 20px;
    padding: 2px 9px;
    margin-bottom: 6px;
}
.qr-url-line {
    font-size: .68rem;
    color: #868e96;
    word-break: break-all;
    margin-bottom: 10px;
    line-height: 1.4;
}

/* footer */
.qr-card-footer {
    background: #fafafa;
    border-top: 1px solid #f0f0f0;
    padding: 10px 12px;
}
.qr-card-footer .btn { border-radius: 8px; font-size: .78rem; font-weight: 500; }

/* stats bar */
.qr-stats-bar {
    background: #fff;
    border-radius: 14px;
    padding: 14px 24px;
    box-shadow: 0 2px 10px rgba(0,0,0,.06);
    margin-bottom: 24px;
}
.qr-stats-bar .stat-item { text-align: center; flex: 1; }
.qr-stats-bar .stat-num  { font-size: 1.6rem; font-weight: 700; line-height: 1; }
.qr-stats-bar .stat-label{ font-size: .72rem; color: #868e96; margin-top: 2px; }
.qr-stats-bar .divider   { width: 1px; background: #eee; align-self: stretch; margin: 0 12px; }

/* ── Scan Modal ──────────────────────────────────────── */
#qrScanModal .modal-content {
    background: #111;
    border: none;
    border-radius: 16px;
}
#qrScanModal .modal-header {
    border-bottom: 1px solid #333;
    padding: 14px 20px;
}
#qrScanModal .modal-title { color: #fff; font-size: 1rem; }
#qrScanModal .btn-close { filter: invert(1); }
#qrScanModal .modal-body {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24px 20px;
}
/* The actual QR image in the modal — no transforms, no radius */
#modalQrImg {
    /* Fill up to 90 vmin so it's large on any phone */
    width: min(480px, 90vmin);
    height: min(480px, 90vmin);
    display: block;
    border-radius: 0;           /* finder corners must NOT be clipped */
    image-rendering: -webkit-optimize-contrast;
    image-rendering: crisp-edges;
    image-rendering: pixelated;
    background: #fff;
    padding: 0;
    border: 6px solid #fff;    /* white quiet-zone border — helps scanners */
    box-shadow: 0 0 0 1px #444;
}
.scan-instruction {
    color: #aaa;
    font-size: .82rem;
    margin-top: 16px;
    text-align: center;
}
.scan-instruction strong { color: #fff; }
.modal-qr-name {
    color: #ccc;
    font-size: .78rem;
    margin-top: 8px;
}
</style>

<!-- ── Page Header ───────────────────────────────────── -->
<div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-2">
    <div>
        <h4 class="page-title mb-0">
            <i class="bi bi-qr-code me-2 text-primary"></i><?= lang('Admin.qr_codes') ?>
        </h4>
        <div class="text-muted small mt-1">Generate, scan &amp; manage QR codes · click any QR to scan</div>
    </div>
</div>

<?php
    $total     = count($profiles);
    $generated = array_filter($profiles, fn($p) => !empty($p['qr_file']));
    $pending   = $total - count($generated);
?>

<!-- ── Stats Bar ─────────────────────────────────────── -->
<?php if ($total > 0): ?>
<div class="qr-stats-bar d-flex align-items-center">
    <div class="stat-item">
        <div class="stat-num text-dark"><?= $total ?></div>
        <div class="stat-label">Total Profiles</div>
    </div>
    <div class="divider"></div>
    <div class="stat-item">
        <div class="stat-num text-success"><?= count($generated) ?></div>
        <div class="stat-label">QR Generated</div>
    </div>
    <div class="divider"></div>
    <div class="stat-item">
        <div class="stat-num text-warning"><?= $pending ?></div>
        <div class="stat-label">Pending</div>
    </div>
</div>
<?php endif; ?>

<!-- ── Cards Grid ────────────────────────────────────── -->
<div class="row g-4">
<?php if (empty($profiles)): ?>
    <div class="col-12">
        <div class="alert alert-info border-0 rounded-3">
            <i class="bi bi-info-circle me-2"></i>
            No profiles found. <a href="<?= site_url('admin/users/create') ?>">Add a profile</a> first.
        </div>
    </div>
<?php else: ?>

<?php foreach ($profiles as $p): ?>
<?php
    $qrDisk = FCPATH . 'uploads/' . ($p['qr_file'] ?? '');
    $qrTs   = (!empty($p['qr_file']) && file_exists($qrDisk)) ? filemtime($qrDisk) : 0;
    $hasQr  = !empty($p['qr_file']) && $qrTs > 0;
    $qrUrl  = $hasQr ? base_url('uploads/' . $p['qr_file']) . '?v=' . $qrTs : '';
?>
<div class="col-sm-6 col-lg-4 col-xl-3" id="profile-<?= $p['id'] ?>">
    <div class="qr-card card h-100">

        <!-- Header -->
        <div class="qr-card-header">
            <span class="badge-status badge <?= $p['is_active'] ? 'bg-success' : 'bg-secondary' ?>">
                <?= $p['is_active'] ? lang('Admin.active') : lang('Admin.inactive') ?>
            </span>
            <p class="profile-name unicode-text mt-1"><?= esc($p['name']) ?></p>
            <?php if (!empty($p['designation']) || !empty($p['company_name'])): ?>
            <p class="profile-sub unicode-text mb-0"><?= esc(trim(($p['designation'] ?? '') . ((!empty($p['designation']) && !empty($p['company_name'])) ? ' · ' : '') . ($p['company_name'] ?? ''))) ?></p>
            <?php endif; ?>
            <div class="qr-avatar-wrap">
                <img src="<?= profile_photo_url($p['profile_photo']) ?>" class="qr-avatar" alt="">
            </div>
        </div>

        <!-- Body -->
        <div class="qr-card-body">
            <?php if ($hasQr): ?>
            <!-- Clickable QR thumbnail → opens full-size scan modal -->
            <div class="qr-thumb-wrap mx-auto"
                 data-qr-url="<?= esc($qrUrl) ?>"
                 data-qr-name="<?= esc($p['name']) ?>"
                 onclick="openScanModal(this)"
                 title="Click to open full-size for scanning">
                <img src="<?= $qrUrl ?>" alt="QR – <?= esc($p['name']) ?>">
                <div class="qr-scan-hint"><i class="bi bi-fullscreen me-1"></i>Click to scan</div>
            </div>

            <?php if (!empty($p['generated_at'])): ?>
            <div class="qr-date-pill">
                <i class="bi bi-clock me-1"></i><?= date('d M Y, H:i', strtotime($p['generated_at'])) ?>
            </div>
            <?php endif; ?>
            <?php if (!empty($p['qr_url'])): ?>
            <div class="qr-url-line"><i class="bi bi-link-45deg"></i> <?= esc($p['qr_url']) ?></div>
            <?php endif; ?>

            <?php else: ?>
            <div class="qr-empty-box mx-auto">
                <i class="bi bi-qr-code" style="font-size:2.2rem;opacity:.3"></i>
                <span style="font-size:.72rem;margin-top:6px">Not generated</span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Footer -->
        <div class="qr-card-footer">
            <form action="<?= site_url('admin/qrcode/generate/'.$p['id']) ?>"
                  method="post" class="d-grid mb-2">
                <?= csrf_field() ?>
                <button type="submit" class="btn btn-<?= $hasQr ? 'outline-primary' : 'primary' ?> btn-sm">
                    <i class="bi bi-<?= $hasQr ? 'arrow-repeat' : 'qr-code' ?> me-1"></i>
                    <?= $hasQr ? lang('Admin.regenerate_qr') : lang('Admin.generate_qr') ?>
                </button>
            </form>

            <?php if ($hasQr): ?>
            <div class="d-flex gap-2">
                <a href="<?= site_url('admin/qrcode/download/'.$p['id']) ?>"
                   class="btn btn-outline-success btn-sm flex-grow-1">
                    <i class="bi bi-download me-1"></i><?= lang('Admin.download_qr') ?>
                </a>
                <button type="button"
                        class="btn btn-outline-danger btn-sm btn-del-qr"
                        data-id="<?= $p['id'] ?>"
                        data-name="<?= esc($p['name']) ?>">
                    <i class="bi bi-trash"></i>
                </button>
                <form id="qr-del-<?= $p['id'] ?>"
                      action="<?= site_url('admin/qrcode/delete/'.$p['id']) ?>"
                      method="post" class="d-none">
                    <?= csrf_field() ?>
                </form>
            </div>
            <?php endif; ?>
        </div>

    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>

<!-- ══════════════════════════════════════════════════════
     SCAN MODAL — full-size QR for reliable phone scanning
     No CSS transforms · no border-radius · no overflow clip
     480 × 480 px (or 90 vmin on small phones)
     ══════════════════════════════════════════════════════ -->
<div class="modal fade" id="qrScanModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:560px">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title">
                    <i class="bi bi-qr-code-scan me-2"></i>Scan QR Code
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- The QR image — rendered at full resolution, no distortion -->
                <img id="modalQrImg" src="" alt="QR Code">

                <div class="scan-instruction">
                    <strong>Hold your phone camera up to this QR code to scan.</strong><br>
                    Or click <em>Open full size</em> → scan from that browser tab for maximum resolution.
                </div>
                <div class="modal-qr-name" id="modalQrName"></div>

                <div class="mt-3 d-flex gap-2 flex-wrap justify-content-center">
                    <a id="modalDownloadBtn" href="#" class="btn btn-outline-light btn-sm">
                        <i class="bi bi-download me-1"></i>Download
                    </a>
                    <a id="modalOpenBtn" href="#" target="_blank" class="btn btn-outline-info btn-sm">
                        <i class="bi bi-box-arrow-up-right me-1"></i>Open full size
                    </a>
                    <button class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">
                        <i class="bi bi-x me-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
// ── Open scan modal ───────────────────────────────────────
function openScanModal(el) {
    const url  = el.dataset.qrUrl;
    const name = el.dataset.qrName;

    // Show QR at full resolution in the modal
    const img = document.getElementById('modalQrImg');
    img.src = '';          // force reload even if same URL
    img.src = url;

    document.getElementById('modalQrName').textContent = name;

    // "Open full size" — direct link to the raw PNG (native 1200 px)
    document.getElementById('modalOpenBtn').href = url;

    // Point download button to the admin download route
    const card = el.closest('[id^="profile-"]');
    if (card) {
        const pid = card.id.replace('profile-', '');
        document.getElementById('modalDownloadBtn').href =
            '<?= site_url('admin/qrcode/download/') ?>' + pid;
    }

    new bootstrap.Modal(document.getElementById('qrScanModal')).show();
}

// ── Delete confirmation ───────────────────────────────────
document.querySelectorAll('.btn-del-qr').forEach(btn => {
    btn.addEventListener('click', function () {
        const id   = this.dataset.id;
        const name = this.dataset.name;
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: '<?= lang('Admin.delete_qr') ?>?',
                text: name,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                confirmButtonText: '<?= lang('Admin.delete') ?>',
                cancelButtonText: '<?= lang('Admin.cancel') ?>',
            }).then(r => { if (r.isConfirmed) document.getElementById('qr-del-' + id).submit(); });
        } else {
            if (confirm('Delete QR for ' + name + '?')) {
                document.getElementById('qr-del-' + id).submit();
            }
        }
    });
});
</script>
<?= $this->endSection() ?>
