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

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

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

// Filters
$filter_inspector = intval($_GET['filter_inspector'] ?? 0);
$filter_status = trim($_GET['filter_status'] ?? '');
$q = trim($_GET['q'] ?? '');

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

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

  if ($action === 'create' || ($action === 'edit' && $id > 0)) {
    $data = [
      'inspector_id' => intval($_POST['inspector_id'] ?? 0),
      'entity_type'  => trim($_POST['entity_type'] ?? ''),
      'entity_id'    => intval($_POST['entity_id'] ?? 0),
      'task_title'   => trim($_POST['task_title'] ?? ''),
      'task_desc'    => trim($_POST['task_desc'] ?? ''),
      'status'       => trim($_POST['status'] ?? 'open'),
      'due_date'     => trim($_POST['due_date'] ?? ''),
    ];
    if ($data['inspector_id'] <= 0) {
      flash_set('error','اختر المراقب.');
      redirect(url('/index.php?page=inspector_tasks&action=' . $action . ($id ? '&id=' . $id : '')));
    }
    if (!in_array($data['entity_type'], ['oasis','farm'], true) || $data['entity_id'] <= 0) {
      flash_set('error','اختر الواحة/المزرعة بشكل صحيح.');
      redirect(url('/index.php?page=inspector_tasks&action=' . $action . ($id ? '&id=' . $id : '')));
    }
    if ($data['task_title'] === '') {
      flash_set('error','عنوان المهمة مطلوب.');
      redirect(url('/index.php?page=inspector_tasks&action=' . $action . ($id ? '&id=' . $id : '')));
    }
    if (!in_array($data['status'], ['open','in_progress','done','cancelled'], true)) {
      $data['status'] = 'open';
    }
    $due = $data['due_date'] !== '' ? $data['due_date'] : null;

    if ($action === 'create') {
      $newId = db_insert(
        "INSERT INTO inspector_tasks (inspector_id,entity_type,entity_id,task_title,task_desc,status,due_date,created_at,updated_at)
         VALUES (?,?,?,?,?,?,?,?,?)",
        [$data['inspector_id'],$data['entity_type'],$data['entity_id'],$data['task_title'],($data['task_desc']!==''?$data['task_desc']:null),$data['status'],$due,now_dt(),null]
      );
      audit_log('create','inspector_task',$newId,null,itask_find($newId));
      flash_set('ok','تمت إضافة المهمة.');
      redirect(url('/index.php?page=inspector_tasks&filter_inspector=' . $data['inspector_id']));
    }

    if ($action === 'edit' && $id > 0) {
      $old = itask_find($id);
      db_exec(
        "UPDATE inspector_tasks SET inspector_id=?,entity_type=?,entity_id=?,task_title=?,task_desc=?,status=?,due_date=?,updated_at=? WHERE id=?",
        [$data['inspector_id'],$data['entity_type'],$data['entity_id'],$data['task_title'],($data['task_desc']!==''?$data['task_desc']:null),$data['status'],$due,now_dt(),$id]
      );
      audit_log('update','inspector_task',$id,$old,itask_find($id));
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=inspector_tasks&filter_inspector=' . $data['inspector_id']));
    }
  }

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

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

$inspectors = db_all("SELECT id,name,code FROM inspectors ORDER BY id DESC LIMIT 500");

if ($action === 'create') {
  $page_title = 'إضافة مهمة';
  $row = ['inspector_id'=>$filter_inspector,'entity_type'=>'oasis','entity_id'=>0,'task_title'=>'','task_desc'=>'','status'=>'open','due_date'=>''];
  include __DIR__ . '/inspector_tasks_form.php';
  return;
}

if ($action === 'edit' && $id > 0) {
  $page_title = 'تعديل مهمة';
  $row = itask_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=inspector_tasks')); }
  include __DIR__ . '/inspector_tasks_form.php';
  return;
}

if ($action === 'delete' && $id > 0) {
  $page_title = 'حذف مهمة';
  $row = itask_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=inspector_tasks')); }
  include __DIR__ . '/inspector_tasks_delete.php';
  return;
}

// list
$params = [];
$sql = "SELECT t.*, i.name AS inspector_name, i.code AS inspector_code
        FROM inspector_tasks t
        JOIN inspectors i ON i.id=t.inspector_id
        WHERE 1=1";

if ($filter_inspector > 0) {
  $sql .= " AND t.inspector_id=?";
  $params[] = $filter_inspector;
}
if ($filter_status !== '' && in_array($filter_status, ['open','in_progress','done','cancelled'], true)) {
  $sql .= " AND t.status=?";
  $params[] = $filter_status;
}
if ($q !== '') {
  $sql .= " AND (t.task_title LIKE ? OR t.task_desc LIKE ?)";
  $like = "%{$q}%";
  $params[] = $like;
  $params[] = $like;
}
$sql .= " ORDER BY t.id DESC LIMIT 1000";

$rows = db_all($sql, $params);

include __DIR__ . '/inspector_tasks_list.php';
