<?php
$page_title = 'المواد';
require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/shop_lib.php';

require_login();
$conn = ensure_db(true);
if(function_exists('require_perm')) require_perm('can_manage_sales');

ensure_shop_tables($conn);

$msg=''; $err='';

// CSRF
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

function require_csrf(): void {
  $sent = (string)($_POST['csrf_token'] ?? '');
  $sess = (string)($_SESSION['csrf_token'] ?? '');
  if ($sent === '' || $sess === '' || !hash_equals($sess, $sent)) {
    throw new RuntimeException('انتهت الجلسة أو رمز الحماية غير صحيح. حدّث الصفحة وحاول مجددًا.');
  }
}

$edit_id = (int)($_GET['edit'] ?? 0);
$edit_row = null;
if ($edit_id > 0) {
  $st = $conn->prepare("SELECT * FROM shop_products WHERE id=? LIMIT 1");
  $st->bind_param('i', $edit_id);
  $st->execute();
  $rs = $st->get_result();
  $edit_row = $rs ? $rs->fetch_assoc() : null;
  $st->close();
  if (!$edit_row) $edit_id = 0;
}

// PRG: avoid duplicate insert/update on refresh
$flash = (string)($_GET['msg'] ?? '');
if ($flash === 'added') $msg = 'تمت الإضافة ✅';
if ($flash === 'updated') $msg = 'تم التعديل ✅';
if ($flash === 'deleted') $msg = 'تم الحذف ✅';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    require_csrf();

    $action = (string)($_POST['action'] ?? '');
    $name = trim((string)($_POST['name'] ?? ''));
    $sku = trim((string)($_POST['sku'] ?? ''));
    $price = (float)($_POST['price'] ?? 0);
    $stock = (int)($_POST['qty'] ?? 0);
    $notes = trim((string)($_POST['notes'] ?? ''));

    $is_voucher = isset($_POST['is_voucher']) ? 1 : 0;
    $voucher_type = (string)($_POST['voucher_type'] ?? 'time');
    if (!in_array($voucher_type, ['time','data','both'], true)) $voucher_type = 'time';

    $voucher_duration_minutes = null;
    $voucher_data_bytes = null;
    $voucher_rate_limit = trim((string)($_POST['voucher_rate_limit'] ?? ''));
    $voucher_mt_profile = trim((string)($_POST['voucher_mt_profile'] ?? ''));
    $voucher_start_on_first_use = isset($_POST['voucher_start_on_first_use']) ? 1 : 0;

    if ($is_voucher) {
      $v_days = (float)($_POST['voucher_days'] ?? 0);
      $v_gb = (float)($_POST['voucher_gb'] ?? 0);

      if ($voucher_type === 'time' || $voucher_type === 'both') {
        $voucher_duration_minutes = (int)round($v_days * 1440);
        if ($voucher_duration_minutes <= 0) throw new RuntimeException('مدة الكرت مطلوبة (أيام > 0)');
      }
      if ($voucher_type === 'data' || $voucher_type === 'both') {
        $voucher_data_bytes = (int)round($v_gb * 1073741824);
        if ($voucher_data_bytes <= 0) throw new RuntimeException('حجم الكرت مطلوب (GB > 0)');
      }
    } else {
      // non-voucher: ignore voucher fields
      $voucher_type = 'time';
      $voucher_duration_minutes = null;
      $voucher_data_bytes = null;
      $voucher_rate_limit = '';
      $voucher_mt_profile = '';
      $voucher_start_on_first_use = 0;
    }

    if ($action === 'add') {
      if ($name==='') throw new RuntimeException('اسم المادة مطلوب');

      $stmt = $conn->prepare("INSERT INTO shop_products
        (name, sku, description, price, stock_qty, is_voucher, voucher_type, voucher_duration_minutes, voucher_data_bytes, voucher_rate_limit, voucher_mt_profile, voucher_start_on_first_use)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
      $stmt->bind_param(
        'sssdiiisissi',
        $name,
        $sku,
        $notes,
        $price,
        $stock,
        $is_voucher,
        $voucher_type,
        $voucher_duration_minutes,
        $voucher_data_bytes,
        $voucher_rate_limit,
        $voucher_mt_profile,
        $voucher_start_on_first_use
      );
      $stmt->execute();
      $stmt->close();

      header('Location: sales_products.php?msg=added');
      exit;
    }

    if ($action === 'update') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) throw new RuntimeException('معرّف المادة غير صحيح');
      if ($name==='') throw new RuntimeException('اسم المادة مطلوب');

      $stmt = $conn->prepare("UPDATE shop_products SET
        name=?, sku=?, description=?, price=?, stock_qty=?,
        is_voucher=?, voucher_type=?, voucher_duration_minutes=?, voucher_data_bytes=?,
        voucher_rate_limit=?, voucher_mt_profile=?, voucher_start_on_first_use=?
        WHERE id=? LIMIT 1");
      $stmt->bind_param(
        'sssdiiisissii',
        $name,
        $sku,
        $notes,
        $price,
        $stock,
        $is_voucher,
        $voucher_type,
        $voucher_duration_minutes,
        $voucher_data_bytes,
        $voucher_rate_limit,
        $voucher_mt_profile,
        $voucher_start_on_first_use,
        $id
      );
      $stmt->execute();
      $stmt->close();

      header('Location: sales_products.php?msg=updated');
      exit;
    }

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) throw new RuntimeException('معرّف المادة غير صحيح');

      // safeguard: if product used in sales_lines, block delete
      $can = true;
      $chk = $conn->prepare("SELECT COUNT(*) c FROM shop_sale_lines WHERE product_id=?");
      if ($chk) {
        $chk->bind_param('i', $id);
        $chk->execute();
        $r = $chk->get_result();
        $row = $r ? $r->fetch_assoc() : null;
        $chk->close();
        if ($row && (int)$row['c'] > 0) $can = false;
      }
      if (!$can) throw new RuntimeException('لا يمكن حذف هذا الصنف لأنه مستخدم في عمليات بيع سابقة.');

      $del = $conn->prepare("DELETE FROM shop_products WHERE id=? LIMIT 1");
      $del->bind_param('i', $id);
      $del->execute();
      $del->close();

      header('Location: sales_products.php?msg=deleted');
      exit;
    }

  } catch(Throwable $e) {
    $err = $e->getMessage();
  }
}
$rows = $conn->query("SELECT * FROM shop_products ORDER BY id DESC");
$active_tab = 'products';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidSalesProducts = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidSalesProducts) $UA_PAGE_CSS = ['assets/css/android_sales_products.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

if ($uaAndroidSalesProducts) {
  require __DIR__ . '/android_sales_products.php';
  include __DIR__ . '/footer.php';
  return;
}

?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header"><div class="container-fluid"><h1 class="mb-0">المواد</h1></div></section>
  <section class="content"><div class="container-fluid">
    <?php if($msg){?><div class="alert alert-success"><?=h($msg)?></div><?php }?>
    <?php if($err){?><div class="alert alert-danger"><?=h($err)?></div><?php }?>

    <div class="card"><div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
        <input type="hidden" name="action" value="<?= $edit_id>0?'update':'add' ?>">
        <?php if($edit_id>0): ?><input type="hidden" name="id" value="<?= (int)$edit_id ?>"><?php endif; ?>
        <div class="row">
          <div class="col-md-4"><label>اسم المادة</label><input name="name" class="form-control" required value="<?= h($edit_row['name'] ?? '') ?>"></div>
          <div class="col-md-2"><label>SKU</label><input name="sku" class="form-control" value="<?= h($edit_row['sku'] ?? '') ?>"></div>
          <div class="col-md-2"><label>السعر</label><input name="price" class="form-control" type="number" step="0.01" value="<?= h($edit_row['price'] ?? '') ?>"></div>
          <div class="col-md-2"><label>الكمية بالمخزن</label><input name="qty" class="form-control" type="number" value="<?= h($edit_row['stock_qty'] ?? 0) ?>"></div>
          <div class="col-md-2 d-flex align-items-end"><button class="btn btn-primary w-100" type="submit"><?= $edit_id>0?'حفظ التعديل':'إضافة' ?></button>
            <?php if($edit_id>0): ?><a class="btn btn-outline-secondary w-100 mt-2" href="sales_products.php">إلغاء</a><?php endif; ?></div>
        </div>

        <div class="mt-2"><label>مواصفات/ملاحظات</label><textarea name="notes" class="form-control" rows="2"><?= h($edit_row['description'] ?? '') ?></textarea></div>

        <hr>
        <div class="row">
          <div class="col-md-3">
            <label class="ua-u-d-flex ua-u-gap-8 ua-u-ai-center ua-u-mt-8">
              <input type="checkbox" name="is_voucher" value="1" <?= !empty($edit_row) && (int)($edit_row['is_voucher'] ?? 0)===1 ? 'checked' : '' ?>>
              <span>هذا صنف كرت (Voucher)</span>
            </label>
            <small class="text-muted">عند تفعيلها سيظهر الصنف ضمن توليد/بيع الكروت.</small>
          </div>
          <div class="col-md-3">
            <label>نوع الكرت</label>
            <select class="form-control" name="voucher_type">
              <option value="time" <?= (($edit_row['voucher_type'] ?? 'time')==='time'?'selected':'') ?>>زمني</option>
              <option value="data" <?= (($edit_row['voucher_type'] ?? 'time')==='data'?'selected':'') ?>>حجمي</option>
              <option value="both" <?= (($edit_row['voucher_type'] ?? 'time')==='both'?'selected':'') ?>>زمني + حجمي</option>
            </select>
          </div>
          <div class="col-md-2">
            <label>أيام</label>
            <input class="form-control" type="number" step="0.1" name="voucher_days" placeholder="مثال: 1">
          </div>
          <div class="col-md-2">
            <label>GB</label>
            <input class="form-control" type="number" step="0.1" name="voucher_gb" placeholder="مثال: 10">
          </div>
          <div class="col-md-2">
            <label>Rate Limit</label>
            <input class="form-control" name="voucher_rate_limit" placeholder="مثال: 5M/5M" value="<?= h($edit_row['voucher_rate_limit'] ?? '') ?>">
          </div>
        </div>

        <div class="row mt-2">
          <div class="col-md-4">
            <label>Hotspot Profile (اختياري)</label>
            <input class="form-control" name="voucher_mt_profile" placeholder="voucher" value="<?= h($edit_row['voucher_mt_profile'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="ua-u-d-flex ua-u-gap-8 ua-u-ai-center ua-u-mt-30">
              <input type="checkbox" name="voucher_start_on_first_use" value="1" checked>
              <span>بدء الصلاحية من أول اتصال</span>
            </label>
          </div>
        </div>
      </form>
    </div></div>

    <div class="card"><div class="card-body">
      <div class="table-responsive">
        <table class="table table-bordered">
          <thead><tr><th>#</th><th>الاسم</th><th>SKU</th><th>السعر</th><th>المخزون</th><th>النوع</th><th class="ua-u-w-160">إجراءات</th></tr></thead>
          <tbody>
            <?php if($rows) while($r=$rows->fetch_assoc()){ ?>
              <tr>
                <td><?= (int)$r['id'] ?></td>
                <td><?= h($r['name']) ?></td>
                <td><?= h($r['sku']) ?></td>
                <td><?= number_format((float)$r['price'],2) ?></td>
                <td><?= (int)($r['stock_qty'] ?? 0) ?></td>
                <td><?= !empty($r['is_voucher']) ? 'كرت' : 'صنف' ?></td>
                <td>
                  <a class="btn btn-sm btn-outline-primary" href="sales_products.php?edit=<?= (int)$r['id'] ?>">تعديل</a>
                  <form class="ua-u-inline" method="post" onsubmit="return confirm('حذف الصنف نهائياً؟');">
                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger" type="submit">حذف</button>
                  </form>
                </td>
              </tr>
            <?php } ?>
          </tbody>
        </table>
      </div>
    </div></div>
  </div></section>
</div>
<?php include __DIR__ . '/footer.php'; ?>
