<?php
$page_title = 'تقارير الاستهلاك (الكروت)';
$UA_FORCE_DESIGN_V2 = true;
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);

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

$where = [];
if ($batch > 0) $where[] = 'v.batch_id='.(int)$batch;
if ($status !== '' && in_array($status, ['new','sold','used','expired','cancelled'], true)) {
  $where[] = "v.status='".$conn->real_escape_string($status)."'";
}

$sql = "SELECT v.id, v.code, v.sold_to, v.status, v.type, v.data_bytes, v.duration_minutes, v.rate_limit, v.mt_username,
               a.bytes_in, a.bytes_out, a.uptime_sec, a.last_update_at,
               b.title AS batch_title
        FROM vouchers v
        LEFT JOIN voucher_accounting a ON a.voucher_id=v.id
        LEFT JOIN voucher_batches b ON b.id=v.batch_id";
if ($where) $sql .= " WHERE ".implode(' AND ', $where);
$sql .= " ORDER BY (a.last_update_at IS NULL), a.last_update_at DESC, v.id DESC LIMIT 500";

$rows = [];
$q = $conn->query($sql);
if ($q) $rows = $q->fetch_all(MYSQLI_ASSOC);

// batches dropdown
$batchRows = [];
$bq = $conn->query("SELECT id,title,created_at,qty FROM voucher_batches ORDER BY id DESC LIMIT 200");
if ($bq) while($r = $bq->fetch_assoc()) $batchRows[] = $r;

function fmt_bytes($n){
  $n = (float)$n;
  $u = ['B','KB','MB','GB','TB'];
  $i=0;
  while($n>=1024 && $i<count($u)-1){ $n/=1024; $i++; }
  return number_format($n, $i===0?0:2).' '.$u[$i];
}
?>

<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-outline-dark" href="vouchers.php"><i class="fa fa-arrow-left"></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">
          <label class="small text-muted">دفعة</label>
          <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'] ?: 'بدون عنوان') ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="small text-muted">الحالة</label>
          <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-2 d-flex align-items-end">
          <button class="btn btn-primary">تطبيق</button>
        </div>
        <div class="col-md-3 d-flex align-items-end justify-content-end">
          <span class="text-muted small">يتم التحديث عبر Accounting Push من MikroTik.</span>
        </div>
      </form>
    </div></div>

    <div class="card"><div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped table-hover mb-0">
          <thead>
            <tr>
              <th>#</th>
              <th>الكود</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="10" class="text-center text-muted p-4">لا توجد بيانات.</td></tr>
          <?php else: foreach($rows as $r):
            $used = (int)($r['bytes_in'] ?? 0) + (int)($r['bytes_out'] ?? 0);
            $limit = (int)($r['data_bytes'] ?? 0);
          ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td><code><?= h($r['code'] ?? '') ?></code></td>
              <td><?= h($r['batch_title'] ?? '') ?></td>
              <td><?= h($r['sold_to'] ?? '') ?></td>
              <td><?= h($r['status'] ?? '') ?></td>
              <td><?= h($r['type'] ?? '') ?></td>
              <td><code><?= h($r['mt_username'] ?? '') ?></code></td>
              <td><?= fmt_bytes($used) ?></td>
              <td><?= $limit>0?fmt_bytes($limit):'<span class="text-muted">—</span>' ?></td>
              <td><?= h($r['last_update_at'] ?? '') ?></td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div></div>
  </div></section>
</div>

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