<?php
$page_title = 'معاينة/اختيار طباعة الدفعة';

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/vouchers_lib.php';

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

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

$batch = (int)($_GET['batch'] ?? 0);
if($batch<=0){
  header('Location: vouchers.php');
  exit;
}

$paper = strtoupper((string)($_GET['paper'] ?? 'A4'));
if (!in_array($paper, ['A4','80MM','58MM'], true)) $paper = 'A4';

$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 id,code,passcode,type,status,rate_limit,data_bytes,duration_minutes,sold_to,sold_at 
                   FROM vouchers WHERE batch_id=".(int)$batch." ORDER BY id ASC");
$rows = $q ? $q->fetch_all(MYSQLI_ASSOC) : [];

include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
?>
<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">معاينة/اختيار الطباعة — دفعة #<?= (int)$batch ?> <?= h($title) ?></h1>
      <div class="mt-2 ua-u-d-flex ua-u-gap-8 ua-u-flex-wrap">
        <a class="btn btn-secondary" href="vouchers.php?batch=<?= (int)$batch ?>"><i class="fa fa-arrow-right"></i> رجوع للكروت</a>
        <a class="btn btn-outline-secondary" href="vouchers_print.php?batch=<?= (int)$batch ?>&paper=<?= urlencode($paper) ?>"><i class="fa fa-print"></i> طباعة كل الدفعة</a>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">

      <div class="card">
        <div class="card-body d-flex align-items-center justify-content-between flex-wrap ua-u-gap-12">
          <div class="ua-u-d-flex ua-u-gap-10 ua-u-ai-center ua-u-flex-wrap">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="chkAll">
              <label class="form-check-label" for="chkAll">تحديد الكل</label>
            
            <div class="ua-u-mt-6">
              <label class="small text-muted mb-1 d-block">فلترة</label>
              <select id="filterSel" class="form-control ua-u-minw-150">
                <option value="all" selected>كل الكروت</option>
                <option value="unsold">غير مباع</option>
                <option value="sold">مباع</option>
              </select>
            </div>

</div>

            <div>
              <label class="small text-muted mb-1 d-block">الورق</label>
              <select id="paperSel" class="form-control ua-u-minw-140">
                <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>
            </div>

            <div class="form-check ua-u-mt-22">
              <input class="form-check-input" type="checkbox" id="autoPrint" checked>
              <label class="form-check-label" for="autoPrint">طباعة تلقائية</label>
            </div>

            <div class="form-check ua-u-mt-22">
              <input class="form-check-input" type="checkbox" id="autoExport" checked>
              <label class="form-check-label" for="autoExport">تصدير MikroTik عند الطباعة</label>
            </div>
          </div>

          <div class="ua-u-d-flex ua-u-gap-8 ua-u-ai-center ua-u-flex-wrap">
            <div class="badge badge-info p-2" id="selCount">المحدد: 0</div>
            <button class="btn btn-primary" type="button" id="btnPreview"><i class="fa fa-eye"></i> معاينة/طباعة المحدد</button>
            <button class="btn btn-outline-primary" type="button" id="btnPrintUnsold"><i class="fa fa-print"></i> طباعة غير المباع فقط</button>
            <button class="btn btn-outline-primary" type="button" id="btnPrintSold"><i class="fa fa-print"></i> طباعة المباع فقط</button>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-striped mb-0">
              <thead>
                <tr>
                  <th class="ua-u-w-40"></th>
                  <th>#</th>
                  <th>الكود</th>
                  <th>الرقم السري</th>
                  <th>النوع</th>
                  <th>الحدود</th>
                  <th>السرعة</th>
                  <th>الحالة</th>
                  <th>بيع</th>
                </tr>
              </thead>
              <tbody>
                <?php if(!$rows): ?>
                  <tr><td colspan="9" class="text-center text-muted p-4">لا توجد كروت ضمن هذه الدفعة.</td></tr>
                <?php endif; ?>

                <?php foreach($rows as $r): ?>
                  <tr data-status="<?= h($r['status']) ?>" data-sold="<?= ($r['status']==='sold' || $r['sold_at']) ? '1':'0' ?>">
                    <td>
                      <input type="checkbox" class="chkRow" value="<?= (int)$r['id'] ?>">
                    </td>
                    <td><?= (int)$r['id'] ?></td>
                    <td><code><?= h($r['code']) ?></code></td>
                    <td><code><?= h($r['passcode']) ?></code></td>
                    <td><?= h($r['type']) ?></td>
                    <td class="small text-muted">
                      <?php if(!empty($r['duration_minutes'])): ?>
                        <?= (int)round(((int)$r['duration_minutes'])/60,2) ?>h
                      <?php endif; ?>
                      <?php if(!empty($r['data_bytes'])): ?>
                        <?= round(((int)$r['data_bytes'])/1024/1024/1024,2) ?>GB
                      <?php endif; ?>
                    </td>
                    <td><?= h($r['rate_limit'] ?: '-') ?></td>
                    <td><span class="badge badge-secondary"><?= h($r['status']) ?></span></td>
                    <td class="small">
                      <?php if($r['status'] === 'sold' || $r['sold_at']): ?>
                        <div><?= h($r['sold_to'] ?: '-') ?></div>
                        <div class="text-muted"><?= h($r['sold_at'] ?: '') ?></div>
                      <?php else: ?>
                        <span class="text-muted">-</span>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      
      <div class="card ua-u-hidden" id="previewCard">
        <div class="card-header d-flex justify-content-between align-items-center flex-wrap ua-u-gap-8">
          <div>
            <b>معاينة الطباعة</b>
            <div class="small text-muted">يمكنك مراجعة الشكل هنا ثم الضغط على "طباعة المحدد" لفتح الطباعة في تبويب جديد.</div>
          </div>
          <div class="ua-u-d-flex ua-u-gap-8 ua-u-flex-wrap">
            <button class="btn btn-success" type="button" id="btnPrintSelected"><i class="fa fa-print"></i> طباعة المحدد</button>
            <button class="btn btn-outline-secondary" type="button" id="btnHidePreview"><i class="fa fa-times"></i> إخفاء</button>
          </div>
        </div>
        <div class="card-body p-0">
          <iframe id="previewFrame" class="ua-u-iframe-preview"></iframe>
        </div>
      </div>

<div class="alert alert-warning">
        <b>ملاحظة:</b> يمكنك طباعة المحدد فقط، أو الرجوع لطباعة كامل الدفعة.
      </div>

    </div>
  </section>
</div>

<script>
function baseDir(){
  return window.location.origin + window.location.pathname.replace(/\/[^\/]*$/, '/');
}
function getSelectedIds(){
  const ids = [];
  document.querySelectorAll('.chkRow:checked').forEach(ch => ids.push(ch.value));
  return ids;
}
function updateCount(){
  const n = getSelectedIds().length;
  document.getElementById('selCount').textContent = 'المحدد: ' + n;
}
function applyFilter(){
  const v = document.getElementById('filterSel').value;
  document.querySelectorAll('table tbody tr').forEach(tr=>{
    const sold = tr.getAttribute('data-sold') === '1';
    let show = true;
    if(v==='sold') show = sold;
    if(v==='unsold') show = !sold;
    tr.style.display = show ? '' : 'none';
  });
}
function buildPrintUrl(ids, paper, auto, exp){
  const url = new URL('vouchers_print.php', baseDir());
  url.searchParams.set('ids', ids.join(','));
  url.searchParams.set('paper', paper);
  url.searchParams.set('auto', auto ? '1':'0');
  url.searchParams.set('export', exp ? '1':'0');
  return url.toString();
}

document.getElementById('chkAll').addEventListener('change', function(){
  document.querySelectorAll('.chkRow').forEach(ch => ch.checked = this.checked);
  updateCount();
});
document.querySelectorAll('.chkRow').forEach(ch => ch.addEventListener('change', updateCount));

document.getElementById('paperSel').addEventListener('change', function(){
  const url = new URL(window.location.href);
  url.searchParams.set('paper', this.value);
  window.location.href = url.toString();
});

document.getElementById('filterSel').addEventListener('change', applyFilter);

document.getElementById('btnPreview').addEventListener('click', function(){
  const ids = getSelectedIds();
  if(ids.length === 0){ alert('اختر كرت واحد على الأقل'); return; }
  const paper = document.getElementById('paperSel').value;
  const autoExport = document.getElementById('autoExport').checked;
  // Preview inline (no auto-print)
  const src = buildPrintUrl(ids, paper, false, autoExport);
  const frame = document.getElementById('previewFrame');
  frame.src = src;
  document.getElementById('previewCard').style.display = '';
  setTimeout(()=>document.getElementById('previewCard').scrollIntoView({behavior:'smooth'}), 50);
});

document.getElementById('btnPrintSelected').addEventListener('click', function(){
  const ids = getSelectedIds();
  if(ids.length === 0){ alert('اختر كرت واحد على الأقل'); return; }
  const paper = document.getElementById('paperSel').value;
  const auto = document.getElementById('autoPrint').checked;
  const autoExport = document.getElementById('autoExport').checked;
  const url = buildPrintUrl(ids, paper, auto, autoExport);
  window.open(url, '_blank');
});

document.getElementById('btnHidePreview').addEventListener('click', function(){
  document.getElementById('previewCard').style.display = 'none';
  document.getElementById('previewFrame').src = 'about:blank';
});


document.getElementById('btnPrintUnsold').addEventListener('click', function(){
  // Select all unsold rows (data-sold=0)
  document.querySelectorAll('table tbody tr').forEach(tr=>{
    const sold = tr.getAttribute('data-sold') === '1';
    const chk = tr.querySelector('.chkRow');
    if(chk) chk.checked = !sold;
  });
  updateCount();
  const ids = getSelectedIds();
  if(ids.length === 0){ alert('لا يوجد كروت غير مباع ضمن هذه الدفعة'); return; }
  const paper = document.getElementById('paperSel').value;
  const auto = document.getElementById('autoPrint').checked;
  const autoExport = document.getElementById('autoExport').checked;
  const url = buildPrintUrl(ids, paper, auto, autoExport);
  // show preview inline (no auto-print)
  document.getElementById('previewFrame').src = buildPrintUrl(ids, paper, false, autoExport);
  document.getElementById('previewCard').style.display = '';
  setTimeout(()=>document.getElementById('previewCard').scrollIntoView({behavior:'smooth'}), 50);
  window.open(url, '_blank');
});

document.getElementById('btnPrintSold').addEventListener('click', function(){
  // Select all sold rows (data-sold=1)
  document.querySelectorAll('table tbody tr').forEach(tr=>{
    const sold = tr.getAttribute('data-sold') === '1';
    const chk = tr.querySelector('.chkRow');
    if(chk) chk.checked = sold;
  });
  updateCount();
  const ids = getSelectedIds();
  if(ids.length === 0){ alert('لا يوجد كروت مباع ضمن هذه الدفعة'); return; }
  const paper = document.getElementById('paperSel').value;
  const auto = document.getElementById('autoPrint').checked;
  const autoExport = document.getElementById('autoExport').checked;
  const url = buildPrintUrl(ids, paper, auto, autoExport);
  document.getElementById('previewFrame').src = buildPrintUrl(ids, paper, false, autoExport);
  document.getElementById('previewCard').style.display = '';
  setTimeout(()=>document.getElementById('previewCard').scrollIntoView({behavior:'smooth'}), 50);
  window.open(url, '_blank');
});

updateCount();
applyFilter();
</script>
<?php include __DIR__ . '/footer.php'; ?>
