<?php
// view: pages/masters/units
use App\Shared\Support\Format;

$rows = $rows ?? [];
$edit = $edit ?? null;
$base_units = $base_units ?? [];
?>
<div class="row g-3">
  <div class="col-lg-7">
    <div class="card shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong>تعريف الوحدات</strong>
        <span class="text-muted small"><?= count($rows) ?> وحدة</span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover table-striped table-bordered align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th style="width:90px;">#</th>
                <th>اسم الوحدة</th>
                <th style="width:130px;">الرمز</th>
                <th style="width:120px;">النوع</th>
                <th>الوحدة الأساسية</th>
                <th style="width:140px;">عدد الأساسية</th>
                <th class="text-center" style="width:110px;">تعديل</th>
                <th class="text-center" style="width:110px;">حذف</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($rows as $r): ?>
                <?php $is_pack = !empty($r['base_unit_id']); ?>
                <tr>
                  <td><?= (int)$r['id'] ?></td>
                  <td class="fw-semibold"><?= e($r['name']) ?></td>
                  <td><?= e($r['symbol'] ?? '') ?></td>
                  <td>
                    <?php if ($is_pack): ?>
                      <span class="badge text-bg-secondary">إجمالية</span>
                    <?php else: ?>
                      <span class="badge text-bg-success">أساسية</span>
                    <?php endif; ?>
                  </td>
                  <td><?= $is_pack ? e($r['base_name'] ?? '-') : '-' ?></td>
                  <td><?= $is_pack ? e(Format::qty($r['factor_to_base'] ?? 1, 6)) : '-' ?></td>
                  <td class="text-center">
                    <a class="btn btn-sm btn-outline-primary" href="<?= e(url('/inventory/units')) ?>?action=edit&id=<?= (int)$r['id'] ?>"><i class="fa-solid fa-pen"></i></a>
                  </td>
                  <td class="text-center">
                    <form method="post" action="<?= e(url('/inventory/units')) ?>" onsubmit="return confirm('تأكيد حذف الوحدة؟')" class="m-0">
                      <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                      <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"><i class="fa-solid fa-trash"></i></button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$rows): ?><tr><td colspan="8" class="text-center text-muted py-4">لا توجد بيانات</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-header"><strong><?= $edit ? 'تعديل وحدة' : 'إضافة وحدة' ?></strong></div>
      <div class="card-body">
        <form method="post" class="vstack gap-3" autocomplete="off">
          <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="action" value="save">
          <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">

          <?php
            $edit_base_id = (int)($edit['base_unit_id'] ?? 0);
            $is_pack = $edit && $edit_base_id > 0;
          ?>

          <div>
            <label class="form-label">نوع الوحدة</label>
            <div class="d-flex gap-3">
              <div class="form-check">
                <input class="form-check-input" type="radio" name="unit_kind" id="uk_base" value="base" <?= $is_pack ? '' : 'checked' ?>>
                <label class="form-check-label" for="uk_base">وحدة أساسية</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="unit_kind" id="uk_pack" value="pack" <?= $is_pack ? 'checked' : '' ?>>
                <label class="form-check-label" for="uk_pack">وحدة إجمالية</label>
              </div>
            </div>
          </div>

          <div id="pack_fields" class="vstack gap-3" style="<?= $is_pack ? '' : 'display:none;' ?>">
            <div>
              <label class="form-label">الوحدة الأساسية</label>
              <select class="form-select" name="base_unit_id" id="base_unit_id">
                <option value="0">اختر الوحدة الأساسية</option>
                <?php foreach ($base_units as $u): ?>
                  <?php if ((int)($edit['id'] ?? 0) !== (int)$u['id']): ?>
                    <option value="<?= (int)$u['id'] ?>" <?= ($edit_base_id === (int)$u['id']) ? 'selected' : '' ?>>
                      <?= e($u['name']) ?>
                    </option>
                  <?php endif; ?>
                <?php endforeach; ?>
              </select>
            </div>

            <div>
              <label class="form-label">كم وحدة أساسية داخل هذه الوحدة؟</label>
              <input class="form-control" type="number" step="1" min="1" name="factor_to_base" id="factor_to_base"
                     value="<?= e(Format::qty($edit['factor_to_base'] ?? 1, 6)) ?>" placeholder="مثال: كرتونة = 12 قطعة">
            </div>
          </div>

          <div>
            <label class="form-label">اسم الوحدة</label>
            <input class="form-control" name="name" value="<?= e($edit['name'] ?? '') ?>" required>
          </div>

          <div>
            <label class="form-label">الرمز</label>
            <input class="form-control" name="symbol" value="<?= e($edit['symbol'] ?? '') ?>" placeholder="اختياري (EA)">
          </div>

          <div class="d-flex gap-2">
            <button class="btn btn-primary flex-fill"><i class="fa-solid fa-save me-2"></i>حفظ</button>
            <a class="btn btn-outline-secondary" href="<?= e(url('/inventory/units')) ?>">جديد</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const baseRadio = document.getElementById('uk_base');
  const packRadio = document.getElementById('uk_pack');
  const packFields = document.getElementById('pack_fields');
  const baseUnit = document.getElementById('base_unit_id');
  const factor = document.getElementById('factor_to_base');

  function sync(){
    const isPack = packRadio && packRadio.checked;
    if (!packFields) return;
    packFields.style.display = isPack ? '' : 'none';
    if (!isPack) {
      if (baseUnit) baseUnit.value = '0';
      if (factor) factor.value = '1';
    }
  }

  if (baseRadio) baseRadio.addEventListener('change', sync);
  if (packRadio) packRadio.addEventListener('change', sync);
  sync();
})();
</script>
