<?php
$page_title = 'توليد كروت الإنترنت';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidVoucherGenerate = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidVoucherGenerate) $UA_PAGE_CSS = ['assets/css/android_vouchers_generate.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_once __DIR__ . '/shop_lib.php';

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

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

$voucher_products = [];
$qvp = $conn->query("SELECT id,name,price,voucher_type,voucher_duration_minutes,voucher_data_bytes,voucher_rate_limit,voucher_mt_profile,voucher_start_on_first_use FROM shop_products WHERE is_active=1 AND is_voucher=1 ORDER BY id DESC");
if ($qvp) $voucher_products = $qvp->fetch_all(MYSQLI_ASSOC);

$err = '';
$ok  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    $title = trim((string)($_POST['title'] ?? 'دفعة كروت'));
    $product_id = (int)($_POST['product_id'] ?? 0);
    $product = null;
    if ($product_id > 0) {
      $pq = $conn->query("SELECT * FROM shop_products WHERE id=$product_id AND is_voucher=1 LIMIT 1");
      $product = ($pq && $pq->num_rows) ? $pq->fetch_assoc() : null;
      if (!$product) throw new RuntimeException('صنف الكرت غير موجود');
      $type = (string)($product['voucher_type'] ?? 'time');
      if (!in_array($type, ['time','data','both'], true)) $type='time';
    }

    $type  = ($_POST['type'] ?? 'time');
    if ($product) { $type = (string)($product['voucher_type'] ?? $type); }
    if (!in_array($type, ['time','data','both'], true)) $type = 'time';

    $qty = (int)($_POST['qty'] ?? 0);
    if ($qty < 1 || $qty > 5000) throw new RuntimeException('الكمية يجب أن تكون بين 1 و 5000');

    $prefix = trim((string)($_POST['prefix'] ?? 'V'));
    $code_len = (int)($_POST['code_len'] ?? 8);
    if ($code_len < 4 || $code_len > 20) $code_len = 8;

    $days = (float)($_POST['days'] ?? 0);
    $gb   = (float)($_POST['gb'] ?? 0);
    $rate = trim((string)($_POST['rate_limit'] ?? ''));
    $price = ($_POST['price'] ?? null);
    $price = ($price === '' || $price === null) ? null : (float)$price;

    $duration_minutes = null;
    $data_bytes = null;

    if ($type === 'time' || $type === 'both') {
      $duration_minutes = $product ? (int)($product['voucher_duration_minutes'] ?? 0) : vouchers_minutes_from_days($days);
      if ($duration_minutes <= 0) throw new RuntimeException('مدة الكرت مطلوبة');
    }
    if ($type === 'data' || $type === 'both') {
      $data_bytes = $product ? (int)($product['voucher_data_bytes'] ?? 0) : vouchers_bytes_from_gb($gb);
      if ($data_bytes <= 0) throw new RuntimeException('حجم الكرت مطلوب');
    }

    $notes = trim((string)($_POST['notes'] ?? ''));
    $me = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));

    $stmt = $conn->prepare("INSERT INTO voucher_batches (created_by, product_id, title, type, duration_minutes, data_bytes, rate_limit, price, qty, prefix, code_len, notes)
                            VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt->bind_param(
      'iissiisdisis',
      $me,
      $product_id,
      $title,
      $type,
      $duration_minutes,
      $data_bytes,
      $rate,
      $price,
      $qty,
      $prefix,
      $code_len,
      $notes
    );
    $stmt->execute();
    $batch_id = (int)$stmt->insert_id;
    $stmt->close();

    $ins = $conn->prepare("INSERT INTO vouchers (batch_id, product_id, code, passcode, type, duration_minutes, data_bytes, rate_limit, price)
                           VALUES (?,?,?,?,?,?,?,?,?)");

    $created = 0;
    $tries = 0;
    while ($created < $qty) {
      $tries++;
      if ($tries > $qty * 20) throw new RuntimeException('تعذر توليد أكواد فريدة، جرّب زيادة طول الكود');

      $code = vouchers_generate_code($code_len, $prefix);
      $pass = vouchers_generate_pass(6);

      $t_type = $type;
      $dur = $duration_minutes;
      $db  = $data_bytes;
      $rl  = $rate;
      $pr  = $price;

      $ins->bind_param('iissssiisd', $batch_id, $product_id, $code, $pass, $t_type, $dur, $db, $rl, $pr);
      @$ins->execute();
      if ($ins->affected_rows === 1) {
        $created++;
      }
    }
    $ins->close();

    if ($product_id > 0) {
      $conn->query("UPDATE shop_products SET stock_qty = stock_qty + $qty WHERE id=$product_id");
    }

    $ok = "تم توليد {$created} كرت بنجاح (دفعة رقم: {$batch_id}).";
  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}
if ($uaAndroidVoucherGenerate) {
  require __DIR__ . '/android_vouchers_generate.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper vg-shell ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid">
      <div class="vg-hero">
        <div>
          <h1 class="vg-title">توليد كروت الإنترنت</h1>
          <p class="vg-sub">واجهة مرتبة وسريعة لإنشاء دفعات الكروت بدون أي نصوص مساعدة مزعجة.</p>
        </div>
        <div class="vg-actions">
          <a class="btn btn-outline-light vg-btn" href="vouchers.php">عودة لإدارة الكروت</a>
        </div>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php if($err): ?>
        <div class="alert alert-danger vg-alert"><?= h($err) ?></div>
      <?php endif; ?>
      <?php if($ok): ?>
        <div class="alert alert-success vg-alert"><?= h($ok) ?></div>
      <?php endif; ?>

      <div class="card vg-card">
        <div class="card-body">
          <form method="post" autocomplete="off">
            <input type="hidden" name="notes" value="<?= h($_POST['notes'] ?? '') ?>">
            <div class="vg-grid">
              <div class="vg-col-4 vg-field">
                <label>صنف الكرت</label>
                <select class="form-control" name="product_id">
                  <option value="0">إدخال يدوي</option>
                  <?php $pidSel = (int)($_POST['product_id'] ?? 0); foreach($voucher_products as $p): ?>
                    <option value="<?= (int)$p['id'] ?>" <?= $pidSel===(int)$p['id']?'selected':'' ?>><?= h($p['name']) ?> — <?= number_format((float)$p['price'],2) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>

              <div class="vg-col-4 vg-field">
                <label>عنوان الدفعة</label>
                <input class="form-control" name="title" value="<?= h($_POST['title'] ?? 'دفعة كروت') ?>" required>
              </div>

              <div class="vg-col-2 vg-field">
                <label>الكمية</label>
                <input type="number" class="form-control" name="qty" min="1" max="5000" value="<?= h($_POST['qty'] ?? 50) ?>" required>
              </div>

              <div class="vg-col-2 vg-field">
                <label>نوع الكرت</label>
                <select class="form-control" name="type">
                  <?php $t = $_POST['type'] ?? 'time'; ?>
                  <option value="time" <?= $t==='time'?'selected':'' ?>>زمني</option>
                  <option value="data" <?= $t==='data'?'selected':'' ?>>حجمي</option>
                  <option value="both" <?= $t==='both'?'selected':'' ?>>زمني + حجمي</option>
                </select>
              </div>

              <div class="vg-col-3 vg-field">
                <label>الأيام</label>
                <input type="number" step="0.1" class="form-control" name="days" value="<?= h($_POST['days'] ?? 1) ?>">
              </div>

              <div class="vg-col-3 vg-field">
                <label>GB</label>
                <input type="number" step="0.1" class="form-control" name="gb" value="<?= h($_POST['gb'] ?? 10) ?>">
              </div>

              <div class="vg-col-3 vg-field">
                <label>Rate Limit</label>
                <input class="form-control" name="rate_limit" value="<?= h($_POST['rate_limit'] ?? '') ?>">
              </div>

              <div class="vg-col-3 vg-field">
                <label>السعر</label>
                <input type="number" step="0.01" class="form-control" name="price" value="<?= h($_POST['price'] ?? '') ?>">
              </div>

              <div class="vg-col-3 vg-field">
                <label>Prefix</label>
                <input class="form-control" name="prefix" value="<?= h($_POST['prefix'] ?? 'V') ?>">
              </div>

              <div class="vg-col-3 vg-field">
                <label>طول الكود</label>
                <input type="number" class="form-control" name="code_len" min="4" max="20" value="<?= h($_POST['code_len'] ?? 8) ?>">
              </div>
            </div>

            <div class="vg-footer">
              <a class="btn btn-secondary vg-btn" href="vouchers.php">عودة لإدارة الكروت</a>
              <button class="btn btn-primary vg-btn"><i class="fa fa-magic"></i> توليد</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </section>
</div>
<?php include __DIR__ . '/footer.php'; ?>
