<?php
require __DIR__ . '/_common.php';
require_perm('view_aflaj');

$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

if (!function_exists('falaj_find')) {
function falaj_find(int $id): ?array {
  return db_one("SELECT * FROM aflaj WHERE id=?", [$id]);
}
}


if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();
  if (in_array($action, ['create','edit','delete'], true)) require_perm('manage_aflaj');

  if ($action==='create' || ($action==='edit' && $id>0)) {
    $data = [
      'oasis_id' => intval($_POST['oasis_id'] ?? 0),
      'code' => trim($_POST['code'] ?? ''),
      'name' => trim($_POST['name'] ?? ''),
      'type' => $_POST['type'] ?? 'surface',
      'length_m' => ($_POST['length_m'] ?? '') !== '' ? floatval($_POST['length_m']) : null,
      'status' => $_POST['status'] ?? 'operational',
      'notes' => trim($_POST['notes'] ?? ''),
    ];

    if ($data['oasis_id']<=0 || $data['code']==='' || $data['name']==='') {
      flash_set('error','الواحة/الرمز/الاسم مطلوبة.');
      redirect(url('/index.php?page=aflaj&action='.$action.($id?('&id='.$id):'')));
    }

    if ($action==='create') {
      $newId = db_insert(
        "INSERT INTO aflaj (oasis_id,code,name,type,length_m,status,notes,created_at,updated_at)
         VALUES (?,?,?,?,?,?,?,?,?)",
        [$data['oasis_id'],$data['code'],$data['name'],$data['type'],$data['length_m'],$data['status'],$data['notes'], now_dt(), null]
      );
      audit_log('create','aflaj',$newId,null,db_one("SELECT * FROM aflaj WHERE id=?",[$newId]));
      flash_set('ok','تمت إضافة الفلج.');
      redirect(url('/index.php?page=aflaj'));
    } else {
      $old = falaj_find($id);
      db_exec("UPDATE aflaj SET oasis_id=?, code=?, name=?, type=?, length_m=?, status=?, notes=?, updated_at=? WHERE id=?",
        [$data['oasis_id'],$data['code'],$data['name'],$data['type'],$data['length_m'],$data['status'],$data['notes'], now_dt(), $id]
      );
      $new = falaj_find($id);
      audit_log('update','aflaj',$id,$old,$new);
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=aflaj'));
    }
  }

  if ($action==='delete' && $id>0) {
    $old = falaj_find($id);
    db_exec("DELETE FROM aflaj WHERE id=?", [$id]);
    audit_log('delete','aflaj',$id,$old,null);
    flash_set('ok','تم حذف الفلج.');
    redirect(url('/index.php?page=aflaj'));
  }
}

// Filters
$q = trim($_GET['q'] ?? '');
$st = trim($_GET['status'] ?? '');
$oasis_id = intval($_GET['oasis_id'] ?? 0);

$where=[]; $params=[];
if ($q!=='') { $where[]="(code LIKE ? OR name LIKE ?)"; $params[]="%$q%"; $params[]="%$q%"; }
if ($st!=='' && in_array($st,['operational','partial','stopped','under_maintenance'],true)) { $where[]="status=?"; $params[]=$st; }
if ($oasis_id>0) { $where[]="oasis_id=?"; $params[]=$oasis_id; }

$whereSql=$where?("WHERE ".implode(" AND ",$where)):"";
$rows=db_all("SELECT a.*, o.name oasis_name, o.code oasis_code
             FROM aflaj a JOIN oases o ON o.id=a.oasis_id
             $whereSql
             ORDER BY a.id DESC", $params);

$oases=db_all("SELECT id,name,code FROM oases ORDER BY name ASC");
?>

<?php if ($action==='list'): ?>
  <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap">
    <div>
      <h1>الأفلاج</h1>
      <div class="small muted">إدارة الأفلاج وربطها بالواحات.</div>
    </div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end">
      <?php if (auth_can('export_aflaj_xlsx')): ?>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=aflaj&mode=filtered&'.http_build_query(['q'=>$q,'status'=>$st,'oasis_id'=>$oasis_id]))) ?>">تصدير Excel (حسب الفلاتر)</a>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=aflaj&mode=all')) ?>">تصدير Excel (كل البيانات)</a>
      <?php endif; ?>
      <?php if (auth_can('manage_aflaj')): ?>
        <a class="btn primary" href="<?= e(url('/index.php?page=aflaj&action=create')) ?>">إضافة فلج</a>
      <?php endif; ?>
    </div>
  </div>

  <hr>

  <form class="actions" method="get" action="<?= e(url('/index.php')) ?>">
    <input type="hidden" name="page" value="aflaj">
    <input class="input" style="max-width:280px" name="q" placeholder="بحث بالرمز/الاسم" value="<?= e($q) ?>">
    <select class="input" name="oasis_id" style="max-width:260px">
      <option value="0">كل الواحات</option>
      <?php foreach ($oases as $o): ?>
        <option value="<?= e((string)$o['id']) ?>" <?= $oasis_id==intval($o['id'])?'selected':'' ?>>
          <?= e($o['name']) ?> (<?= e($o['code']) ?>)
        </option>
      <?php endforeach; ?>
    </select>
    <select class="input" name="status" style="max-width:190px">
      <option value="">كل الحالات</option>
      <?php foreach (['operational'=>'تشغيلي','partial'=>'جزئي','stopped'=>'متوقف','under_maintenance'=>'تحت الصيانة'] as $k=>$v): ?>
        <option value="<?= e($k) ?>" <?= $st===$k?'selected':'' ?>><?= e($v) ?></option>
      <?php endforeach; ?>
    </select>
    <button class="btn">بحث</button>
    <a class="btn" href="<?= e(url('/index.php?page=aflaj')) ?>">إعادة ضبط</a>
  </form>

  <div style="margin-top:10px;overflow:auto">
    <table class="table">
      <thead><tr><th>الرمز</th><th>الاسم</th><th>الواحة</th><th>النوع</th><th>الطول</th><th>الحالة</th><th>إجراءات</th></tr></thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?= e($r['code']) ?></td>
            <td><?= e($r['name']) ?></td>
            <td class="small"><?= e($r['oasis_name']) ?> (<?= e($r['oasis_code']) ?>)</td>
            <td class="small"><?= e($r['type']) ?></td>
            <td class="small"><?= e((string)($r['length_m'] ?? '-')) ?></td>
            <td><?= status_tag($r['status']) ?></td>
            <td class="actions">
              <?php if (auth_can('manage_aflaj')): ?>
                <a class="btn" href="<?= e(url('/index.php?page=aflaj&action=edit&id='.$r['id'])) ?>">تعديل</a>
                <form method="post" action="<?= e(url('/index.php?page=aflaj&action=delete&id='.$r['id'])) ?>" onsubmit="return confirm('حذف الفلج؟')">
                  <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                  <button class="btn danger">حذف</button>
                </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?><tr><td colspan="7" class="small">لا توجد بيانات.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<?php if ($action==='create' || ($action==='edit' && $id>0)): ?>
  <?php require_perm('manage_aflaj'); ?>
  <?php $row = ($action==='edit') ? falaj_find($id) : ['oasis_id'=>intval($_GET['oasis_id'] ?? 0),'code'=>'','name'=>'','type'=>'surface','length_m'=>'','status'=>'operational','notes'=>'']; ?>
  <h1><?= $action==='create'?'إضافة فلج':'تعديل فلج' ?></h1>
  <hr>
  <form method="post">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
    <div class="form-grid">
      <div>
        <label class="small">الواحة</label>
        <select class="input" name="oasis_id" required>
          <option value="">اختر...</option>
          <?php foreach ($oases as $o): ?>
            <option value="<?= e((string)$o['id']) ?>" <?= intval($row['oasis_id'] ?? 0)==intval($o['id'])?'selected':'' ?>>
              <?= e($o['name']) ?> (<?= e($o['code']) ?>)
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="small">الرمز</label>
        <input class="input" name="code" value="<?= e((string)$row['code']) ?>" required>
      </div>
      <div>
        <label class="small">الاسم</label>
        <input class="input" name="name" value="<?= e((string)$row['name']) ?>" required>
      </div>
      <div>
        <label class="small">النوع</label>
        <select class="input" name="type">
          <?php foreach (['surface'=>'سطحي','underground'=>'جوفي','mixed'=>'مختلط'] as $k=>$v): ?>
            <option value="<?= e($k) ?>" <?= (($row['type']??'')===$k)?'selected':'' ?>><?= e($v) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="small">الطول (م)</label>
        <input class="input" name="length_m" value="<?= e((string)($row['length_m'] ?? '')) ?>">
      </div>
      <div>
        <label class="small">الحالة</label>
        <select class="input" name="status">
          <?php foreach (['operational'=>'تشغيلي','partial'=>'جزئي','stopped'=>'متوقف','under_maintenance'=>'تحت الصيانة'] as $k=>$v): ?>
            <option value="<?= e($k) ?>" <?= (($row['status']??'')===$k)?'selected':'' ?>><?= e($v) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div style="grid-column:1/-1">
        <label class="small">ملاحظات</label>
        <textarea class="input" name="notes" rows="4"><?= e((string)($row['notes'] ?? '')) ?></textarea>
      </div>
    </div>
    <div class="actions" style="margin-top:12px">
      <button class="btn primary">حفظ</button>
      <a class="btn" href="<?= e(url('/index.php?page=aflaj')) ?>">عودة</a>
    </div>
  </form>
<?php endif; ?>
