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

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

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

if (!function_exists('inspector_assignments')) {
function inspector_assignments(int $inspectorId): array {
  return db_all("SELECT * FROM inspector_assignments WHERE inspector_id=? ORDER BY id DESC", [$inspectorId]);
}
}

if (!function_exists('inspector_tasks_count')) {
function inspector_tasks_count(int $inspectorId): int {
  $r = db_one("SELECT COUNT(*) AS c FROM inspector_tasks WHERE inspector_id=?", [$inspectorId]);
  return intval($r['c'] ?? 0);
}
}

$q = trim($_GET['q'] ?? '');
$only_active = ($_GET['active'] ?? '') === '1' ? 1 : 0;

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

  // CRUD
  if (in_array($action, ['create','edit','delete'], true)) {
    require_perm('manage_inspectors');
  }

  // Assignment actions (edit page)
  $sub = $_POST['_sub'] ?? '';
  if ($sub === 'add_assignment' && $id > 0) {
    require_perm('manage_inspectors');
    $etype = trim($_POST['entity_type'] ?? '');
    $eid = intval($_POST['entity_id'] ?? 0);
    $role_title = trim($_POST['role_title'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    if (!in_array($etype, ['oasis','farm'], true) || $eid <= 0) {
      flash_set('error', 'يرجى اختيار الواحة/المزرعة بشكل صحيح.');
      redirect(url('/index.php?page=inspectors&action=edit&id='.$id.'#assignments'));
    }
    // ignore duplicates
    db_exec(
      "INSERT INTO inspector_assignments (inspector_id, entity_type, entity_id, role_title, notes, created_at, updated_at)
       VALUES (?,?,?,?,?,?,?)
       ON DUPLICATE KEY UPDATE role_title=VALUES(role_title), notes=VALUES(notes), updated_at=VALUES(updated_at)",
      [$id, $etype, $eid, ($role_title!==''?$role_title:null), ($notes!==''?$notes:null), now_dt(), now_dt()]
    );
    audit_log('create','inspector_assignment', $id, null, ['entity_type'=>$etype,'entity_id'=>$eid]);
    flash_set('ok','تمت إضافة/تحديث الربط.');
    redirect(url('/index.php?page=inspectors&action=edit&id='.$id.'#assignments'));
  }

  if ($sub === 'delete_assignment' && $id > 0) {
    require_perm('manage_inspectors');
    $aid = intval($_POST['assignment_id'] ?? 0);
    if ($aid > 0) {
      $old = db_one("SELECT * FROM inspector_assignments WHERE id=? AND inspector_id=?", [$aid, $id]);
      db_exec("DELETE FROM inspector_assignments WHERE id=? AND inspector_id=?", [$aid, $id]);
      audit_log('delete','inspector_assignment', $aid, $old, null);
    }
    flash_set('ok','تم حذف الربط.');
    redirect(url('/index.php?page=inspectors&action=edit&id='.$id.'#assignments'));
  }

  // Create/Edit inspector
  if ($action === 'create' || ($action === 'edit' && $id > 0)) {
    $data = [
      'code' => strtoupper(trim($_POST['code'] ?? '')),
      'name' => trim($_POST['name'] ?? ''),
      'phone' => trim($_POST['phone'] ?? ''),
      'email' => trim($_POST['email'] ?? ''),
      'emirates_id' => trim($_POST['emirates_id'] ?? ''),
      'notes' => trim($_POST['notes'] ?? ''),
      'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];

    if ($data['name'] === '') {
      flash_set('error','اسم المراقب مطلوب.');
      redirect(url('/index.php?page=inspectors&action='.$action.($id?('&id='.$id):'')));
    }
    if ($data['emirates_id'] !== '' && !preg_match('/^\d{15}$/', $data['emirates_id'])) {
      flash_set('error','هوية إماراتية غير صحيحة (15 رقم).');
      redirect(url('/index.php?page=inspectors&action='.$action.($id?('&id='.$id):'')));
    }

    if ($action === 'create') {
      $newId = db_insert(
        "INSERT INTO inspectors (code,name,phone,email,emirates_id,notes,is_active,created_at,updated_at)
         VALUES (?,?,?,?,?,?,?,?,?)",
        [
          ($data['code']!==''?$data['code']:null),
          $data['name'],
          ($data['phone']!==''?$data['phone']:null),
          ($data['email']!==''?$data['email']:null),
          ($data['emirates_id']!==''?$data['emirates_id']:null),
          ($data['notes']!==''?$data['notes']:null),
          $data['is_active'],
          now_dt(),
          null
        ]
      );
      audit_log('create','inspector',$newId,null,inspector_find($newId));
      flash_set('ok','تمت إضافة المراقب.');
      redirect(url('/index.php?page=inspectors&action=edit&id='.$newId));
    }

    if ($action === 'edit' && $id > 0) {
      $old = inspector_find($id);
      db_exec(
        "UPDATE inspectors SET code=?, name=?, phone=?, email=?, emirates_id=?, notes=?, is_active=?, updated_at=? WHERE id=?",
        [
          ($data['code']!==''?$data['code']:null),
          $data['name'],
          ($data['phone']!==''?$data['phone']:null),
          ($data['email']!==''?$data['email']:null),
          ($data['emirates_id']!==''?$data['emirates_id']:null),
          ($data['notes']!==''?$data['notes']:null),
          $data['is_active'],
          now_dt(),
          $id
        ]
      );
      audit_log('update','inspector',$id,$old,inspector_find($id));
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=inspectors&action=edit&id='.$id));
    }
  }

  if ($action === 'delete' && $id > 0) {
    $old = inspector_find($id);
    // delete related
    db_exec("DELETE FROM inspector_tasks WHERE inspector_id=?", [$id]);
    db_exec("DELETE FROM inspector_assignments WHERE inspector_id=?", [$id]);
    db_exec("DELETE FROM inspectors WHERE id=?", [$id]);
    audit_log('delete','inspector',$id,$old,null);
    flash_set('ok','تم حذف المراقب.');
    redirect(url('/index.php?page=inspectors'));
  }
}

$page_title = 'المراقبون';

if ($action === 'create') {
  $page_title = 'إضافة مراقب';
  $row = ['code'=>'','name'=>'','phone'=>'','email'=>'','emirates_id'=>'','notes'=>'','is_active'=>1];
  $assignments = [];
  include __DIR__ . '/inspectors_form.php';
  return;
}

if ($action === 'edit' && $id > 0) {
  $page_title = 'تعديل مراقب';
  $row = inspector_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=inspectors')); }
  $assignments = inspector_assignments($id);
  $tasksCount = inspector_tasks_count($id);
  // dropdown lists
  $oases = db_all("SELECT id,code,name FROM oases ORDER BY id DESC LIMIT 500");
  $farms = db_all("SELECT id,code,owner_name FROM farms ORDER BY id DESC LIMIT 500");
  include __DIR__ . '/inspectors_form.php';
  return;
}

if ($action === 'delete' && $id > 0) {
  $page_title = 'حذف مراقب';
  $row = inspector_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=inspectors')); }
  $assignments = inspector_assignments($id);
  $tasksCount = inspector_tasks_count($id);
  include __DIR__ . '/inspectors_delete.php';
  return;
}

// list
$params = [];
$sql = "SELECT i.*,
  (SELECT COUNT(*) FROM inspector_assignments a WHERE a.inspector_id=i.id) AS assignments_count,
  (SELECT COUNT(*) FROM inspector_tasks t WHERE t.inspector_id=i.id) AS tasks_count
  FROM inspectors i WHERE 1=1";

if ($q !== '') {
  $sql .= " AND (i.name LIKE ? OR i.code LIKE ? OR i.phone LIKE ? OR i.emirates_id LIKE ?)";
  $like = "%{$q}%";
  array_push($params, $like, $like, $like, $like);
}
if ($only_active === 1) {
  $sql .= " AND i.is_active=1";
}

$sql .= " ORDER BY i.id DESC LIMIT 500";
$rows = db_all($sql, $params);

include __DIR__ . '/inspectors_list.php';
