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

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

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

if (!function_exists('owner_options')) {
  function owner_options(string $type, int $oasisFilterId=0): array {
    if ($type === 'oasis') {
      return db_all("SELECT id, name, code FROM oases ORDER BY name ASC");
    }
    if ($type === 'falaj') {
      if ($oasisFilterId>0) return db_all("SELECT id, name, code FROM afalaj WHERE oasis_id=? ORDER BY name ASC", [$oasisFilterId]);
      return db_all("SELECT id, name, code FROM afalaj ORDER BY name ASC");
    }
    // farm
    if ($oasisFilterId>0) return db_all("SELECT f.id, f.code, f.owner_name, o.name oasis_name, o.code oasis_code
                                        FROM farms f JOIN oases o ON o.id=f.oasis_id
                                        WHERE f.oasis_id=? ORDER BY f.code ASC", [$oasisFilterId]);
    return db_all("SELECT f.id, f.code, f.owner_name, o.name oasis_name, o.code oasis_code
                   FROM farms f JOIN oases o ON o.id=f.oasis_id
                   ORDER BY f.code ASC");
  }
}

if (!function_exists('asset_owner_label')) {
function asset_owner_label(array $r): string {
  $t = (string)($r['owner_type'] ?? '');
  $oid = intval($r['owner_id'] ?? 0);
  if ($t==='oasis') {
    $o = db_one("SELECT name, code FROM oases WHERE id=?", [$oid]);
    return $o ? ($o['name'].' ('.$o['code'].')') : 'واحة #'.$oid;
  }
  if ($t==='falaj') {
    $f = db_one("SELECT name, code FROM afalaj WHERE id=?", [$oid]);
    return $f ? ($f['name'].' ('.$f['code'].')') : 'فلج #'.$oid;
  }
  if ($t==='farm') {
    $f = db_one("SELECT code, owner_name FROM farms WHERE id=?", [$oid]);
    return $f ? ($f['code'].' - '.($f['owner_name'] ?? '')) : 'مزرعة #'.$oid;
  }
  return $t.' #'.$oid;
}
}

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


  // 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 = asset_find($did);
      db_exec("DELETE FROM assets WHERE id=?", [$did]);
      audit_log('delete','assets',$did,$old,null);
      flash_set('ok','تم حذف الأصل.');
    }
    redirect(url('/index.php?page=assets'));
  }

  $data = [
    'tag' => trim($_POST['tag'] ?? ''),
    'category' => trim($_POST['category'] ?? ''),
    'owner_type' => trim($_POST['owner_type'] ?? 'oasis'),
    'owner_id' => intval($_POST['owner_id'] ?? 0),
    'status' => trim($_POST['status'] ?? 'ok'),
    'serial_number' => trim($_POST['serial_number'] ?? ''),
    'installed_at' => trim($_POST['installed_at'] ?? ''),
    'lat' => trim($_POST['lat'] ?? ''),
    'lng' => trim($_POST['lng'] ?? ''),
    'notes' => trim($_POST['notes'] ?? ''),
  ];

  if ($data['tag']==='' || $data['category']==='' || $data['owner_id']<=0) {
    flash_set('error','الرجاء تعبئة الحقول الأساسية (الملصق/الفئة/الجهة).');
    redirect(url('/index.php?page=assets&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }

  if (!in_array($data['owner_type'], ['oasis','falaj','farm'], true)) $data['owner_type']='oasis';
  if (!in_array($data['status'], ['ok','needs_service','out_of_order'], true)) $data['status']='ok';

  // إحداثيات الموقع (اختيارية)
  $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=assets&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }
  if ($lng !== null && ($lng < -180 || $lng > 180)) {
    flash_set('error','خط الطول Longitude يجب أن يكون بين -180 و 180.');
    redirect(url('/index.php?page=assets&action=' . $action . ($id>0 ? '&id='.$id : '')));
  }


  $installed = $data['installed_at']!=='' ? $data['installed_at'] : null;
  $serial = $data['serial_number']!=='' ? $data['serial_number'] : null;

  if ($action==='create') {
    $newId = db_insert(
      "INSERT INTO assets (tag,category,owner_type,owner_id,status,serial_number,installed_at,lat,lng,notes,created_at,updated_at)
       VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
      [$data['tag'],$data['category'],$data['owner_type'],$data['owner_id'],$data['status'],$serial,$installed,$lat,$lng,$data['notes'], now_dt(), null]
    );
    audit_log('create','assets',$newId,null,asset_find($newId));
    flash_set('ok','تمت إضافة الأصل.');
    if (isset($_POST['open_attachments'])) {
      redirect(url('/index.php?page=assets&action=edit&id='.$newId.'#attachments'));
    }
    redirect(url('/index.php?page=assets'));
  }

  if ($action==='edit' && $id>0) {
    $old = asset_find($id);
    db_exec(
      "UPDATE assets SET tag=?,category=?,owner_type=?,owner_id=?,status=?,serial_number=?,installed_at=?,lat=?,lng=?,notes=?,updated_at=? WHERE id=?",
      [$data['tag'],$data['category'],$data['owner_type'],$data['owner_id'],$data['status'],$serial,$installed,$lat,$lng,$data['notes'], now_dt(), $id]
    );
    audit_log('update','assets',$id,$old,asset_find($id));
    flash_set('ok','تم حفظ التعديلات.');
    redirect(url('/index.php?page=assets&action=edit&id='.$id.'#attachments'));
  }

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

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

// LIST data + filters
$q = trim($_GET['q'] ?? '');
$st = trim($_GET['status'] ?? '');
$owner_type = trim($_GET['owner_type'] ?? '');
$owner_id = intval($_GET['owner_id'] ?? 0);

$where=[]; $params=[];
if ($q!=='') {
  $where[]="(tag LIKE ? OR category LIKE ? OR serial_number LIKE ?)";
  $params[]="%$q%"; $params[]="%$q%"; $params[]="%$q%";
}
if ($st!=='' && in_array($st,['ok','needs_service','out_of_order'],true)) { $where[]="status=?"; $params[]=$st; }
if ($owner_type!=='' && in_array($owner_type,['oasis','falaj','farm'],true)) { $where[]="owner_type=?"; $params[]=$owner_type; }
if ($owner_id>0) { $where[]="owner_id=?"; $params[]=$owner_id; }

$whereSql = $where ? ("WHERE ".implode(" AND ",$where)) : "";
$rows = db_all("SELECT * FROM assets $whereSql ORDER BY id DESC LIMIT 800", $params);
?>
<?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_assets_xlsx')): ?>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=assets&mode=filtered&'.http_build_query(['q'=>$q,'status'=>$st,'owner_type'=>$owner_type,'owner_id'=>$owner_id]))) ?>">تصدير Excel (حسب الفلاتر)</a>
        <a class="btn" href="<?= e(url('/index.php?page=export_xlsx&entity=assets&mode=all')) ?>">تصدير Excel (كل البيانات)</a>
      <?php endif; ?>
      <?php if (auth_can('manage_assets')): ?>
        <a class="btn primary" href="<?= e(url('/index.php?page=assets&action=create')) ?>">إضافة أصل</a>
      <?php endif; ?>
    </div>
  </div>

  <hr>

  <form class="actions" method="get" action="<?= e(url('/index.php')) ?>">
    <input type="hidden" name="page" value="assets">
    <input class="input" style="max-width:320px" name="q" placeholder="بحث: ملصق/فئة/Serial" value="<?= e($q) ?>">
    <select class="input" name="owner_type" style="max-width:180px">
      <option value="">كل الجهات</option>
      <option value="oasis" <?= $owner_type==='oasis'?'selected':'' ?>>واحة</option>
      <option value="falaj" <?= $owner_type==='falaj'?'selected':'' ?>>فلج</option>
      <option value="farm" <?= $owner_type==='farm'?'selected':'' ?>>مزرعة</option>
    </select>
    <input class="input" style="max-width:140px" name="owner_id" placeholder="Owner ID" value="<?= $owner_id>0?e((string)$owner_id):'' ?>">
    <select class="input" name="status" style="max-width:190px">
      <option value="">كل الحالات</option>
      <option value="ok" <?= $st==='ok'?'selected':'' ?>>سليم</option>
      <option value="needs_service" <?= $st==='needs_service'?'selected':'' ?>>بحاجة صيانة</option>
      <option value="out_of_order" <?= $st==='out_of_order'?'selected':'' ?>>متعطل</option>
    </select>
    <button class="btn">بحث</button>
    <a class="btn" href="<?= e(url('/index.php?page=assets')) ?>">إعادة ضبط</a>
  </form>

  <div style="margin-top:10px;overflow:auto">
    <table class="table">
      <thead><tr>
        <th>Tag</th><th>التصنيف</th><th>الجهة</th><th>الحالة</th><th>Serial</th><th>تاريخ التركيب</th><th>ملاحظات</th><th>إجراءات</th>
      </tr></thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?= e($r['tag']) ?></td>
            <td class="small"><?= e($r['category']) ?></td>
            <td class="small"><?= e(asset_owner_label($r)) ?></td>
            <td><?= status_tag($r['status']) ?></td>
            <td class="small"><?= e((string)($r['serial_number'] ?? '-')) ?></td>
            <td class="small"><?= e((string)($r['installed_at'] ?? '-')) ?></td>
            <td class="small"><?= e(mb_strimwidth((string)($r['notes'] ?? ''),0,70,'…','UTF-8')) ?></td>
            <td class="actions">
              <?php if (auth_can('manage_assets')): ?>
                <a class="btn" href="<?= e(url('/index.php?page=assets&action=edit&id='.$r['id'])) ?>">تعديل</a>
                <form method="post" action="<?= e(url('/index.php?page=assets&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_assets'); ?>
  <?php
    $row = ($action==='edit') ? asset_find($id) : [
      'tag'=>'','category'=>'',
      'owner_type'=>($_GET['owner_type'] ?? 'oasis'),
      'owner_id'=>intval($_GET['owner_id'] ?? 0),
      'status'=>'ok','serial_number'=>'','installed_at'=>'','notes'=>''
    ];
    $ownerOpts = owner_options((string)($row['owner_type'] ?? 'oasis'));
  ?>
  <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">Tag (ملصق)</label>
          <input class="input" name="tag" required value="<?= e((string)($row['tag'] ?? '')) ?>">
        </div>
        <div>
          <label class="label">التصنيف</label>
          <input class="input" name="category" required value="<?= e((string)($row['category'] ?? '')) ?>">
        </div>

        <div>
          <label class="label">نوع الجهة</label>
          <select class="input" name="owner_type" onchange="this.form.submit()">
            <option value="oasis" <?= ((string)($row['owner_type']??''))==='oasis'?'selected':'' ?>>واحة</option>
            <option value="falaj" <?= ((string)($row['owner_type']??''))==='falaj'?'selected':'' ?>>فلج</option>
            <option value="farm" <?= ((string)($row['owner_type']??''))==='farm'?'selected':'' ?>>مزرعة</option>
          </select>
          <div class="small muted">تغيير نوع الجهة سيعيد تحميل الخيارات.</div>
        </div>

        <div>
          <label class="label">الجهة (ID)</label>
          <input class="input" name="owner_id" required value="<?= e((string)($row['owner_id'] ?? '')) ?>" placeholder="أدخل ID أو اختر من القائمة بالأسفل">
          <div class="small muted" style="margin-top:6px">
            <select class="input" onchange="document.querySelector('input[name=owner_id]').value=this.value">
              <option value="">اختر...</option>
              <?php foreach ($ownerOpts as $o): ?>
                <option value="<?= e((string)$o['id']) ?>">
                  <?php if (($row['owner_type']??'')==='farm'): ?>
                    <?= e($o['code']) ?> - <?= e((string)($o['owner_name'] ?? '')) ?> (<?= e($o['oasis_name']) ?>)
                  <?php else: ?>
                    <?= e($o['name']) ?> (<?= e($o['code']) ?>)
                  <?php endif; ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <div>
          <label class="label">الحالة</label>
          <select class="input" name="status">
            <option value="ok" <?= ((string)($row['status']??''))==='ok'?'selected':'' ?>>سليم</option>
            <option value="needs_service" <?= ((string)($row['status']??''))==='needs_service'?'selected':'' ?>>بحاجة صيانة</option>
            <option value="out_of_order" <?= ((string)($row['status']??''))==='out_of_order'?'selected':'' ?>>متعطل</option>
          </select>
        </div>

        <div>
          <label class="label">Serial Number</label>
          <input class="input" name="serial_number" value="<?= e((string)($row['serial_number'] ?? '')) ?>">
        </div>

        <div>
          <label class="label">تاريخ التركيب</label>
          <input class="input" type="date" name="installed_at" value="<?= e((string)($row['installed_at'] ?? '')) ?>">
        </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 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=assets')) ?>">عودة</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", ['asset', $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_assets')): ?>
        <form method="post" enctype="multipart/form-data"
              action="<?= e(url('/index.php?page=attachments&action=upload&owner_type=asset&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=assets&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_assets')): ?>
                    <form method="post" action="<?= e(url('/index.php?page=attachments&action=delete&owner_type=asset&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=assets&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; ?>