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

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

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

if (!function_exists('valid_emirates_id')) {
function valid_emirates_id(?string $s): bool {
  if ($s===null) return true;
  $s = trim($s);
  if ($s==='') return true;
  return (bool)preg_match('/^[0-9]{15}$/', $s);
}
}

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


  // Handle delete BEFORE validating create/edit fields (delete posts only id + csrf)
  $delAction = ($action==='delete' || $action==='del' || $action==='remove');
  if ($delAction) {
    $did = intval($_POST['id'] ?? ($id ?? 0));
    if ($did>0) {
      $old = farm_find($did);
      db_exec("DELETE FROM farms WHERE id=?", [$did]);
      audit_log('delete','farm',$did,$old,null);
      flash_set('ok','تم حذف المزرعة.');
    }
    redirect(url('/index.php?page=farms'));
  }

  $data = [
    'oasis_id' => intval($_POST['oasis_id'] ?? 0),
    'code' => trim($_POST['code'] ?? ''),
    'owner_name' => trim($_POST['owner_name'] ?? ''),
    'owner_phone' => trim($_POST['owner_phone'] ?? ''),
    'owner_emirates_id' => trim($_POST['owner_emirates_id'] ?? ''),
    'area_m2' => trim($_POST['area_m2'] ?? ''),
    'lat' => trim($_POST['lat'] ?? ''),
    'lng' => trim($_POST['lng'] ?? ''),
    'status' => trim($_POST['status'] ?? 'active'),
    'notes' => trim($_POST['notes'] ?? ''),
  ];

  if ($data['oasis_id']<=0 || $data['code']==='') {
    flash_set('error','الرجاء تحديد الواحة وإدخال رمز المزرعة.');
    redirect(url('/index.php?page=farms&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }

  if (!in_array($data['status'], ['active','inactive','blocked'], true)) $data['status']='active';
  if (!valid_emirates_id($data['owner_emirates_id'] !== '' ? $data['owner_emirates_id'] : null)) {
    flash_set('error','هوية إماراتية يجب أن تكون 15 رقم.');
    redirect(url('/index.php?page=farms&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }

  // إحداثيات الموقع (اختيارية)
  $lat = $data['lat']!=='' ? (float)$data['lat'] : null;
  $lng = $data['lng']!=='' ? (float)$data['lng'] : null;
  if ($lat !== null && ($lat < -90 || $lat > 90)) {
    flash_set('error','خط العرض Latitude يجب أن يكون بين -90 و 90.');
    redirect(url('/index.php?page=farms&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }
  if ($lng !== null && ($lng < -180 || $lng > 180)) {
    flash_set('error','خط الطول Longitude يجب أن يكون بين -180 و 180.');
    redirect(url('/index.php?page=farms&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }


  $area = $data['area_m2']!=='' ? $data['area_m2'] : null;
  $eid = $data['owner_emirates_id']!=='' ? $data['owner_emirates_id'] : null;
  $phone = $data['owner_phone']!=='' ? $data['owner_phone'] : null;
  $owner = $data['owner_name']!=='' ? $data['owner_name'] : null;

  if ($action==='create') {
    $newId = db_insert(
      "INSERT INTO farms (oasis_id,code,owner_name,owner_phone,owner_emirates_id,area_m2,lat,lng,status,notes,created_at,updated_at)
       VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
      [$data['oasis_id'],$data['code'],$owner,$phone,$eid,$area,$lat,$lng,$data['status'],$data['notes'], now_dt(), null]
    );
    audit_log('create','farms',$newId,null,farm_find($newId));
    flash_set('ok','تمت إضافة المزرعة.');
    if (isset($_POST['open_attachments'])) {
      redirect(url('/index.php?page=farms&action=edit&id='.$newId.'#attachments'));
    }
    redirect(url('/index.php?page=farms'));
  }

  if ($action==='edit' && $id>0) {
    $old = farm_find($id);
    db_exec(
      "UPDATE farms SET oasis_id=?,code=?,owner_name=?,owner_phone=?,owner_emirates_id=?,area_m2=?,lat=?,lng=?,status=?,notes=?,updated_at=? WHERE id=?",
      [$data['oasis_id'],$data['code'],$owner,$phone,$eid,$area,$lat,$lng,$data['status'],$data['notes'], now_dt(), $id]
    );
    audit_log('update','farms',$id,$old,farm_find($id));
    flash_set('ok','تم حفظ التعديلات.');
    redirect(url('/index.php?page=farms&action=edit&id='.$id.'#attachments'));
  }

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

  redirect(url('/index.php?page=farms'));
}

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

$where=[]; $params=[];
if ($q!=='') { $where[]="(code LIKE ? OR owner_name LIKE ?)"; $params[]="%$q%"; $params[]="%$q%"; }
if ($st!=='' && in_array($st,['active','inactive','blocked'],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 f.*, o.name oasis_name, o.code oasis_code
             FROM farms f JOIN oases o ON o.id=f.oasis_id
             $whereSql
             ORDER BY f.id DESC LIMIT 800", $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_farms_xlsx')): ?>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=farms&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=farms&mode=all')) ?>">تصدير Excel (كل البيانات)</a>
      <?php endif; ?>
      <?php if (auth_can('manage_farms')): ?>
        <a class="btn primary" href="<?= e(url('/index.php?page=farms&action=create')) ?>">إضافة مزرعة</a>
      <?php endif; ?>
    </div>
  </div>

  <hr>

  <form class="actions" method="get" action="<?= e(url('/index.php')) ?>">
    <input type="hidden" name="page" value="farms">
    <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:200px">
      <option value="">كل الحالات</option>
      <option value="active" <?= $st==='active'?'selected':'' ?>>نشطة</option>
      <option value="inactive" <?= $st==='inactive'?'selected':'' ?>>غير نشطة</option>
      <option value="blocked" <?= $st==='blocked'?'selected':'' ?>>محجوبة</option>
    </select>
    <button class="btn">بحث</button>
    <a class="btn" href="<?= e(url('/index.php?page=farms')) ?>">إعادة ضبط</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><th>إجراءات</th></tr></thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?= e($r['code']) ?></td>
            <td><?= e((string)($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($r['oasis_name']) ?> (<?= e($r['oasis_code']) ?>)</td>
            <td class="small"><?= e((string)($r['area_m2'] ?? '-')) ?></td>
            <td><?= status_tag($r['status']) ?></td>
            <td class="actions">
              <?php if (auth_can('manage_farms')): ?>
                <a class="btn" href="<?= e(url('/index.php?page=farms&action=edit&id='.$r['id'])) ?>">تعديل</a>
                <form method="post" action="<?= e(url('/index.php?page=farms&action=delete&id='.$r['id'])) ?>" onsubmit="return confirm('حذف المزرعة؟')">
                  <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                  <input type="hidden" name="id" value="<?= e((string)$r['id']) ?>">
                  <button class="btn danger">حذف</button>
                </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?><tr><td colspan="8" class="small">لا توجد بيانات.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<?php if ($action==='create' || ($action==='edit' && $id>0)): ?>
  <?php require_perm('manage_farms'); ?>
  <?php
    $row = ($action==='edit') ? farm_find($id) : [
      'oasis_id'=>intval($_GET['oasis_id'] ?? 0),
      'code'=>'','owner_name'=>'','owner_phone'=>'','owner_emirates_id'=>'',
      'area_m2'=>'','status'=>'active','notes'=>''
    ];
  ?>
  <h1><?= $action==='create'?'إضافة مزرعة':'تعديل مزرعة' ?></h1>
  <div class="card">
    <form method="post">
      <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

      <div class="grid cols-2">
        <div>
          <label class="label">الواحة</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="label">رمز المزرعة</label>
          <input class="input" name="code" required value="<?= e((string)($row['code'] ?? '')) ?>">
        </div>

        <div>
          <label class="label">اسم المالك</label>
          <input class="input" name="owner_name" value="<?= e((string)($row['owner_name'] ?? '')) ?>">
        </div>
        <div>
          <label class="label">هاتف المالك</label>
          <input class="input" name="owner_phone" value="<?= e((string)($row['owner_phone'] ?? '')) ?>">
        </div>

        <div>
          <label class="label">هوية إماراتية (15 رقم)</label>
          <input class="input" name="owner_emirates_id" maxlength="15" value="<?= e((string)($row['owner_emirates_id'] ?? '')) ?>" placeholder="مثال: 784xxxxxxxxxxxx">
        </div>
        <div>
          <label class="label">المساحة (م²)</label>
          <input class="input" name="area_m2" value="<?= e((string)($row['area_m2'] ?? '')) ?>">
        </div>
        <div>
          <label class="label">خط العرض Latitude</label>
          <input class="input" name="lat" value="<?= e((string)($row['lat'] ?? '')) ?>" placeholder="مثال: 24.2075">
        </div>
        <div>
          <label class="label">خط الطول Longitude</label>
          <input class="input" name="lng" value="<?= e((string)($row['lng'] ?? '')) ?>" placeholder="مثال: 55.7441">
        </div>


        <div>
          <label class="label">الحالة</label>
          <select class="input" name="status">
            <option value="active" <?= ((string)($row['status']??''))==='active'?'selected':'' ?>>نشطة</option>
            <option value="inactive" <?= ((string)($row['status']??''))==='inactive'?'selected':'' ?>>غير نشطة</option>
            <option value="blocked" <?= ((string)($row['status']??''))==='blocked'?'selected':'' ?>>محجوبة</option>
          </select>
        </div>

        <div class="grid-span-2">
          <label class="label">ملاحظات</label>
          <textarea class="input" name="notes" rows="3"><?= e((string)($row['notes'] ?? '')) ?></textarea>
        </div>
      </div>

      <div class="actions" style="margin-top:12px">
        <button class="btn primary">حفظ</button>
        <?php if ($action==='create'): ?>
          <button class="btn" name="open_attachments" value="1">حفظ وفتح المرفقات</button>
        <?php endif; ?>
        <a class="btn" href="<?= e(url('/index.php?page=farms')) ?>">عودة</a>
      </div>
    </form>
  </div>

  <?php if ($action==='edit' && $id>0): ?>
    <?php $attRows = db_all("SELECT * FROM attachments WHERE owner_type=? AND owner_id=? ORDER BY id DESC", ['farm', $id]); ?>
    <div id="attachments" class="card" style="margin-top:14px">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap">
        <h3 style="margin:0">المرفقات</h3>
        <div class="small">PDF / صور — بحد أقصى 10MB</div>
      </div>

      <?php if (auth_can('manage_farms')): ?>
        <form method="post" enctype="multipart/form-data"
              action="<?= e(url('/index.php?page=attachments&action=upload&owner_type=farm&owner_id=' . $id)) ?>"
              style="margin-top:10px;display:flex;gap:10px;flex-wrap:wrap;align-items:center">
          <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="back" value="<?= e(url('/index.php?page=farms&action=edit&id=' . $id . '#attachments')) ?>">
          <input class="input" type="file" name="file" accept=".pdf,.jpg,.jpeg,.png,.webp" required style="max-width:420px">
          <button class="btn">رفع مرفق</button>
        </form>
      <?php endif; ?>

      <div style="margin-top:12px;overflow:auto">
        <table class="table">
          <thead><tr><th>الملف</th><th>النوع</th><th>الحجم</th><th>تاريخ الرفع</th><th>إجراءات</th></tr></thead>
          <tbody>
            <?php foreach ($attRows as $a): ?>
              <tr>
                <td class="small"><?= e($a['original_name']) ?></td>
                <td class="small"><?= e($a['mime']) ?></td>
                <td class="small"><?= e(round(intval($a['size_bytes'])/1024,1)) ?> KB</td>
                <td class="small"><?= e($a['created_at']) ?></td>
                <td class="actions">
                  <a class="btn" href="<?= e(url('/download.php?id=' . $a['id'])) ?>">تنزيل</a>
                  <?php if (auth_can('manage_farms')): ?>
                    <form method="post" action="<?= e(url('/index.php?page=attachments&action=delete&owner_type=farm&owner_id=' . $id)) ?>" onsubmit="return confirm('حذف المرفق؟')">
                      <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                      <input type="hidden" name="back" value="<?= e(url('/index.php?page=farms&action=edit&id=' . $id . '#attachments')) ?>">
                      <input type="hidden" name="id" value="<?= e($a['id']) ?>">
                      <button class="btn danger">حذف</button>
                    </form>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$attRows): ?><tr><td colspan="5" class="small">لا توجد مرفقات.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>
<?php endif; ?>