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

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

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


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

  if ($action === 'create') require_perm('manage_oases');
  if ($action === 'edit') require_perm('manage_oases');
  if ($action === 'delete') require_perm('manage_oases');

  if (($action==='create') || ($action==='edit' && $id>0)) {
    $data = [
      'code' => trim($_POST['code'] ?? ''),
      'name' => trim($_POST['name'] ?? ''),
      'area' => trim($_POST['area'] ?? ''),
      'lat' => ($_POST['lat'] ?? '') !== '' ? floatval($_POST['lat']) : null,
      'lng' => ($_POST['lng'] ?? '') !== '' ? floatval($_POST['lng']) : null,
      'status' => $_POST['status'] ?? 'active',
      'notes' => trim($_POST['notes'] ?? ''),
      'palm_trees_count' => intval($_POST['palm_trees_count'] ?? 0),
      'falaj_outlets_count' => intval($_POST['falaj_outlets_count'] ?? 0),
    ];

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

    if ($action==='create') {
      $newId = db_insert(
        "INSERT INTO oases (code,name,area,lat,lng,status,notes,palm_trees_count,falaj_outlets_count,created_by,created_at,updated_at)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
        [
          $data['code'],$data['name'],$data['area'],
          $data['lat'],$data['lng'],$data['status'],$data['notes'],$data['palm_trees_count'],$data['falaj_outlets_count'],
          ($_SESSION['uid'] ?? null),
          now_dt(), null
        ]
      );
      audit_log('create','oases',$newId,null,db_one("SELECT * FROM oases WHERE id=?",[$newId]));
      flash_set('ok','تمت إضافة الواحة.');
      redirect(url('/index.php?page=oases'));
    } else {
      $old = oasis_find($id);
      db_exec(
        "UPDATE oases SET code=?, name=?, area=?, lat=?, lng=?, status=?, notes=?, palm_trees_count=?, falaj_outlets_count=?, updated_at=? WHERE id=?",
        [$data['code'],$data['name'],$data['area'],$data['lat'],$data['lng'],$data['status'],$data['notes'],$data['palm_trees_count'],$data['falaj_outlets_count'], now_dt(), $id]
      );
      $new = oasis_find($id);
      audit_log('update','oases',$id,$old,$new);
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=oases'));
    }
  }

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

// List filters
$q = trim($_GET['q'] ?? '');
$st = trim($_GET['status'] ?? '');

$where = [];
$params = [];
if ($q !== '') {
  $where[] = "(code LIKE ? OR name LIKE ? OR area LIKE ?)";
  $params[] = "%$q%"; $params[]="%$q%"; $params[]="%$q%";
}
if ($st !== '' && in_array($st, ['active','inactive','under_maintenance'], true)) {
  $where[] = "status = ?";
  $params[] = $st;
}
$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";

$rows = db_all("SELECT * FROM oases $whereSql ORDER BY id DESC", $params);

// View details
$viewRow = null;
$aflaj = $farms = $assets = $mOpen = [];
if ($action==='view' && $id>0) {
  $tab = $_GET['tab'] ?? 'overview';
  if (!in_array($tab, ['overview','aflaj','farms','assets','maintenance'], true)) { $tab='overview'; }

  $viewRow = oasis_find($id);
  if (!$viewRow) {
    flash_set('error','الواحة غير موجودة.');
    redirect(url('/index.php?page=oases'));
  }
  $aflaj = db_all("SELECT * FROM aflaj WHERE oasis_id=? ORDER BY id DESC", [$id]);
  $farms = db_all("SELECT * FROM farms WHERE oasis_id=? ORDER BY id DESC", [$id]);
  $assets = db_all("SELECT * FROM assets WHERE owner_type='oasis' AND owner_id=? ORDER BY id DESC", [$id]);
  $mOpen = db_all("SELECT mr.*, a.tag asset_tag 
                   FROM maintenance_requests mr
                   JOIN assets a ON a.id=mr.asset_id
                   WHERE mr.status IN ('open','assigned','in_progress')
                     AND (
                        (a.owner_type='oasis' AND a.owner_id=?)
                        OR (a.owner_type='falaj' AND a.owner_id IN (SELECT id FROM aflaj WHERE oasis_id=?))
                        OR (a.owner_type='farm'  AND a.owner_id IN (SELECT id FROM farms WHERE oasis_id=?))
                     )
                   ORDER BY mr.reported_at DESC
                   LIMIT 50", [$id,$id,$id]);
}

?>

<?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">إدارة سجل الواحات وربطها بالأفلاج والمزارع والأصول.</div>
    </div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end">
      <?php if (auth_can('export_oases_xlsx')): ?>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=oases&mode=filtered&'.http_build_query(['q'=>$q,'status'=>$st]))) ?>">تصدير Excel (حسب الفلاتر)</a>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=oases&mode=all')) ?>">تصدير Excel (كل البيانات)</a>
      <?php endif; ?>
      <?php if (auth_can('manage_oases')): ?>
        <a class="btn primary" href="<?= e(url('/index.php?page=oases&action=create')) ?>">إضافة واحة</a>
      <?php endif; ?>
    </div>
  </div>

  <hr>

  <form class="actions" method="get" action="<?= e(url('/index.php')) ?>">
    <input type="hidden" name="page" value="oases">
    <input class="input" style="max-width:320px" name="q" placeholder="بحث بالرمز/الاسم/المنطقة" value="<?= e($q) ?>">
    <select class="input" name="status" style="max-width:200px">
      <option value="">كل الحالات</option>
      <option value="active" <?= $st==='active'?'selected':'' ?>>نشطة</option>
      <option value="inactive" <?= $st==='inactive'?'selected':'' ?>>غير نشطة</option>
      <option value="under_maintenance" <?= $st==='under_maintenance'?'selected':'' ?>>تحت الصيانة</option>
    </select>
    <button class="btn">بحث</button>
    <a class="btn" href="<?= e(url('/index.php?page=oases')) ?>">إعادة ضبط</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['area']) ?></td>
            <td><?= status_tag($r['status']) ?></td>
            <td class="actions">
              <a class="btn" href="<?= e(url('/index.php?page=oases&action=view&id=' . intval($r['id']))) ?>">تفاصيل</a>
<?php if (auth_can('manage_oases')): ?>
                <a class="btn" href="<?= e(url('/index.php?page=oases&action=edit&id='.$r['id'])) ?>">تعديل</a>
                <form method="post" action="<?= e(url('/index.php?page=oases&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="5" class="small">لا توجد بيانات.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<?php if ($action==='create' || ($action==='edit' && $id>0)): ?>
  <?php require_perm('manage_oases'); ?>
  <?php $row = ($action==='edit') ? oasis_find($id) : ['code'=>'','name'=>'','area'=>'','lat'=>'','lng'=>'','status'=>'active','notes'=>'']; ?>
  <h1><?= $action==='create' ? 'إضافة واحة' : 'تعديل واحة' ?></h1>
  <div class="small muted">املأ البيانات ثم احفظ.</div>
  <hr>

  <form method="post">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
    <div class="form-grid">
      <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>
        <input class="input" name="area" value="<?= e((string)$row['area']) ?>">
      </div>
<div>
  <label class="small">عدد أشجار النخيل</label>
  <input class="input" name="palm_trees_count" value="<?= e((string)($row['palm_trees_count'] ?? 0)) ?>" type="number" min="0">
</div>
<div>
  <label class="small">عدد فتحات/مخارج الفلج</label>
  <input class="input" name="falaj_outlets_count" value="<?= e((string)($row['falaj_outlets_count'] ?? 0)) ?>" type="number" min="0">
</div>

      <div>
        <label class="small">الحالة</label>
        <select class="input" name="status">
          <option value="active" <?= (($row['status']??'')==='active')?'selected':'' ?>>نشطة</option>
          <option value="inactive" <?= (($row['status']??'')==='inactive')?'selected':'' ?>>غير نشطة</option>
          <option value="under_maintenance" <?= (($row['status']??'')==='under_maintenance')?'selected':'' ?>>تحت الصيانة</option>
        </select>
      </div>
      <div>
        <label class="small">Latitude</label>
        <input class="input" name="lat" value="<?= e((string)($row['lat'] ?? '')) ?>">
      </div>
      <div>
        <label class="small">Longitude</label>
        <input class="input" name="lng" value="<?= e((string)($row['lng'] ?? '')) ?>">
      </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=oases')) ?>">عودة</a>
    </div>
  </form>
<?php endif; ?>

<?php if ($action==='view' && $viewRow): ?>
  <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap">
    <div>
      <h1><?= e($viewRow['name']) ?> <span class="small muted">(<?= e($viewRow['code']) ?>)</span></h1>
      <div class="small muted"><?= e($viewRow['area'] ?? '') ?> • <?= status_tag($viewRow['status']) ?></div>
    </div>
    <div class="actions">
      <?php if (auth_can('manage_oases')): ?>
        <a class="btn" href="<?= e(url('/index.php?page=oases&action=edit&id='.$viewRow['id'])) ?>">تعديل</a>
      <?php endif; ?>
      <a class="btn" href="<?= e(url('/index.php?page=oases')) ?>">عودة</a>
    </div>
  </div>

  <hr>

<div class="tabs" style="display:flex;gap:8px;flex-wrap:wrap;margin:10px 0">
  <a class="btn <?= ($tab==='overview')?'primary':'' ?>" href="<?= e(url('/index.php?page=oases&action=view&id='.(int)$viewRow['id'].'&tab=overview')) ?>">نظرة عامة</a>
  <a class="btn <?= ($tab==='aflaj')?'primary':'' ?>" href="<?= e(url('/index.php?page=oases&action=view&id='.(int)$viewRow['id'].'&tab=aflaj')) ?>">الأفلاج</a>
  <a class="btn <?= ($tab==='farms')?'primary':'' ?>" href="<?= e(url('/index.php?page=oases&action=view&id='.(int)$viewRow['id'].'&tab=farms')) ?>">المزارع</a>
  <a class="btn <?= ($tab==='assets')?'primary':'' ?>" href="<?= e(url('/index.php?page=oases&action=view&id='.(int)$viewRow['id'].'&tab=assets')) ?>">الأصول</a>
  <a class="btn <?= ($tab==='maintenance')?'primary':'' ?>" href="<?= e(url('/index.php?page=oases&action=view&id='.(int)$viewRow['id'].'&tab=maintenance')) ?>">الصيانة</a>
</div>

  <hr>

  <?php if ($tab==='overview'): ?>
  <div class="grid-5">
    <div class="kpi"><div class="num"><?= e((string)count($aflaj)) ?></div><div class="lbl">أفلاج</div></div>
    <div class="kpi"><div class="num"><?= e((string)count($farms)) ?></div><div class="lbl">مزارع</div></div>
    
    <div class="kpi"><div class="num"><?= e((string)($viewRow['palm_trees_count'] ?? 0)) ?></div><div class="lbl">أشجار نخيل</div></div>
    <div class="kpi"><div class="num"><?= e((string)($viewRow['falaj_outlets_count'] ?? 0)) ?></div><div class="lbl">مخارج فلج</div></div>
    <div class="kpi"><div class="num"><?= e((string)count($assets)) ?></div><div class="lbl">أصول</div></div>
<div class="kpi"><div class="num"><?= e((string)count($mOpen)) ?></div><div class="lbl">بلاغات مفتوحة/قيد التنفيذ</div></div>
  </div>
  <?php endif; ?>

  <hr>

  <div class="grid-2">
    <?php if ($tab==='overview' || $tab==='aflaj'): ?>
    <div class="card">
      <h2>الأفلاج</h2>
      <div class="small muted">مرتبطة بهذه الواحة.</div>
      <div style="margin-top:10px;overflow:auto">
        <table class="table">
          <thead><tr><th>الرمز</th><th>الاسم</th><th>النوع</th><th>الحالة</th></tr></thead>
          <tbody>
            <?php foreach ($aflaj as $r): ?>
              <tr>
                <td><?= e($r['code']) ?></td>
                <td><?= e($r['name']) ?></td>
                <td class="small"><?= e($r['type']) ?></td>
                <td><?= status_tag($r['status']) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$aflaj): ?><tr><td colspan="4" class="small">لا يوجد.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="actions" style="margin-top:10px">
        <a class="btn" href="<?= e(url('/index.php?page=aflaj&oasis_id='.$viewRow['id'])) ?>">فتح صفحة الأفلاج مع فلتر الواحة</a>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($tab==='overview' || $tab==='farms'): ?>
    <div class="card">
      <h2>المزارع</h2>
      <div class="small muted">مرتبطة بهذه الواحة.</div>
      <div style="margin-top:10px;overflow:auto">
        <table class="table">
          <thead><tr><th>الرمز</th><th>المالك</th><th>هاتف</th><th>هوية</th><th>المساحة</th><th>الحالة</th></tr></thead>
          <tbody>
            <?php foreach ($farms as $r): ?>
              <tr>
                <td><?= e($r['code']) ?></td>
                <td><?= e($r['owner_name']) ?></td>
                <td class="small"><?= e((string)($r['owner_phone'] ?? '-')) ?></td>
                <td class="small"><?= e((string)($r['owner_emirates_id'] ?? '-')) ?></td>
                <td class="small"><?= e((string)($r['area_m2'] ?? '-')) ?></td>
                <td><?= status_tag($r['status']) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$farms): ?><tr><td colspan="6" class="small">لا يوجد.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="actions" style="margin-top:10px">
        <a class="btn" href="<?= e(url('/index.php?page=farms&oasis_id='.$viewRow['id'])) ?>">فتح صفحة المزارع مع فلتر الواحة</a>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <hr>

  <div class="grid-2">
    <div class="card">
      <h2>الأصول المرتبطة مباشرة بالواحة</h2>
      <div class="small muted">أصول owner_type=oasis.</div>
      <div style="margin-top:10px;overflow:auto">
        <table class="table">
          <thead><tr><th>الملصق</th><th>الفئة</th><th>الحالة</th></tr></thead>
          <tbody>
            <?php foreach ($assets as $a): ?>
              <tr>
                <td><?= e($a['tag']) ?></td>
                <td><?= e($a['category']) ?></td>
                <td><?= status_tag($a['status']) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$assets): ?><tr><td colspan="3" class="small">لا يوجد.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="actions" style="margin-top:10px">
        <a class="btn" href="<?= e(url('/index.php?page=assets&owner_type=oasis&owner_id='.$viewRow['id'])) ?>">فتح صفحة الأصول مع فلتر الواحة</a>
      </div>
    </div>

    <div class="card">
      <h2>بلاغات صيانة مفتوحة/قيد التنفيذ</h2>
      <div class="small muted">ضمن الواحة (واحة/أفلاجها/مزارعها).</div>
      <div style="margin-top:10px;overflow:auto">
        <table class="table">
          <thead><tr><th>#</th><th>العنوان</th><th>الأصل</th><th>الحالة</th><th>البلاغ</th></tr></thead>
          <tbody>
            <?php foreach ($mOpen as $r): ?>
              <tr>
                <td><?= e((string)$r['id']) ?></td>
                <td><?= e($r['title']) ?></td>
                <td class="small"><?= e($r['asset_tag']) ?></td>
                <td><?= status_tag($r['status']) ?></td>
                <td class="small"><?= e((string)$r['reported_at']) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$mOpen): ?><tr><td colspan="5" class="small">لا يوجد.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="actions" style="margin-top:10px">
        <a class="btn" href="<?= e(url('/index.php?page=maintenance&oasis_id='.$viewRow['id'])) ?>">فتح صفحة الصيانة مع فلتر الواحة</a>
      </div>
    </div>
  </div>
<?php endif; ?>
