<?php
session_start();
$page_title = 'Menu QR Codes';
$active_nav = 'menu_qr';
include("includes/header.php");

// ── Build base scan URL ──────────────────────────────────────────────────────
$proto     = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
$host      = $_SERVER['HTTP_HOST'];
$self      = $_SERVER['PHP_SELF'];
$site_base = $proto . '://' . $host . preg_replace('/\/restaurantadmin\/.*/', '', $self);
$scan_base = $site_base . '/customer/scan.php';
$full_menu_url = $scan_base . '?rid=' . $__rid;

// ── Fetch categories ─────────────────────────────────────────────────────────
$cs = $conn->prepare("SELECT * FROM categories WHERE restaurant_id=? ORDER BY sort_order, name");
$cs->bind_param("i", $__rid); $cs->execute();
$categories = $cs->get_result()->fetch_all(MYSQLI_ASSOC);

// ── Fetch all menu items ─────────────────────────────────────────────────────
$ms = $conn->prepare("SELECT m.*, c.name AS cat_name FROM menu_items m LEFT JOIN categories c ON m.category_id=c.id WHERE m.restaurant_id=? ORDER BY c.sort_order, c.name, m.name");
$ms->bind_param("i", $__rid); $ms->execute();
$all_items = $ms->get_result()->fetch_all(MYSQLI_ASSOC);

// Group by category
$by_cat = []; $uncategorized = [];
foreach ($all_items as $item) {
    if ($item['category_id']) {
        $by_cat[$item['category_id']]['name']    = $item['cat_name'];
        $by_cat[$item['category_id']]['id']      = $item['category_id'];
        $by_cat[$item['category_id']]['items'][] = $item;
    } else { $uncategorized[] = $item; }
}

$total_items = count($all_items);
$total_cats  = count($categories);
$view = in_array($_GET['view'] ?? '', ['overview','categories','items']) ? $_GET['view'] : 'overview';
?>
<!-- QRCode.js — renders directly to canvas, no external image API needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<style>
.qr-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:16px}
.qr-card{background:var(--white);border:1.5px solid var(--border);border-radius:16px;overflow:hidden;display:flex;flex-direction:column;transition:box-shadow .2s,transform .2s}
.qr-card:hover{box-shadow:0 8px 24px rgba(34,90,227,.12);transform:translateY(-2px)}
.qr-card.is-featured{border:2.5px solid var(--primary)}
.qr-wrap{padding:18px 18px 10px;background:var(--bg);display:flex;align-items:center;justify-content:center;min-height:170px}
.qr-wrap canvas,.qr-wrap img{border-radius:8px;border:1px solid #E2E8F0;background:#fff;display:block!important}
.qr-body{padding:12px 14px;flex:1}
.qr-name{font-size:.88rem;font-weight:800;margin-bottom:3px;line-height:1.3}
.qr-price{font-size:.95rem;font-weight:800;color:var(--primary)}
.qr-hint{font-size:.7rem;color:var(--text-muted);margin-top:3px}
.qr-btns{padding:10px 12px;border-top:1px solid var(--border);display:flex;gap:6px}
.sep{font-size:.67rem;font-weight:700;text-transform:uppercase;letter-spacing:.14em;color:var(--text-muted);margin:26px 0 12px;display:flex;align-items:center;gap:10px}
.sep::after{content:'';flex:1;height:1px;background:var(--border)}
.vtab{padding:8px 16px;border-radius:10px;font-size:.83rem;font-weight:700;border:1.5px solid var(--border);background:var(--white);color:var(--text-muted);transition:all .2s;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
.vtab svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-linecap:round}
.vtab.on{background:var(--primary);color:#fff;border-color:var(--primary);box-shadow:var(--shadow-lg)}
.vtab:not(.on):hover{background:var(--bg)}
.hero{background:linear-gradient(135deg,#1a3dbd,var(--primary) 55%,#4f79ea);border-radius:18px;padding:24px 26px;display:flex;align-items:center;gap:20px;flex-wrap:wrap;margin-bottom:26px}
.hero-qr-box{width:86px;height:86px;background:#fff;border-radius:12px;padding:7px;flex-shrink:0;display:flex;align-items:center;justify-content:center}
.hero-qr-box canvas,.hero-qr-box img{border-radius:5px!important;border:none!important}
.hero-txt{flex:1;color:#fff;min-width:180px}
.hero-txt h2{font-size:1.05rem;font-weight:800;margin-bottom:5px}
.hero-txt p{font-size:.82rem;opacity:.78;line-height:1.6;margin-bottom:11px}
@media print{
  *{-webkit-print-color-adjust:exact!important;print-color-adjust:exact!important}
  .sidebar,.topbar,.hamburger,.hero,.vtab-row,.qr-btns,.no-print,.order-alert,.overlay{display:none!important}
  body,html{background:#fff!important}
  .layout{display:block!important}
  .main-content{margin:0!important;padding:12px!important}
  .qr-grid{grid-template-columns:repeat(3,1fr)!important;gap:10px!important}
  .qr-card{break-inside:avoid;border:1px solid #ddd!important;box-shadow:none!important;transform:none!important}
  @page{margin:1.2cm;size:A4}
}
</style>

<!-- Page header -->
<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:22px;flex-wrap:wrap;gap:12px" class="no-print">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Menu QR Codes</h1>
    <p style="color:var(--text-muted);font-size:.875rem"><?php echo $total_items; ?> items &bull; <?php echo $total_cats; ?> categories — print and place for customers to scan</p>
  </div>
  <button onclick="window.print()" class="btn btn-primary btn-md no-print">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
    Print This View
  </button>
</div>

<!-- Hero -->
<div class="hero no-print">
  <div class="hero-qr-box"><div id="hero-qr-el"></div></div>
  <div class="hero-txt">
    <h2>Full Menu QR Code</h2>
    <p>Customers scan this to browse your <strong>entire menu</strong> and place an order from their phone.</p>
    <div style="display:flex;gap:8px;flex-wrap:wrap">
      <button onclick="openPrintModal('full-menu-hero','<?php echo htmlspecialchars($__rest_name,ENT_QUOTES); ?> — Full Menu','','All <?php echo $total_items; ?> items')"
              class="btn btn-sm" style="background:rgba(255,255,255,.18);color:#fff;border:1.5px solid rgba(255,255,255,.3)">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print Full Menu QR
      </button>
      <button onclick="copyUrl('<?php echo addslashes($full_menu_url); ?>',this)"
              class="btn btn-sm" style="background:rgba(255,255,255,.18);color:#fff;border:1.5px solid rgba(255,255,255,.3)">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
        Copy Link
      </button>
    </div>
  </div>
</div>

<!-- View tabs -->
<div style="display:flex;gap:8px;margin-bottom:22px;flex-wrap:wrap" class="vtab-row no-print">
  <a href="?view=overview"   class="vtab <?php echo $view==='overview'  ?'on':''; ?>"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/></svg>Overview</a>
  <a href="?view=categories" class="vtab <?php echo $view==='categories'?'on':''; ?>"><svg viewBox="0 0 24 24"><path d="M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z"/></svg>By Category (<?php echo $total_cats; ?>)</a>
  <a href="?view=items"      class="vtab <?php echo $view==='items'     ?'on':''; ?>"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 10h16M4 14h16M4 18h7"/></svg>All Items (<?php echo $total_items; ?>)</a>
</div>

<!-- Print-only header (hidden on screen) -->
<div style="display:none" id="print-header">
  <div style="text-align:center;padding-bottom:14px;border-bottom:2px solid #ddd;margin-bottom:16px">
    <div style="font-size:1.4rem;font-weight:800"><?php echo htmlspecialchars($__rest_name); ?></div>
    <div style="color:#666;font-size:.85rem;margin-top:3px">Scan a QR code to view our menu and order</div>
  </div>
</div>

<?php if ($total_items === 0 && empty($categories)): ?>
<div class="card" style="padding:60px;text-align:center;color:var(--text-muted)">
  <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M4 6h16M4 10h16M4 14h16M4 18h7"/></svg>
  <p style="font-weight:700;margin-bottom:8px">No menu items or categories yet</p>
  <p style="font-size:.84rem;margin-bottom:18px">Add categories and menu items first, then come back to print QR codes.</p>
  <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">
    <a href="categories.php" class="btn btn-secondary btn-md">Add Categories</a>
    <a href="menu.php" class="btn btn-primary btn-md">Add Menu Items</a>
  </div>
</div>

<?php elseif ($view === 'overview'): ?>
<!-- ═══ OVERVIEW ═══ -->
<div class="sep">Full Menu</div>
<div class="qr-grid">
  <div class="qr-card is-featured">
    <div class="qr-wrap" style="background:var(--primary-bg)">
      <div class="qr-target" data-url="<?php echo htmlspecialchars($full_menu_url); ?>" data-size="180" data-id="ov-full"></div>
    </div>
    <div class="qr-body">
      <div class="qr-name" style="color:var(--primary)"><?php echo htmlspecialchars($__rest_name); ?></div>
      <div class="qr-hint">Full Menu &bull; <?php echo $total_items; ?> items &bull; <?php echo $total_cats; ?> categories</div>
    </div>
    <div class="qr-btns no-print">
      <button onclick="openPrintModal('ov-full','<?php echo htmlspecialchars($__rest_name,ENT_QUOTES); ?> — Full Menu','','<?php echo $total_items; ?> items')" class="btn btn-primary btn-sm" style="flex:1">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print
      </button>
      <button onclick="copyUrl('<?php echo addslashes($full_menu_url); ?>',this)" class="btn btn-secondary btn-sm">Copy URL</button>
    </div>
  </div>
</div>

<?php if (!empty($categories)): ?>
<div class="sep">Categories (<?php echo $total_cats; ?>)</div>
<div class="qr-grid">
  <?php foreach ($categories as $cat):
    $curl = $scan_base.'?rid='.$__rid.'&cat='.$cat['id'];
    $cnt  = count($by_cat[$cat['id']]['items'] ?? []);
    $did  = 'ov-cat-'.$cat['id'];
  ?>
  <div class="qr-card">
    <div class="qr-wrap">
      <div class="qr-target" data-url="<?php echo htmlspecialchars($curl); ?>" data-size="170" data-id="<?php echo $did; ?>"></div>
    </div>
    <div class="qr-body">
      <div class="qr-name"><?php echo htmlspecialchars($cat['name']); ?></div>
      <div class="qr-hint"><?php echo $cnt; ?> item<?php echo $cnt!==1?'s':''; ?></div>
    </div>
    <div class="qr-btns no-print">
      <button onclick="openPrintModal('<?php echo $did; ?>','<?php echo htmlspecialchars($cat['name'],ENT_QUOTES); ?>','<?php echo htmlspecialchars($__rest_name,ENT_QUOTES); ?>','<?php echo $cnt; ?> items')" class="btn btn-primary btn-sm" style="flex:1">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print
      </button>
      <button onclick="copyUrl('<?php echo addslashes($curl); ?>',this)" class="btn btn-secondary btn-sm">Copy</button>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php elseif ($view === 'categories'): ?>
<!-- ═══ CATEGORIES ═══ -->
<div class="sep">Full Menu</div>
<div class="qr-grid">
  <div class="qr-card is-featured">
    <div class="qr-wrap" style="background:var(--primary-bg)">
      <div class="qr-target" data-url="<?php echo htmlspecialchars($full_menu_url); ?>" data-size="170" data-id="cat-full"></div>
    </div>
    <div class="qr-body">
      <div class="qr-name" style="color:var(--primary)">Full Menu</div>
      <div class="qr-hint">All <?php echo $total_items; ?> items &bull; <?php echo htmlspecialchars($__rest_name); ?></div>
    </div>
    <div class="qr-btns no-print">
      <button onclick="openPrintModal('cat-full','<?php echo htmlspecialchars($__rest_name,ENT_QUOTES); ?>','Full Menu','')" class="btn btn-primary btn-sm" style="flex:1">Print</button>
      <button onclick="copyUrl('<?php echo addslashes($full_menu_url); ?>',this)" class="btn btn-secondary btn-sm">Copy</button>
    </div>
  </div>
</div>

<?php if (empty($categories)): ?>
<div class="alert alert-info" style="margin-top:16px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
  No categories yet. <a href="categories.php" style="font-weight:700;color:var(--primary)">Create categories →</a>
</div>
<?php else: ?>
<div class="sep">Categories</div>
<div class="qr-grid">
  <?php foreach ($categories as $cat):
    $curl = $scan_base.'?rid='.$__rid.'&cat='.$cat['id'];
    $cnt  = count($by_cat[$cat['id']]['items'] ?? []);
    $did  = 'c-'.$cat['id'];
  ?>
  <div class="qr-card">
    <div class="qr-wrap">
      <div class="qr-target" data-url="<?php echo htmlspecialchars($curl); ?>" data-size="170" data-id="<?php echo $did; ?>"></div>
    </div>
    <div class="qr-body">
      <div class="qr-name"><?php echo htmlspecialchars($cat['name']); ?></div>
      <div class="qr-hint"><?php echo $cnt; ?> item<?php echo $cnt!==1?'s':''; ?></div>
    </div>
    <div class="qr-btns no-print">
      <button onclick="openPrintModal('<?php echo $did; ?>','<?php echo htmlspecialchars($cat['name'],ENT_QUOTES); ?>','<?php echo htmlspecialchars($__rest_name,ENT_QUOTES); ?>','<?php echo $cnt; ?> items')" class="btn btn-primary btn-sm" style="flex:1">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print
      </button>
      <button onclick="copyUrl('<?php echo addslashes($curl); ?>',this)" class="btn btn-secondary btn-sm">Copy</button>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php elseif ($view === 'items'): ?>
<!-- ═══ ALL ITEMS ═══ -->
<?php if (!empty($uncategorized)): ?>
<div class="sep">Uncategorized</div>
<div class="qr-grid">
  <?php foreach ($uncategorized as $item):
    $iurl = $scan_base.'?rid='.$__rid.'&item='.$item['id'];
    $did  = 'i-'.$item['id'];
  ?>
  <div class="qr-card">
    <div class="qr-wrap"><div class="qr-target" data-url="<?php echo htmlspecialchars($iurl); ?>" data-size="165" data-id="<?php echo $did; ?>"></div></div>
    <div class="qr-body">
      <div class="qr-name"><?php echo htmlspecialchars($item['name']); ?></div>
      <div class="qr-price">₦<?php echo number_format($item['price'],0); ?></div>
      <div class="qr-hint"><?php echo $item['is_available']?'Available':'<span style="color:var(--error)">Unavailable</span>'; ?></div>
    </div>
    <div class="qr-btns no-print">
      <button onclick="openPrintModal('<?php echo $did; ?>','<?php echo htmlspecialchars($item['name'],ENT_QUOTES); ?>','₦<?php echo number_format($item['price'],0); ?>','')" class="btn btn-primary btn-sm" style="flex:1">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print
      </button>
      <button onclick="copyUrl('<?php echo addslashes($iurl); ?>',this)" class="btn btn-secondary btn-sm">Copy</button>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php foreach ($by_cat as $cid => $cdata):
  $curl = $scan_base.'?rid='.$__rid.'&cat='.$cid;
  $cdid = 'ci-'.$cid;
?>
<div class="sep">
  <?php echo htmlspecialchars($cdata['name']); ?>
  <span style="opacity:.55;font-size:.65rem"><?php echo count($cdata['items']); ?> items</span>
  <!-- hidden QR target for category print -->
  <div class="qr-target" data-url="<?php echo htmlspecialchars($curl); ?>" data-size="165" data-id="<?php echo $cdid; ?>" style="display:none;position:absolute"></div>
  <button onclick="openPrintModal('<?php echo $cdid; ?>','<?php echo htmlspecialchars($cdata['name'],ENT_QUOTES); ?>','<?php echo htmlspecialchars($__rest_name,ENT_QUOTES); ?>','<?php echo count($cdata['items']); ?> items')" class="btn btn-secondary btn-sm no-print" style="margin-left:auto;font-size:.68rem">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" width="12" height="12"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
    Print category QR
  </button>
</div>
<div class="qr-grid" style="margin-bottom:6px">
  <?php foreach ($cdata['items'] as $item):
    $iurl = $scan_base.'?rid='.$__rid.'&item='.$item['id'];
    $did  = 'i-'.$item['id'];
  ?>
  <div class="qr-card">
    <div class="qr-wrap"><div class="qr-target" data-url="<?php echo htmlspecialchars($iurl); ?>" data-size="165" data-id="<?php echo $did; ?>"></div></div>
    <div class="qr-body">
      <div class="qr-name"><?php echo htmlspecialchars($item['name']); ?></div>
      <div class="qr-price">₦<?php echo number_format($item['price'],0); ?></div>
      <div class="qr-hint">
        <?php echo htmlspecialchars($item['cat_name']??''); ?>
        <?php if(!$item['is_available']): ?> &bull; <span style="color:var(--error)">Unavailable</span><?php endif; ?>
      </div>
    </div>
    <div class="qr-btns no-print">
      <button onclick="openPrintModal('<?php echo $did; ?>','<?php echo htmlspecialchars($item['name'],ENT_QUOTES); ?>','₦<?php echo number_format($item['price'],0); ?>','<?php echo htmlspecialchars($item['cat_name']??'',ENT_QUOTES); ?>')" class="btn btn-primary btn-sm" style="flex:1">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print
      </button>
      <button onclick="copyUrl('<?php echo addslashes($iurl); ?>',this)" class="btn btn-secondary btn-sm">Copy</button>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>

<!-- ── Print Modal ──────────────────────────────────────────────────────── -->
<div class="modal-backdrop" id="printModal">
  <div class="modal" style="max-width:340px">
    <div class="modal-header">
      <h3>Print QR Code</h3>
      <button class="modal-close" onclick="closeModal('printModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <div class="modal-body" style="text-align:center">
      <div style="padding:18px 14px;border:2px dashed var(--border);border-radius:14px">
        <div style="font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:.12em;color:var(--text-muted);margin-bottom:8px" id="pm-rest"></div>
        <div id="pm-qr" style="display:flex;align-items:center;justify-content:center;margin:0 auto 12px"></div>
        <div style="font-size:.92rem;font-weight:800;margin-bottom:4px" id="pm-name"></div>
        <div style="font-size:.85rem;font-weight:700;color:var(--primary);margin-bottom:2px" id="pm-price"></div>
        <div style="font-size:.7rem;color:var(--text-muted)" id="pm-sub"></div>
        <div style="margin-top:10px;font-size:.7rem;color:var(--text-muted)">📱 Scan to view menu &amp; order</div>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round" style="margin:6px auto 0;display:block"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
      </div>
      <p style="font-size:.72rem;color:var(--text-muted);margin-top:10px">Tip: uncheck "Headers and footers" in print dialog</p>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary btn-md" onclick="closeModal('printModal')">Cancel</button>
      <button class="btn btn-primary btn-md" onclick="doPrint()">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print Now
      </button>
    </div>
  </div>
</div>

<script>
const REST_NAME  = <?php echo json_encode($__rest_name); ?>;
const FULL_URL   = <?php echo json_encode($full_menu_url); ?>;
const QR_OPTIONS = { correctLevel: QRCode.CorrectLevel.M, colorDark: '#0F172A', colorLight: '#ffffff' };

/* ── Render every .qr-target on page ── */
function renderAll() {
  document.querySelectorAll('.qr-target').forEach(el => {
    if (el._done) return;
    el._done = true;
    const url  = el.dataset.url;
    const size = parseInt(el.dataset.size) || 170;
    if (!url) return;
    try {
      new QRCode(el, Object.assign({}, QR_OPTIONS, { text: url, width: size, height: size }));
    } catch(e) {
      el.innerHTML = '<p style="color:red;font-size:.7rem">Error</p>';
    }
  });
}

/* ── Hero (small) ── */
function renderHero() {
  const el = document.getElementById('hero-qr-el');
  if (!el || el._done) return;
  el._done = true;
  new QRCode(el, Object.assign({}, QR_OPTIONS, { text: FULL_URL, width: 72, height: 72 }));
}

document.addEventListener('DOMContentLoaded', () => {
  renderHero();
  renderAll();
});

/* ── Print Modal ── */
let _printUrl = FULL_URL;

function openPrintModal(dataId, name, price, sub) {
  // Retrieve URL from the matching qr-target element
  const src = document.querySelector('[data-id="' + dataId + '"]');
  _printUrl = src ? src.dataset.url : FULL_URL;

  document.getElementById('pm-rest').textContent  = REST_NAME;
  document.getElementById('pm-name').textContent  = name;
  document.getElementById('pm-price').textContent = price;
  document.getElementById('pm-sub').textContent   = sub;

  const qrBox = document.getElementById('pm-qr');
  qrBox.innerHTML = '';
  new QRCode(qrBox, Object.assign({}, QR_OPTIONS, { text: _printUrl, width: 200, height: 200 }));

  openModal('printModal');
}

function doPrint() {
  const canvas = document.querySelector('#pm-qr canvas');
  const qrDataUrl = canvas ? canvas.toDataURL('image/png') : '';
  const name  = document.getElementById('pm-name').textContent;
  const price = document.getElementById('pm-price').textContent;
  const sub   = document.getElementById('pm-sub').textContent;

  const win = window.open('', '_blank', 'width=480,height=600');
  win.document.write(`<!DOCTYPE html>
<html><head>
<title>QR — ${name}</title>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;700;800&display=swap" rel="stylesheet">
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:'Plus Jakarta Sans',sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fff;padding:20px}
  .card{text-align:center;padding:26px 22px;border:2px dashed #CBD5E1;border-radius:16px;max-width:270px;width:100%}
  .rest{font-size:.58rem;font-weight:700;text-transform:uppercase;letter-spacing:.12em;color:#64748B;margin-bottom:10px}
  img{border-radius:9px;border:1px solid #E2E8F0;display:block;margin:0 auto}
  .name{font-size:.9rem;font-weight:800;margin-top:12px;margin-bottom:3px;color:#0F172A}
  .price{font-size:.85rem;font-weight:700;color:#225AE3}
  .sub{font-size:.68rem;color:#64748B;margin-top:2px}
  .hint{font-size:.68rem;color:#94A3B8;margin-top:10px}
  .brand{margin-top:8px;display:flex;align-items:center;justify-content:center;gap:4px;color:#225AE3;font-size:.68rem;font-weight:700}
  @media print{@page{margin:.6cm}}
</style>
</head><body>
<div class="card">
  <div class="rest">${REST_NAME}</div>
  ${qrDataUrl ? `<img src="${qrDataUrl}" width="200" height="200">` : ''}
  <div class="name">${name}</div>
  ${price ? `<div class="price">${price}</div>` : ''}
  ${sub   ? `<div class="sub">${sub}</div>`   : ''}
  <div class="hint">📱 Scan to view menu &amp; order</div>
  <div class="brand">
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
    Dabil
  </div>
</div>
</body></html>`);
  win.document.close();
  win.onload = () => { win.focus(); setTimeout(() => win.print(), 400); };
}

/* ── Copy URL ── */
function copyUrl(url, btn) {
  navigator.clipboard.writeText(url)
    .then(() => {
      const o = btn.textContent;
      btn.textContent = 'Copied!';
      btn.style.cssText += ';background:var(--success);color:#fff;border-color:var(--success)';
      setTimeout(() => { btn.textContent = o; btn.style.cssText = ''; }, 1800);
    })
    .catch(() => prompt('Copy this URL:', url));
}
</script>

<?php include("includes/footer.php"); ?>
