<?php
$page_title = 'طباعة كروت الإنترنت';

if (session_status() === PHP_SESSION_NONE) session_start();
if (!ob_get_level()) ob_start();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/vouchers_lib.php';
require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/settings_store.php';

ensure_db(true);
$conn = $GLOBALS['conn'];

require_login();
if(function_exists('require_perm')) require_perm('can_manage_sales');

// إعداد الورق (A4 / 80mm / 58mm)
$paper = $_GET['paper'] ?? null;
$paper = $paper ? (string)$paper : (function_exists('setting_get') ? (string)setting_get($conn, 'voucher_default_paper', 'A4') : 'A4');
$paper = strtoupper($paper);
if (!in_array($paper, ['A4','80MM','58MM'], true)) $paper = 'A4';
$paper_class = $paper === 'A4' ? 'a4' : ($paper === '58MM' ? '58mm' : '80mm');

$admin_name = $_SESSION['admin_username'] ?? ($_SESSION['admin_user'] ?? 'admin');
$now = date('Y-m-d H:i');
$op_id = 'VCH-' . date('His');
$auto = (($_GET['auto'] ?? '') === '1');

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidVoucherPrint = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidVoucherPrint) $UA_PAGE_CSS = ['assets/css/android_vouchers_print.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';


$conn = ensure_db(true);
vouchers_ensure_tables($conn);

// ✅ إعدادات QR (محلي بدون إنترنت)
$qr_mode = get_app_setting($conn,'voucher_qr_mode','code_pass');
$qr_hotspot_url = get_app_setting($conn,'voucher_qr_hotspot_url','');
$qr_paid_only = get_app_setting($conn,'voucher_qr_paid_only','1'); // يُستخدم للتحكم بالفعالية داخل صفحة redeem

// Base URL لهذه الصفحة (لإنشاء رابط QR محلي)
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$basePath = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'] ?? '/admin/')), '/');
$baseUrl = $scheme . '://' . $host . ($basePath ? $basePath . '/' : '/');

$batch = (int)($_GET['batch'] ?? 0);
$voucher_id = (int)($_GET['voucher_id'] ?? 0);
$ids_raw = trim((string)($_GET['ids'] ?? '')); // comma-separated voucher ids
$selected_ids = [];
if($ids_raw !== ''){
  foreach(preg_split('/[^0-9]+/', $ids_raw) as $p){
    $v = (int)$p;
    if($v>0) $selected_ids[$v]=1;
  }
}
$selected_ids = array_keys($selected_ids);
settings_ensure_table($conn);
$auto_export_default = (int)setting_get($conn, 'voucher_auto_export_on_print', '1');
$export_get = $_GET['export'] ?? null; // 1/0
$auto_export = ($export_get === null) ? $auto_export_default : (int)$export_get; // 1 = export on first print

if ($auto_export !== 0 && $batch > 0) {
  // Export once (prevents duplicates on reprint)
  try {
    vouchers_ensure_tables($conn);
    $actor = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
    vouchers_export_batch_to_mikrotik($conn, $batch, $actor);
  } catch (Throwable $e) {
    // ignore here; printing still allowed
  }
}


$rows = [];
$title = '';

if (!empty($selected_ids)) {
  // Print selected vouchers (comma-separated ids)
  $ids_sql = implode(',', array_map('intval', $selected_ids));

  if ($auto_export !== 0) {
    // export all involved batches once
    try {
      $actor = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
      $bq = $conn->query("SELECT DISTINCT batch_id FROM vouchers WHERE id IN ($ids_sql) AND batch_id IS NOT NULL");
      if ($bq) {
        while($br = $bq->fetch_assoc()){
          $vb = (int)($br['batch_id'] ?? 0);
          if($vb>0) vouchers_export_batch_to_mikrotik($conn, $vb, $actor);
        }
      }
    } catch(Throwable $e) {}
  }

  $q = $conn->query("SELECT * FROM vouchers WHERE id IN ($ids_sql) ORDER BY FIELD(id,$ids_sql)");
  if ($q) $rows = $q->fetch_all(MYSQLI_ASSOC);

} elseif ($voucher_id > 0) {
  // Print a single voucher
  if ($auto_export !== 0) {
    // export voucher's batch once (if exists)
    try {
      $qq = $conn->query("SELECT batch_id FROM vouchers WHERE id=".(int)$voucher_id." LIMIT 1");
      $rr = $qq ? $qq->fetch_assoc() : null;
      $vb = (int)($rr['batch_id'] ?? 0);
      if ($vb > 0) {
        $actor = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
        vouchers_export_batch_to_mikrotik($conn, $vb, $actor);
      }
    } catch(Throwable $e) {}
  }
  $q = $conn->query("SELECT * FROM vouchers WHERE id=".(int)$voucher_id." LIMIT 1");
  if ($q) $rows = $q->fetch_all(MYSQLI_ASSOC);

} elseif ($batch > 0) {
  $b = $conn->query("SELECT * FROM voucher_batches WHERE id=".(int)$batch." LIMIT 1");
  $br = $b ? $b->fetch_assoc() : null;
  $title = $br ? ($br['title'] ?? '') : '';
  $q = $conn->query("SELECT * FROM vouchers WHERE batch_id=".(int)$batch." ORDER BY id ASC");
  if ($q) $rows = $q->fetch_all(MYSQLI_ASSOC);

} else {
  $q = $conn->query("SELECT * FROM vouchers ORDER BY id DESC LIMIT 200");
  if ($q) $rows = $q->fetch_all(MYSQLI_ASSOC);
}

if ($uaAndroidVoucherPrint) {
  $androidVoucherBatches = [];
  $androidBatchQuery = $conn->query("SELECT id,title,qty,created_at FROM voucher_batches ORDER BY id DESC LIMIT 100");
  if ($androidBatchQuery) $androidVoucherBatches = $androidBatchQuery->fetch_all(MYSQLI_ASSOC);
  require __DIR__ . '/android_vouchers_print.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid d-flex justify-content-between align-items-center flex-wrap">
      <h1 class="mb-0">طباعة كروت الإنترنت <?= !empty($selected_ids) ? ('— محدد (' . count($selected_ids) . ')') : ($batch>0 ? ('— دفعة #'.(int)$batch.' '.h($title)) : '') ?></h1>
      <div class="mt-2 print-toolbar ua-u-flex-wrap-center">
        <form method="get" class="ua-u-inline-flex-center">
          <?php if($batch>0): ?><input type="hidden" name="batch" value="<?= (int)$batch ?>"><?php endif; ?>
          <label class="ua-u-muted-line">الورق</label>
          <select name="paper" class="form-control ua-u-width-auto" onchange="this.form.submit()">
            <option value="A4" <?= $paper==='A4'?'selected':'' ?>>A4</option>
            <option value="80mm" <?= $paper==='80MM'?'selected':'' ?>>80mm</option>
            <option value="58mm" <?= $paper==='58MM'?'selected':'' ?>>58mm</option>
          </select>
        </form>
        <a class="btn btn-primary" href="vouchers_print.php<?= $batch>0?'?batch='.urlencode((string)$batch):'' ?><?= ($batch>0?'&':'?') ?>paper=<?= h(strtolower($paper)) ?>&auto=1"><i class="fa fa-print"></i> طباعة</a>
        <a class="btn btn-secondary" href="vouchers.php<?= $batch>0?'?batch='.urlencode((string)$batch):'' ?>">عودة</a>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php if(!empty($export_res) && isset($export_res['ok'])): ?>
        <?php if($export_res['ok']): ?>
          <?php if(!empty($export_res['already_exported'])): ?>
            <div class="alert alert-info">تمت الطباعة سابقًا — لن يتم إعادة التصدير إلى MikroTik.</div>
          <?php else: ?>
            <div class="alert alert-success">تم تصدير الدفعة إلى MikroTik ✅ (جديد: <?= (int)($export_res['exported']??0) ?> / موجود سابقًا: <?= (int)($export_res['skipped']??0) ?>)</div>
          <?php endif; ?>
        <?php else: ?>
          <div class="alert alert-danger">فشل تصدير الدفعة إلى MikroTik: <?= h($export_res['error']??'') ?></div>
        <?php endif; ?>
      <?php endif; ?>

      <?php if(!$rows): ?>
        <div class="alert alert-warning">لا توجد كروت للطباعة.</div>
      <?php endif; ?>

      <div class="print-toolbar">
        <div class="field">
          <label>حجم الكرت</label>
          <select id="cardPreset">
            <option value="default">افتراضي (320px)</option>
            <option value="85x55">85×55 mm (Credit)</option>
            <option value="90x60">90×60 mm</option>
            <option value="100x70">100×70 mm</option>
            <option value="custom">مخصص…</option>
          </select>
        </div>
        <div class="field">
          <label>عرض (mm)</label>
          <input id="cardW" type="number" min="50" max="140" step="1" placeholder="مثال: 85" disabled>
        </div>
        <div class="field">
          <label>ارتفاع (mm)</label>
          <input id="cardH" type="number" min="40" max="120" step="1" placeholder="مثال: 55" disabled>
        </div>
        <div class="field">
          <label>حجم QR (mm)</label>
          <input id="qrSize" type="number" min="18" max="60" step="1" placeholder="مثال: 28">
        </div>

        <div class="field">
          <label>نوع الورق</label>
          <select id="paperPreset">
            <option value="a4">A4 (افتراضي)</option>
            <option value="thermal80">حراري 80mm</option>
            <option value="thermal58">حراري 58mm</option>
            <option value="custom">مخصص…</option>
          </select>
        </div>
        <div class="field">
          <label>عرض الورق (mm)</label>
          <input id="paperW" type="number" min="50" max="220" step="1" placeholder="مثال: 80" disabled>
        </div>
        <div class="field">
          <label>الأعمدة بالصفحة</label>
          <select id="cols">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3" selected>3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
          </select>
        </div>
        <div class="field">
          <label>المسافة بين الكروت (mm)</label>
          <input id="gap" type="number" min="0" max="20" step="1" placeholder="مثال: 3">
        </div>
        <div class="field">
          <label>هوامش الصفحة (mm)</label>
          <input id="pageM" type="number" min="0" max="25" step="1" placeholder="مثال: 8">
        </div>
        <div class="field">
          <label>&nbsp;</label>
          <button class="btn btn-primary" onclick="window.print()">طباعة</button>
        </div>
      </div>

      <script>
        (function(){
          const root = document.documentElement;
          const presetEl = document.getElementById('cardPreset');
          const wEl = document.getElementById('cardW');
          const hEl = document.getElementById('cardH');
          const qrEl = document.getElementById('qrSize');

          const paperPresetEl = document.getElementById('paperPreset');
          const paperWEl = document.getElementById('paperW');
          const colsEl = document.getElementById('cols');
          const gapEl = document.getElementById('gap');
          const pageMEl = document.getElementById('pageM');

          function setVar(name, value){ if(value!==null && value!==undefined && value!=='') root.style.setProperty(name, value); }
          function px(n){ return String(n) + 'px'; }
          function mm(n){ return String(n) + 'mm'; }

          function applyPaperPreset(p){
            if(p==='a4'){
              setVar('--paper-max', '100%');
              // leave margins to user
            } else if(p==='thermal80'){
              setVar('--paper-max', '80mm');
              setVar('--cols', '1');
              setVar('--page-m', '0mm');
              setVar('--gap', '2mm');
            } else if(p==='thermal58'){
              setVar('--paper-max', '58mm');
              setVar('--cols', '1');
              setVar('--page-m', '0mm');
              setVar('--gap', '2mm');
            }
          }

          function applyPreset(p){
            if(p==='default'){
              setVar('--card-w', '320px');
              setVar('--card-h', 'auto');
              setVar('--card-pad', '12px');
              setVar('--qr', '120px');
              setVar('--fs-title', '14px');
              setVar('--fs-code', '18px');
              setVar('--fs-pass', '16px');
              setVar('--fs-meta', '12px');
            } else if(p==='85x55'){
              setVar('--card-w', mm(85));
              setVar('--card-h', mm(55));
              setVar('--card-pad', mm(4));
              setVar('--qr', mm(26));
              setVar('--fs-title', '12px');
              setVar('--fs-code', '16px');
              setVar('--fs-pass', '14px');
              setVar('--fs-meta', '10.5px');
            } else if(p==='90x60'){
              setVar('--card-w', mm(90));
              setVar('--card-h', mm(60));
              setVar('--card-pad', mm(4.5));
              setVar('--qr', mm(28));
              setVar('--fs-title', '12px');
              setVar('--fs-code', '16.5px');
              setVar('--fs-pass', '14px');
              setVar('--fs-meta', '11px');
            } else if(p==='100x70'){
              setVar('--card-w', mm(100));
              setVar('--card-h', mm(70));
              setVar('--card-pad', mm(5));
              setVar('--qr', mm(32));
              setVar('--fs-title', '13px');
              setVar('--fs-code', '18px');
              setVar('--fs-pass', '15px');
              setVar('--fs-meta', '11.5px');
            }
          }

          function save(){
            localStorage.setItem('voucher_print_preset', presetEl.value);
            localStorage.setItem('voucher_print_w', wEl.value||'');
            localStorage.setItem('voucher_print_h', hEl.value||'');
            localStorage.setItem('voucher_print_qr', qrEl.value||'');

            localStorage.setItem('voucher_print_paper_preset', paperPresetEl.value);
            localStorage.setItem('voucher_print_paper_w', paperWEl.value||'');
            localStorage.setItem('voucher_print_cols', colsEl.value||'');
            localStorage.setItem('voucher_print_gap', gapEl.value||'');
            localStorage.setItem('voucher_print_pagem', pageMEl.value||'');
          }

          function load(){
            const p = localStorage.getItem('voucher_print_preset') || 'default';
            presetEl.value = p;
            const cw = localStorage.getItem('voucher_print_w') || '';
            const ch = localStorage.getItem('voucher_print_h') || '';
            const q = localStorage.getItem('voucher_print_qr') || '';
            wEl.value = cw; hEl.value = ch; qrEl.value = q;

            const pp = localStorage.getItem('voucher_print_paper_preset') || 'a4';
            paperPresetEl.value = pp;
            const pw = localStorage.getItem('voucher_print_paper_w') || '';
            paperWEl.value = pw;

            const cols = localStorage.getItem('voucher_print_cols') || '3';
            colsEl.value = cols;
            const gap = localStorage.getItem('voucher_print_gap') || '';
            gapEl.value = gap;
            const pm = localStorage.getItem('voucher_print_pagem') || '';
            pageMEl.value = pm;

            const isCustom = (p==='custom');
            wEl.disabled = !isCustom; hEl.disabled = !isCustom;

            if(p!=='custom') applyPreset(p);
            if(q) setVar('--qr', mm(parseInt(q,10)));

            // Paper presets + layout
            const paperCustom = (pp==='custom');
            paperWEl.disabled = !paperCustom;
            if(pp!=='custom') applyPaperPreset(pp);
            if(paperCustom && pw) setVar('--paper-max', mm(parseInt(pw,10)));

            if(cols) setVar('--cols', String(parseInt(cols,10)||3));
            if(gap) setVar('--gap', mm(parseInt(gap,10)));
            if(pm) setVar('--page-m', mm(parseInt(pm,10)));

            if(isCustom){
              if(cw) setVar('--card-w', mm(parseInt(cw,10)));
              if(ch) setVar('--card-h', mm(parseInt(ch,10)));
            }
          }

          presetEl.addEventListener('change', ()=>{
            const p = presetEl.value;
            const isCustom = (p==='custom');
            wEl.disabled = !isCustom; hEl.disabled = !isCustom;
            if(p!=='custom') applyPreset(p);
            else {
              // Keep current vars; user will enter values
            }
            save();
          });
          [wEl,hEl].forEach(el=>{
            el.addEventListener('input', ()=>{
              const w = parseInt(wEl.value||'0',10);
              const h = parseInt(hEl.value||'0',10);
              if(w>0) setVar('--card-w', mm(w));
              if(h>0) setVar('--card-h', mm(h));
              save();
            });
          });
          qrEl.addEventListener('input', ()=>{
            const q = parseInt(qrEl.value||'0',10);
            if(q>0) setVar('--qr', mm(q));
            save();
          });

          paperPresetEl.addEventListener('change', ()=>{
            const p = paperPresetEl.value;
            const isCustom = (p==='custom');
            paperWEl.disabled = !isCustom;
            if(p!=='custom') applyPaperPreset(p);
            save();
          });
          paperWEl.addEventListener('input', ()=>{
            const w = parseInt(paperWEl.value||'0',10);
            if(w>0) setVar('--paper-max', mm(w));
            save();
          });
          colsEl.addEventListener('change', ()=>{ setVar('--cols', String(parseInt(colsEl.value||'3',10)||3)); save(); });
          gapEl.addEventListener('input', ()=>{ const g=parseInt(gapEl.value||'0',10); if(g>=0) setVar('--gap', mm(g)); save(); });
          pageMEl.addEventListener('input', ()=>{ const m=parseInt(pageMEl.value||'0',10); if(m>=0) setVar('--page-m', mm(m)); save(); });

          load();
        })();
      </script>


      <div class="print-area print-area--paper-<?= h($paper_class) ?>">
        <div class="voucher-grid">
        <?php foreach($rows as $r): ?>
          <div class="voucher-card">
            <div class="voucher-title">كرت إنترنت</div>
            <div class="voucher-code"><code><?= h($r['code']) ?></code></div>
            <div class="voucher-pass">PASS: <code><?= h($r['passcode']) ?></code></div>
            <?php
              $paid = (!empty($r['payment_id']) || ($r['status']==='used'));
              // ✅ نطبع QR دائماً للكميات الكبيرة، لكن "لا يعمل" قبل الدفع (يتم التحقق في redeem)
              $show_qr = true;
              $token = vouchers_ensure_qr_token($conn, (int)$r['id']);
              $qrText = $baseUrl . 'voucher_redeem.php?t=' . rawurlencode($token);
            ?>
            <div class="voucher-meta">الدفع: <span class="badge-paid <?= $paid?'ok':'no' ?>"><?= $paid?'مدفوع':'غير مدفوع' ?></span></div>
            <?php if($show_qr): ?>
              <div class="voucher-qr">
                <div class="qrbox" data-qr="<?= h($qrText) ?>"></div>
                <div class="voucher-meta">
                  امسح QR للتفعيل/الدخول.
                  <?php if($qr_paid_only==='1' && !$paid): ?><br><span class="text-muted">(غير فعّال قبل الدفع)</span><?php endif; ?>
                </div>
              </div>
            <?php endif; ?>
            <div class="voucher-meta">
              <?php if(!empty($r['rate_limit'])): ?>السرعة: <?= h($r['rate_limit']) ?><br><?php endif; ?>
              <?php if(!empty($r['duration_minutes'])): ?>المدة: <?= round(((int)$r['duration_minutes'])/60,2) ?> ساعة<br><?php endif; ?>
              <?php if(!empty($r['data_bytes'])): ?>الحجم: <?= round(((int)$r['data_bytes'])/1024/1024/1024,2) ?> GB<br><?php endif; ?>
              الحالة: <?= h($r['status']) ?>
            </div>
          </div>
        <?php endforeach; ?>
        </div>
      </div>

      <script src="assets/js/qr_local.min.js"></script>
      
      <div class="footer ua-u-print-card-foot">
        <span><b>المستخدم:</b> <?= h($admin_name) ?></span>
        <span><b>التاريخ:</b> <?= h($now) ?></span>
        <span><b>رقم العملية:</b> <?= h($op_id) ?></span>
      </div>

<script>
        (function(){
          function mmToPx(mm){
            // 96dpi ≈ 3.7795 px per mm
            return Math.round(mm * 3.7795);
          }
          function getQrPx(){
            var v = getComputedStyle(document.documentElement).getPropertyValue('--qr').trim();
            if(!v) return 120;
            if(v.endsWith('mm')){
              var n = parseFloat(v);
              if(!isNaN(n)) return mmToPx(n);
            }
            if(v.endsWith('px')){
              var n2 = parseFloat(v);
              if(!isNaN(n2)) return Math.round(n2);
            }
            var n3 = parseFloat(v);
            return isNaN(n3) ? 120 : Math.round(n3);
          }

          function renderAll(){
            var els = document.querySelectorAll('.qrbox[data-qr]');
            var size = getQrPx();
            els.forEach(function(el){
              var text = el.getAttribute('data-qr') || '';
              if (!text) return;

              // clear old QR
              el.innerHTML = '';
              try {
                var qr = QRLocal.create(text, 5);
                var canvas = qr.toCanvas(size);

                // scale to fit box (no clipping)
                canvas.style.width = '100%';
                canvas.style.height = '100%';
                canvas.style.display = 'block';

                el.appendChild(canvas);
              } catch(e){
                el.innerHTML = '<div class="ua-u-print-small">QR Error</div>';
              }
            });
          }

          renderAll();

          // re-render on size/preset changes
          var qrInput = document.getElementById('qrSize');
          var presetEl = document.getElementById('cardPreset');

          function schedule(){
            clearTimeout(window.__qrRerenderT);
            window.__qrRerenderT = setTimeout(renderAll, 120);
          }
          if(qrInput) qrInput.addEventListener('input', schedule);
          if(presetEl) presetEl.addEventListener('change', schedule);
        })();
      </script>

    </div>
  </section>
</div>
<?php require_once __DIR__ . '/output_devices_lib.php'; if ($conn instanceof mysqli) ua_output_print_bootstrap($conn, 'voucher_cards', (string)($batch_id ?? '')); ?>
<?php if ($auto): ?>
<script>window.addEventListener('load',()=>setTimeout(()=>window.print(),250));</script>
<?php endif; ?>
<?php include __DIR__ . '/footer.php'; ?>
