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

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

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

$contractors = db_all("SELECT id,code,name,is_active FROM contractors ORDER BY name ASC");

$contractor_id = intval($_GET['contractor_id'] ?? 0);
$status = trim($_GET['status'] ?? '');
$q = trim($_GET['q'] ?? '');

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

  if (($action==='create') || ($action==='edit' && $id>0)) {
    $data = [
      'contractor_id' => intval($_POST['contractor_id'] ?? 0),
      'contract_no' => strtoupper(trim($_POST['contract_no'] ?? '')),
      'title' => trim($_POST['title'] ?? ''),
      'start_date' => trim($_POST['start_date'] ?? ''),
      'end_date' => trim($_POST['end_date'] ?? ''),
      'status' => $_POST['status'] ?? 'active',
      'terms' => trim($_POST['terms'] ?? ''),
    ];
    if ($data['contractor_id']<=0 || $data['contract_no']==='' || $data['title']==='') {
      flash_set('error','المقاول ورقم العقد والعنوان مطلوبة.');
      redirect(url('/index.php?page=contracts&action='.$action.($id?('&id='.$id):'')));
    }
    $sd = $data['start_date'] !== '' ? $data['start_date'] : null;
    $ed = $data['end_date'] !== '' ? $data['end_date'] : null;
    $terms = $data['terms'] !== '' ? $data['terms'] : null;

    if ($action==='create') {
      $newId = db_insert("INSERT INTO contracts
        (contractor_id,contract_no,title,start_date,end_date,status,terms,created_at,updated_at)
        VALUES (?,?,?,?,?,?,?,?,?)",
        [$data['contractor_id'],$data['contract_no'],$data['title'],$sd,$ed,$data['status'],$terms, now_dt(), null]
      );
      audit_log('create','contract',$newId,null,contract_find($newId));
      flash_set('ok','تمت إضافة العقد.');
      redirect(url('/index.php?page=contracts&action=edit&id='.$newId));
    }

    if ($action==='edit' && $id>0) {
      $old = contract_find($id);
      db_exec("UPDATE contracts SET contractor_id=?, contract_no=?, title=?, start_date=?, end_date=?, status=?, terms=?, updated_at=? WHERE id=?",
        [$data['contractor_id'],$data['contract_no'],$data['title'],$sd,$ed,$data['status'],$terms, now_dt(), $id]
      );
      $new = contract_find($id);
      audit_log('update','contract',$id,$old,$new);
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=contracts&action=edit&id='.$id));
    }
  }

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

  if ($action==='add_service' && $id>0) {
    $svc = [
      'service_name' => trim($_POST['service_name'] ?? ''),
      'unit' => trim($_POST['unit'] ?? ''),
      'unit_price' => ($_POST['unit_price'] ?? '') !== '' ? floatval($_POST['unit_price']) : null,
      'notes' => trim($_POST['notes'] ?? ''),
      'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];
    if ($svc['service_name']==='') {
      flash_set('error','اسم الخدمة مطلوب.');
      redirect(url('/index.php?page=contracts&action=edit&id='.$id.'#services'));
    }

    // NOTE: schema includes is_active + updated_at (upgrade_v032.php will add if missing)
    $svcId = db_insert(
      "INSERT INTO contract_services (contract_id,service_name,unit,unit_price,notes,is_active,created_at,updated_at)
       VALUES (?,?,?,?,?,?,?,?)",
      [
        $id,
        $svc['service_name'],
        ($svc['unit']!=='' ? $svc['unit'] : null),
        $svc['unit_price'],
        ($svc['notes']!=='' ? $svc['notes'] : null),
        $svc['is_active'],
        now_dt(),
        null
      ]
    );

    $row = db_one("SELECT * FROM contract_services WHERE id=?", [$svcId]);
    audit_log('create','contract_service',$svcId,null,$row);
    flash_set('ok','تمت إضافة الخدمة.');
    redirect(url('/index.php?page=contracts&action=edit&id='.$id.'#services'));
  }

  if ($action==='delete_service') {
    $sid = intval($_POST['service_id'] ?? 0);
    if ($sid>0) {
      $old = db_one("SELECT * FROM contract_services WHERE id=?", [$sid]);
      db_exec("DELETE FROM contract_services WHERE id=?", [$sid]);
      audit_log('delete','contract_service',$sid,$old,null);
      flash_set('ok','تم حذف الخدمة.');
    }
    redirect(url('/index.php?page=contracts&action=edit&id='.$id.'#services'));
  }

  if ($action==='toggle_service') {
    $sid = intval($_POST['service_id'] ?? 0);
    if ($sid>0) {
      $old = db_one("SELECT * FROM contract_services WHERE id=?", [$sid]);
      $newActive = intval($old['is_active'] ?? 1)===1 ? 0 : 1;
      db_exec("UPDATE contract_services SET is_active=?, updated_at=? WHERE id=?", [$newActive, now_dt(), $sid]);
      $new = db_one("SELECT * FROM contract_services WHERE id=?", [$sid]);
      audit_log('update','contract_service',$sid,$old,$new);
      flash_set('ok','تم تحديث حالة الخدمة.');
    }
    redirect(url('/index.php?page=contracts&action=edit&id='.$id.'#services'));
  }
}

$title = 'العقود';

if ($action==='create') {
  require_perm('manage_contracts');
  $title = 'إضافة عقد';
  $row = ['contractor_id'=>$contractor_id?:0,'contract_no'=>'','title'=>'','start_date'=>'','end_date'=>'','status'=>'active','terms'=>''];
  $services = [];
  include __DIR__ . '/contracts_form.php';
  return;
}

if ($action==='edit' && $id>0) {
  $title = 'تعديل عقد';
  $row = contract_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=contracts')); }
  $services = db_all("SELECT * FROM contract_services WHERE contract_id=? ORDER BY id DESC", [$id]);
  include __DIR__ . '/contracts_form.php';
  return;
}

if ($action==='delete' && $id>0) {
  require_perm('manage_contracts');
  $title = 'حذف عقد';
  $row = contract_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=contracts')); }
  $con = db_one("SELECT code,name FROM contractors WHERE id=?", [intval($row['contractor_id'])]);
  include __DIR__ . '/contracts_delete.php';
  return;
}

// list
$params=[];
$sql = "SELECT c.*, ct.code contractor_code, ct.name contractor_name
        FROM contracts c
        JOIN contractors ct ON ct.id=c.contractor_id
        WHERE 1=1";

if ($contractor_id>0) { $sql .= " AND c.contractor_id=?"; $params[]=$contractor_id; }
if ($status!=='') { $sql .= " AND c.status=?"; $params[]=$status; }
if ($q!=='') {
  $sql .= " AND (c.contract_no LIKE ? OR c.title LIKE ? OR ct.name LIKE ?)";
  $like="%{$q}%";
  array_push($params,$like,$like,$like);
}
$sql .= " ORDER BY c.id DESC LIMIT 600";
$rows = db_all($sql, $params);

include __DIR__ . '/contracts_list.php';

