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

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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  if (in_array($action, ['create','edit','delete'], true)) require_perm('manage_contractors');

  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'] ?? ''),
      'address' => trim($_POST['address'] ?? ''),
      'license_no' => trim($_POST['license_no'] ?? ''),
      'notes' => trim($_POST['notes'] ?? ''),
      'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];
    if ($data['code']==='' || $data['name']==='') {
      flash_set('error','الرمز واسم المقاول مطلوبان.');
      redirect(url('/index.php?page=contractors&action='.$action.($id?('&id='.$id):'')));
    }

    if ($action==='create') {
      $newId = db_insert("INSERT INTO contractors
        (code,name,phone,email,address,license_no,notes,is_active,created_at,updated_at)
        VALUES (?,?,?,?,?,?,?,?,?,?)",
        [
          $data['code'],$data['name'],
          ($data['phone']!==''?$data['phone']:null),
          ($data['email']!==''?$data['email']:null),
          ($data['address']!==''?$data['address']:null),
          ($data['license_no']!==''?$data['license_no']:null),
          ($data['notes']!==''?$data['notes']:null),
          $data['is_active'],
          now_dt(), null
        ]
      );
      audit_log('create','contractor',$newId,null,contractor_find($newId));
      flash_set('ok','تمت إضافة المقاول.');
      redirect(url('/index.php?page=contractors'));
    }

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

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

$title = 'المقاولون';

if ($action==='create') {
  $title = 'إضافة مقاول';
  $row = ['code'=>'','name'=>'','phone'=>'','email'=>'','address'=>'','license_no'=>'','notes'=>'','is_active'=>1];
  include __DIR__ . '/contractors_form.php';
  return;
}

if ($action==='edit' && $id>0) {
  $title = 'تعديل مقاول';
  $row = contractor_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=contractors')); }
  include __DIR__ . '/contractors_form.php';
  return;
}

if ($action==='delete' && $id>0) {
  $title = 'حذف مقاول';
  $row = contractor_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=contractors')); }
  include __DIR__ . '/contractors_delete.php';
  return;
}

// list
$params = [];
$sql = "SELECT c.*,
        (SELECT COUNT(*) FROM contracts x WHERE x.contractor_id=c.id) AS contracts_count
        FROM contractors c WHERE 1=1";

if ($q !== '') {
  $sql .= " AND (c.code LIKE ? OR c.name LIKE ? OR c.phone LIKE ? OR c.email LIKE ?)";
  $like = "%{$q}%";
  array_push($params,$like,$like,$like,$like);
}
if ($only_active===1) {
  $sql .= " AND c.is_active=1";
}
$sql .= " ORDER BY c.id DESC LIMIT 500";
$rows = db_all($sql, $params);

include __DIR__ . '/contractors_list.php';

