<?php
require __DIR__ . '/inc/bootstrap.php';
require __DIR__ . '/inc/stock.php';
require_perm('materials');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = post('action');
  $id = (int)post('id', 0);
  if ($action === 'move') stock_handle_move('materials', 'material', 'materials.php');
  if ($action === 'save') {
    $name = str_limit(post('name'), 150);
    if ($name === '') { flash(__('اسم المادة مطلوب'), 'err'); redirect('materials.php'); }
    // كود المادة: قصير وفريد (حروف وأرقام و - _ .)
    $code = str_limit(post('code'), 30);
    if ($code !== '' && !preg_match('/^[A-Za-z0-9_.\-]{1,30}$/', $code)) { flash(__('الكود: حروف إنجليزية وأرقام فقط (مثل s234)'), 'err'); redirect('materials.php'); }
    if ($code !== '' && q_val('SELECT id FROM materials WHERE code = ? AND id <> ?', [$code, $id])) { flash(__('هذا الكود مستخدم لمادة أخرى'), 'err'); redirect('materials.php'); }
    // سعر الوحدة بالدينار أو الدولار: نحفظ الأصلي وعملته ، والمعتمد بالدينار للحساب
    $cur = post_cur('unit_cost');
    $orig = max(0, to_num($_POST['unit_cost'] ?? 0));
    $cost = max(0, to_iqd($orig, $cur));
    $data = [$code !== '' ? $code : null, $cur, $cur === 'USD' ? $orig : 0, $name, str_limit(post('unit') ?: __('قطعة'), 30), max(0, post_num('min_qty')), $cost, str_limit(post('supplier'), 150), str_limit(post('notes'), 2000)];
    if ($id) {
      q('UPDATE materials SET code=?, cur=?, unit_cost_orig=?, name=?, unit=?, min_qty=?, unit_cost=?, supplier=?, notes=? WHERE id=?', array_merge($data, [$id]));
    } else {
      $qty = max(0, post_num('qty'));
      q('INSERT INTO materials (code, cur, unit_cost_orig, name, unit, min_qty, unit_cost, supplier, notes, qty) VALUES (?,?,?,?,?,?,?,?,?,?)', array_merge($data, [$qty]));
      if ($qty > 0) q("INSERT INTO stock_moves (store, item_id, qty, note, user_id) VALUES ('material',?,?,?,?)", [db()->lastInsertId(), $qty, 'رصيد افتتاحي', uid()]);
    }
    log_activity('حفظ مادة: ' . $name);
    flash(__('تم الحفظ'));
  } elseif ($action === 'delete' && $id) {
    q('DELETE FROM materials WHERE id = ?', [$id]);
    q("DELETE FROM stock_moves WHERE store='material' AND item_id = ?", [$id]);
    log_activity("حذف مادة #$id");
    flash(__('تم الحذف'));
  }
  redirect('materials.php');
}

if ($hid = get_int('history')) stock_history('material', $hid, 'materials', 'materials.php', 'materials', __('مخزن المواد'));

$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$f = ($_GET['f'] ?? '') === 'low' ? 'low' : '';
$where = ['1=1']; $params = [];
if ($search !== '') { $where[] = '(name LIKE ? OR code LIKE ? OR supplier LIKE ?)'; array_push($params, "%$search%", "%$search%", "%$search%"); }
if ($f) $where[] = 'min_qty > 0 AND qty <= min_qty';
$w = implode(' AND ', $where);
[$off, $per, $pager] = paginate((int)q_val("SELECT COUNT(*) FROM materials WHERE $w", $params), 30);
// الكود المطابق أولاً ثم الناقصة ثم الاسم
$rows = q_all("SELECT * FROM materials WHERE $w ORDER BY " . ($search !== '' ? "(code = " . db()->quote($search) . ") DESC, " : '') . "(min_qty > 0 AND qty <= min_qty) DESC, name LIMIT $off, $per", $params);

// بطاقات المواد (تُستخدم في الصفحة وفي نتائج البحث الفوري)
function render_materials(array $rows, string $search, string $pager, int $found) {
  if ($search !== '') echo '<p class="os-res">' . e(__('%s نتيجة', $found)) . '</p>';
  echo '<div class="mgrid">';
  if (!$rows) empty_state(__('لا توجد مواد'), '📦');
  foreach ($rows as $r):
    $low = $r['min_qty'] > 0 && $r['qty'] <= $r['min_qty'];
    $lvl = $r['min_qty'] > 0 ? min(100, (int)round($r['qty'] / ($r['min_qty'] * 3) * 100)) : null;
    $lvlCls = $low ? 'low' : ($r['min_qty'] > 0 && $r['qty'] <= $r['min_qty'] * 1.5 ? 'mid' : 'ok');
    $usd = $r['cur'] === 'USD';
    $fill = ['id' => $r['id'], 'code' => $r['code'], 'name' => $r['name'], 'unit' => $r['unit'], 'min_qty' => (float)$r['min_qty'],
      'unit_cost' => (float)($usd ? $r['unit_cost_orig'] : $r['unit_cost']), 'unit_cost__cur' => $r['cur'], 'supplier' => $r['supplier'], 'notes' => $r['notes']]; ?>
    <article class="mc<?= $low ? ' low' : '' ?>">
      <div class="mc-top">
        <span class="mc-ic"><?= icon('box') ?></span>
        <div class="mc-id"><?php if ($r['code']): ?><span class="mc-code num"><?= hl($r['code'], $search) ?></span><?php endif; ?>
          <h3><?= hl($r['name'], $search) ?></h3></div>
        <?php if ($low): ?><span class="mc-flag"><?= __('⚠️ ناقصة') ?></span><?php endif; ?>
      </div>
      <div class="mc-qty"><b class="num"><?= num($r['qty']) ?></b><span><?= e($r['unit']) ?></span>
        <?php if ($r['min_qty'] > 0): ?><small><?= __('الحد الأدنى:') ?> <?= num($r['min_qty']) ?></small><?php endif; ?></div>
      <?php if ($lvl !== null): ?><div class="mc-bar <?= $lvlCls ?>"><i style="width:<?= max(4, $lvl) ?>%"></i></div><?php endif; ?>
      <div class="mc-money">
        <div><small><?= __('سعر الوحدة') ?></small><b class="num"><?= $usd ? '$' . num($r['unit_cost_orig']) : money($r['unit_cost']) ?></b>
          <?php if ($usd): ?><em class="mc-usd">≈ <?= money($r['unit_cost']) ?></em><?php endif; ?></div>
        <div><small><?= __('القيمة') ?></small><b class="num"><?= money($r['qty'] * $r['unit_cost']) ?></b></div>
      </div>
      <?php if ($r['supplier']): ?><p class="mc-sup"><?= __('المورد:') ?> <?= hl($r['supplier'], $search) ?></p><?php endif; ?>
      <div class="mc-act">
        <?= move_btn($r) ?>
        <a class="mini-btn" href="?history=<?= (int)$r['id'] ?>" title="<?= e(__('سجل الحركات')) ?>" aria-label="<?= e(__('سجل الحركات')) ?>"><?= icon('eye') ?></a>
        <?= edit_btn('m-mat', $fill, __('تعديل المادة')) ?>
        <?= delete_btn('delete', (int)$r['id'], __('حذف المادة وسجل حركاتها؟')) ?>
      </div>
    </article>
  <?php endforeach;
  echo '</div>' . $pager;
}

if (isset($_GET['ajax'])) { header('Content-Type: text/html; charset=utf-8'); render_materials($rows, $search, $pager, count($rows)); exit; }

$tot = q_one('SELECT COUNT(*) n, COALESCE(SUM(qty*unit_cost),0) val, COALESCE(SUM(min_qty > 0 AND qty <= min_qty),0) low, COALESCE(SUM(cur = \'USD\'),0) nusd FROM materials');
$units = q_all("SELECT DISTINCT unit FROM materials ORDER BY unit");

page_header('materials', __('مخزن المواد'));
?>
<section class="mh">
  <div class="mh-main">
    <span class="mh-ic"><?= icon('box') ?></span>
    <div><small><?= __('قيمة المواد الخام') ?></small><b class="num"><?= money($tot['val']) ?></b></div>
    <button class="mh-add" data-modal="m-mat"><?= icon('plus') ?><span><?= __('مادة جديدة') ?></span></button>
  </div>
  <div class="mh-stats">
    <div><small><?= __('عدد المواد') ?></small><b class="num"><?= (int)$tot['n'] ?></b></div>
    <div><small><?= __('مواد ناقصة') ?></small><b class="num"><?= (int)$tot['low'] ?></b></div>
    <div><small><?= __('سعر الصرف اليومي') ?></small><b class="num"><?= usd_rate() > 0 ? '1$ = ' . num(usd_rate()) : '—' ?></b></div>
  </div>
</section>

<nav class="otabs mtabs" aria-label="<?= e(__('تصفية')) ?>">
  <a class="otab<?= $f === '' ? ' on' : '' ?>" style="--tc:#14b8a6" href="?<?= e(http_build_query(array_filter(['q' => $search]))) ?>"><i></i><span><?= __('كل المواد') ?></span><em><?= (int)$tot['n'] ?></em></a>
  <a class="otab<?= $f === 'low' ? ' on' : '' ?>" style="--tc:#ef4444" href="?<?= e(http_build_query(array_filter(['f' => 'low', 'q' => $search]))) ?>"><i></i><span><?= __('⚠️ ناقصة') ?></span><em><?= (int)$tot['low'] ?></em></a>
</nav>

<form class="osearch" method="get" role="search" data-live="#live-list">
  <?php if ($f): ?><input type="hidden" name="f" value="<?= e($f) ?>"><?php endif; ?>
  <?= icon('search') ?>
  <input type="search" name="q" value="<?= e($search) ?>" placeholder="<?= e(__('ابحث بالكود أو الاسم أو المورد…')) ?>" aria-label="<?= e(__('بحث')) ?>" autocomplete="off">
  <button type="button" class="os-clear" data-live-clear<?= $search === '' ? ' hidden' : '' ?> aria-label="<?= e(__('مسح البحث')) ?>"><?= icon('x') ?></button>
</form>

<div id="live-list"><?php render_materials($rows, $search, $pager, count($rows)); ?></div>

<datalist id="units"><?php foreach (array_unique(array_merge([__('قطعة'), __('لوح'), __('متر'), __('كغم'), __('لتر'), __('علبة'), __('كيس')], array_column($units, 'unit'))) as $u): ?><option value="<?= e($u) ?>"><?php endforeach; ?></datalist>

<!-- نافذة مادة جديدة / تعديل: صغيرة وعصرية -->
<div class="modal-ov" id="m-mat" hidden>
  <form class="modal sm pm" method="post" autocomplete="off">
    <div class="pm-head">
      <span class="pm-ic teal"><?= icon('box') ?></span>
      <h3 data-title><?= __('مادة جديدة') ?></h3>
      <button type="button" class="icon-btn" data-close aria-label="<?= e(__('إغلاق')) ?>"><?= icon('x') ?></button>
    </div>
    <div class="pm-body"><?= csrf_field() ?>
      <input type="hidden" name="action" value="save"><input type="hidden" name="id" value="0" data-reset="0">
      <div class="pm-row code-row">
        <label class="pm-f"><span><?= __('كود المادة') ?></span><input name="code" maxlength="30" dir="ltr" placeholder="w18" autocapitalize="none" spellcheck="false" pattern="[A-Za-z0-9_.\-]{1,30}"></label>
        <label class="pm-f"><span><?= __('اسم المادة *') ?></span><input name="name" required maxlength="150" placeholder="<?= e(__('مثال: خشب MDF 18 ملم')) ?>"></label>
      </div>
      <div class="pm-row">
        <label class="pm-f"><span><?= __('سعر الوحدة') ?></span><input name="unit_cost" type="text" inputmode="decimal" data-money value="0"></label>
        <label class="pm-f"><span><?= __('الوحدة') ?></span><input name="unit" list="units" maxlength="30" value="<?= e(__('قطعة')) ?>"></label>
      </div>
      <div class="pm-row">
        <label class="pm-f" data-new-only><span><?= __('الكمية الحالية') ?></span><input name="qty" type="text" inputmode="decimal" data-money data-nocur value="0"></label>
        <label class="pm-f"><span><?= __('الحد الأدنى للتنبيه') ?></span><input name="min_qty" type="text" inputmode="decimal" data-money data-nocur value="0"></label>
      </div>
      <label class="pm-f"><span><?= __('المورد') ?></span><input name="supplier" maxlength="150"></label>
      <label class="pm-f"><span><?= __('ملاحظات') ?></span><textarea name="notes" rows="2" maxlength="2000"></textarea></label>
    </div>
    <div class="pm-foot">
      <button class="pm-save" type="submit" title="<?= e(__('حفظ')) ?>" aria-label="<?= e(__('حفظ')) ?>"><?= icon('check') ?></button>
      <button class="pm-cancel" type="button" data-close title="<?= e(__('إلغاء')) ?>" aria-label="<?= e(__('إلغاء')) ?>"><?= icon('x') ?></button>
    </div>
  </form>
</div>
<?php stock_move_modal(); page_footer('materials');
