<?php
$page_title = 'كروت الإنترنت';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidVouchers = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidVouchers) $UA_PAGE_CSS = ['assets/css/android_vouchers.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/helpers.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);

$q = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));
$batch = (int)($_GET['batch'] ?? 0);

$where = [];
$params = [];
$types = '';

if ($q !== '') {
  $where[] = "(code LIKE CONCAT('%',?,'%') OR sold_to LIKE CONCAT('%',?,'%'))";
  $params[] = $q; $params[] = $q; $types .= 'ss';
}
if ($status !== '' && in_array($status, ['new','sold','used','expired','cancelled'], true)) {
  $where[] = "status=?";
  $params[] = $status; $types .= 's';
}
if ($batch > 0) {
  $where[] = "batch_id=?";
  $params[] = $batch; $types .= 'i';
}

$sql = "SELECT v.*, b.title AS batch_title
        FROM vouchers v
        LEFT JOIN voucher_batches b ON b.id=v.batch_id";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY v.id DESC LIMIT 500";

$stmt = $conn->prepare($sql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$res = $stmt->get_result();
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
$stmt->close();

// batches dropdown
$batchRows = [];
$bq = $conn->query("SELECT id,title,created_at,qty FROM voucher_batches ORDER BY id DESC LIMIT 100");
if ($bq) while($r = $bq->fetch_assoc()) $batchRows[] = $r;
if ($uaAndroidVouchers) {
  require __DIR__ . '/android_vouchers.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid d-flex align-items-center justify-content-between flex-wrap">
      <h1 class="mb-0">كروت الإنترنت</h1>
      <div class="mt-2">
        <a class="btn btn-primary" href="vouchers_generate.php"><i class="fa fa-magic"></i> توليد دفعة</a>
        <a class="btn btn-secondary" href="vouchers_print.php<?= $batch>0?'?batch='.urlencode((string)$batch):'' ?><?= ($batch>0?'&':'?') ?>paper=A4"><i class="fa fa-print"></i> طباعة</a>
        <?php if($batch>0): ?>
          <a class="btn btn-outline-secondary" href="vouchers_print_select.php?batch=<?= (int)$batch ?>&paper=A4"><i class="fa fa-eye"></i> معاينة الدفعة</a>
        <?php endif; ?>
        <a class="btn btn-outline-success" href="vouchers_usage_report.php"><i class="fa fa-chart-bar"></i> تقارير الاستهلاك</a>
        <a class="btn btn-outline-dark" href="vouchers_settings.php"><i class="fa fa-cog"></i> إعدادات</a>
      </div>
    </div>
  </section>

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

      <div class="card">
        <div class="card-body">
          <form class="row g-2" method="get">
            <div class="col-md-4">
              <input class="form-control" name="q" placeholder="بحث بالكود أو اسم المشتري..." value="<?= h($q) ?>">
            </div>
            <div class="col-md-3">
              <select class="form-control" name="status">
                <option value="">كل الحالات</option>
                <?php foreach(['new'=>'جديد','sold'=>'مباع','used'=>'مستخدم','expired'=>'منتهي','cancelled'=>'ملغي'] as $k=>$lab): ?>
                  <option value="<?= h($k) ?>" <?= $status===$k?'selected':'' ?>><?= h($lab) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-3">
              <select class="form-control" name="batch">
                <option value="0">كل الدفعات</option>
                <?php foreach($batchRows as $b): ?>
                  <option value="<?= (int)$b['id'] ?>" <?= $batch==(int)$b['id']?'selected':'' ?>>
                    #<?= (int)$b['id'] ?> — <?= h($b['title']) ?> (<?= (int)$b['qty'] ?>)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-2">
              <button class="btn btn-info w-100"><i class="fa fa-search"></i> بحث</button>
            </div>

            <?php if($batch>0): ?>
              <div class="col-md-2">
                <a class="btn btn-secondary w-100" href="vouchers_print.php?batch=<?= (int)$batch ?>&paper=80MM&auto=1"><i class="fa fa-print"></i> طباعة الدفعة</a>
              </div>
            <?php endif; ?>

          </form>
        </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>#</th>
                  <th>الدفعة</th>
                  <th>الكود</th>
                  <th>الرقم السري</th>
                  <th>النوع</th>
                  <th>الحدود</th>
                  <th>السرعة</th>
                  <th>الحالة</th>
                  <th>بيع</th>
                  <th>فاتورة</th>
                  <th>قبض</th>
                  <th>مستخدم MikroTik</th>
                  <th class="ua-u-w-220">إجراءات</th>
                </tr>
              </thead>
              <tbody>
                <?php if(!$rows): ?>
                  <tr><td colspan="13" class="text-center text-muted p-4">لا توجد بيانات.</td></tr>
                <?php endif; ?>

                <?php foreach($rows as $r): ?>
                  <tr>
                    <td><?= (int)$r['id'] ?></td>
                    <td><?= $r['batch_id'] ? ('#'.(int)$r['batch_id'].' '.h($r['batch_title'] ?? '')) : '-' ?></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>
                      <?php
                        $badge = [
                          'new'=>'secondary',
                          'sold'=>'primary',
                          'used'=>'success',
                          'expired'=>'dark',
                          'cancelled'=>'danger'
                        ][$r['status']] ?? 'secondary';
                      ?>
                      <span class="badge badge-<?= h($badge) ?>"><?= 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>
                    <td class="small">
                      <?php if(!empty($r['shop_sale_id'])): ?>
                        <a class="btn btn-outline-primary btn-sm" href="sales_view.php?id=<?= (int)$r['shop_sale_id'] ?>">
                          #<?= (int)$r['shop_sale_id'] ?>
                        </a>
                      <?php else: ?>
                        <span class="text-muted">-</span>
                      <?php endif; ?>
                    </td>
                    <td class="small">
                      <?php if(!empty($r['payment_id'])): ?>
                        <a class="btn btn-outline-success btn-sm" href="finance_payments.php?payment_id=<?= (int)$r['payment_id'] ?>">
                          #<?= (int)$r['payment_id'] ?>
                        </a>
                      <?php elseif(!empty($r['shop_sale_id'])): ?>
                        <a class="btn btn-outline-success btn-sm" href="finance_payments.php?ref=<?= urlencode('SHOP_SALE#'.(int)$r['shop_sale_id']) ?>">
                          عبر المرجع
                        </a>
                      <?php else: ?>
                        <span class="text-muted">-</span>
                      <?php endif; ?>
                    </td>
                    <td class="small">
                      <?php if($r['mt_username']): ?>
                        <div><code><?= h($r['mt_username']) ?></code></div>
                      <?php else: ?>
                        <span class="text-muted">-</span>
                      <?php endif; ?>
                    </td>
                    <td>
                      <div class="btn-group btn-group-sm" role="group">
                        <button class="btn btn-success" onclick="markSold(<?= (int)$r['id'] ?>, '<?= h($r['code']) ?>', <?= json_encode($r['price']) ?>)"><i class="fa fa-check"></i> بيع</button>
                        <a class="btn btn-secondary" href="vouchers_print.php?voucher_id=<?= (int)$r['id'] ?>&paper=80MM&auto=1"><i class="fa fa-print"></i> طباعة</a>
                        <?php if($r['status'] !== 'used' && $r['status'] !== 'expired'): ?>
                          <button class="btn btn-danger" onclick="cancelVoucher(<?= (int)$r['id'] ?>, '<?= h($r['code']) ?>')"><i class="fa fa-ban"></i> إلغاء</button>
                        <?php endif; ?>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="alert alert-info">
        <b>ملاحظة:</b> عند الضغط على <b>MikroTik</b> سيتم إنشاء مستخدم Hotspot بنفس الكود/الرقم السري (إذا لم يكن موجودًا).

      </div>

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

<script>
async function postAction(payload){
  const res = await fetch('vouchers_api.php', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
    body: new URLSearchParams(payload).toString()
  });

  // بعض الأخطاء ترجع HTML (تسجيل دخول/تحذير PHP) فيفشل res.json()
  const txt = await res.text();
  try{
    return JSON.parse(txt);
  }catch(e){
    console.error('Non-JSON response:', txt);
    // ⚠️ تجنّب كسر JavaScript بسطر جديد داخل string
    return {ok:false, error: 'Non-JSON response (قد تكون الجلسة منتهية أو يوجد Warning PHP).\n\n' + txt};
  }
}

async function markSold(id, code, price){
  const sold_to = prompt('اسم/هاتف المشتري (اختياري):', '');
  if (sold_to === null) return;

  let p = price;
  const price_in = prompt('السعر (اختياري):', (p===null || p===undefined) ? '' : String(p));
  if (price_in === null) return;

  const r = await postAction({action:'mark_sold', id, sold_to, price: price_in, make_sale: 1});
  if(!r.ok){ alert(r.error || 'فشل'); return; }
  if(r.sale_id){
    if(confirm('تم البيع وإنشاء فاتورة مبيعات رقم #' + r.sale_id + '\nهل تريد فتح الفاتورة الآن؟')){
      window.location.href = 'sales_view.php?id=' + r.sale_id;
      return;
    }
  }
  if(r.payment_id){
    if(confirm('تم تسجيل القبض رقم #' + r.payment_id + "\nهل تريد فتح سجل الدفعة الآن؟")){
      window.location.href = 'finance_payments.php?payment_id=' + r.payment_id;
      return;
    }
  }
  location.reload();
}

async function cancelVoucher(id, code){
  if(!confirm('تأكيد إلغاء الكرت: '+code+' ؟')) return;
  const r = await postAction({action:'cancel', id});
  if(!r.ok){ alert(r.error || 'فشل'); return; }
  location.reload();
}

async function createHotspot(id, code){
  if(!confirm('إنشاء مستخدم Hotspot لهذا الكرت على MikroTik؟\n'+code)) return;
  const r = await postAction({action:'create_hotspot_user', id});
  if(!r.ok){ alert(r.error || 'فشل'); return; }
  alert('تم.\nUsername: '+r.username+'\nPassword: '+r.password);
  location.reload();
}
async function resetViolations(id, code){
  if(!confirm("تأكيد تصفير المخالفات لهذا الكرت على MikroTik؟\nالكود: " + code)) return;
  const r = await postAction({action:"reset_violations", id});
  if(!r.ok){ alert(r.error || "فشل العملية"); return; }
  alert("تم تصفير المخالفات وإعادة تفعيل المستخدم (إن كان مقفولاً).");
  location.reload();
}

</script>

<?php include __DIR__ . '/footer.php'; ?>
