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

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

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

$assets = db_all("SELECT id, tag FROM assets ORDER BY tag ASC");
$users  = db_all("SELECT id, name FROM users WHERE is_active=1 ORDER BY name ASC");
$contractors = db_all("SELECT id, code, name, is_active FROM contractors ORDER BY name ASC");

if (!function_exists('contracts_for_contractor')) {
function contracts_for_contractor(int $contractor_id = 0): array {
  if ($contractor_id > 0) {
    return db_all("SELECT c.*, ct.name contractor_name, ct.code contractor_code
                   FROM contracts c JOIN contractors ct ON ct.id=c.contractor_id
                   WHERE c.contractor_id=? ORDER BY c.id DESC", [$contractor_id]);
  }
  return db_all("SELECT c.*, ct.name contractor_name, ct.code contractor_code
                 FROM contracts c JOIN contractors ct ON ct.id=c.contractor_id
                 ORDER BY c.id DESC");
}
}

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

  if (($action==='create') || ($action==='edit' && $id>0)) {
    $data = [
      'asset_id' => intval($_POST['asset_id'] ?? 0),
      'category' => trim($_POST['category'] ?? ''),
      'title' => trim($_POST['title'] ?? ''),
      'description' => trim($_POST['description'] ?? ''),
      'priority' => $_POST['priority'] ?? 'medium',
      'status' => $_POST['status'] ?? 'open',
      'reported_at' => trim($_POST['reported_at'] ?? ''),
      'due_date' => trim($_POST['due_date'] ?? ''),
      'reported_by' => intval($_POST['reported_by'] ?? 0),
      'assigned_to' => intval($_POST['assigned_to'] ?? 0),
      'contractor_id' => intval($_POST['contractor_id'] ?? 0),
      'contract_id' => intval($_POST['contract_id'] ?? 0),
      'estimated_cost' => ($_POST['estimated_cost'] ?? '') !== '' ? floatval($_POST['estimated_cost']) : null,
      'actual_cost' => ($_POST['actual_cost'] ?? '') !== '' ? floatval($_POST['actual_cost']) : null,
    ];

    if ($data['asset_id']<=0 || $data['title']==='') {
      flash_set('error','الرجاء اختيار أصل وكتابة عنوان.');
      redirect(url('/index.php?page=maintenance&action='.$action.($id?('&id='.$id):'')));
    }

    $allowedPriority = ['low','medium','high'];
    $allowedStatus = ['open','in_progress','closed'];
    if (!in_array($data['priority'], $allowedPriority, true)) $data['priority']='medium';
    if (!in_array($data['status'], $allowedStatus, true)) $data['status']='open';

    $reported_at = $data['reported_at'] !== '' ? $data['reported_at'] : now_dt();
    // دعم datetime-local من المتصفح: 2025-12-28T14:30 => 2025-12-28 14:30:00
    if (is_string($reported_at) && strpos($reported_at, 'T') !== false) {
      $reported_at = str_replace('T', ' ', $reported_at);
    }
    if (is_string($reported_at) && preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $reported_at)) {
      $reported_at .= ':00';
    }
    $due_date = $data['due_date'] !== '' ? $data['due_date'] : null;

    $assigned_to = $data['assigned_to']>0 ? $data['assigned_to'] : null;
    $reported_by = $data['reported_by']>0 ? $data['reported_by'] : (auth_user()['id'] ?? null);

    $contractor_id = $data['contractor_id']>0 ? $data['contractor_id'] : null;
    $contract_id = $data['contract_id']>0 ? $data['contract_id'] : null;

    // Validate contract belongs to contractor (if both set)
    if ($contract_id && $contractor_id) {
      $ok = db_one("SELECT id FROM contracts WHERE id=? AND contractor_id=? LIMIT 1", [$contract_id, $contractor_id]);
      if (!$ok) $contract_id = null;
    }
    // If contract set but contractor not set -> infer
    if ($contract_id && !$contractor_id) {
      $row = db_one("SELECT contractor_id FROM contracts WHERE id=? LIMIT 1", [$contract_id]);
      if ($row) $contractor_id = intval($row['contractor_id']);
    }

    $completed_at = null;
    if ($data['status']==='closed') $completed_at = now_dt();

    if ($action==='create') {
      $assignedMetaAt = ($contractor_id || $contract_id) ? now_dt() : null;
      $assignedMetaBy = ($contractor_id || $contract_id) ? (auth_user()['id'] ?? null) : null;

      
// INSERT ديناميكي لتوافق قواعد البيانات القديمة (قد تكون بعض الأعمدة غير موجودة)
$cols = ['asset_id','title','description','priority','status','reported_at','due_date','reported_by','assigned_to','created_at','updated_at'];
$vals = [
  $data['asset_id'],
  $data['title'],
  ($data['description']!==''?$data['description']:null),
  $data['priority'],
  $data['status'],
  $reported_at,
  $due_date,
  $reported_by,
  $assigned_to,
  now_dt(),
  null
];

if (db_has_column('maintenance_requests','tag')) {
  $cols[] = 'tag';
  $vals[] = ($data['tag']!==''?$data['tag']:null);
}
if (db_has_column('maintenance_requests','category')) {
  $cols[] = 'category';
  $vals[] = ($data['category']!==''?$data['category']:null);
}
if (db_has_column('maintenance_requests','completed_at')) {
  $cols[] = 'completed_at';
  $vals[] = $completed_at;
}
if (db_has_column('maintenance_requests','contractor_id')) {
  $cols[] = 'contractor_id';
  $vals[] = $contractor_id;
}
if (db_has_column('maintenance_requests','contract_id')) {
  $cols[] = 'contract_id';
  $vals[] = $contract_id;
}
if (db_has_column('maintenance_requests','contractor_assigned_at')) {
  $cols[] = 'contractor_assigned_at';
  $vals[] = $assignedMetaAt;
}
if (db_has_column('maintenance_requests','contractor_assigned_by')) {
  $cols[] = 'contractor_assigned_by';
  $vals[] = $assignedMetaBy;
}
if (db_has_column('maintenance_requests','estimated_cost')) {
  $cols[] = 'estimated_cost';
  $vals[] = ($data['estimated_cost']!==''?$data['estimated_cost']:null);
}
if (db_has_column('maintenance_requests','actual_cost')) {
  $cols[] = 'actual_cost';
  $vals[] = ($data['actual_cost']!==''?$data['actual_cost']:null);
}

$ph = implode(',', array_fill(0, count($cols), '?'));
$sql = "INSERT INTO maintenance_requests (".implode(',', $cols).") VALUES ($ph)";
$newId = db_insert($sql, $vals);
audit_log('create','maintenance_request',$newId,null,mr_find($newId));
      flash_set('ok','تمت إضافة طلب الصيانة.');
      redirect(url('/index.php?page=maintenance'));
    }

    if ($action==='edit' && $id>0) {
      $old = mr_find($id);
      if (!$old) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=maintenance')); }

      // contractor assignment meta if changed
      $oldCon = intval($old['contractor_id'] ?? 0);
      $oldCtr = intval($old['contract_id'] ?? 0);
      $newCon = intval($contractor_id ?? 0);
      $newCtr = intval($contract_id ?? 0);
      $assignChanged = ($oldCon !== $newCon) || ($oldCtr !== $newCtr);

      $assignedMetaAt = $old['contractor_assigned_at'] ?? null;
      $assignedMetaBy = $old['contractor_assigned_by'] ?? null;
      if ($assignChanged) {
        $assignedMetaAt = ($contractor_id || $contract_id) ? now_dt() : null;
        $assignedMetaBy = ($contractor_id || $contract_id) ? (auth_user()['id'] ?? null) : null;
      }

      if ($data['status']==='closed' && empty($old['completed_at'])) $completed_at = now_dt();
      if ($data['status']!=='closed') $completed_at = null;

      
// Build UPDATE dynamically to support legacy schemas
$sets = [];
$params = [];

$sets[] = "asset_id=?";
$params[] = $data['asset_id'];

if (db_has_column('maintenance_requests','tag')) {
  $sets[] = "tag=?";
  $params[] = ($data['tag']!==''?$data['tag']:null);
}
if (db_has_column('maintenance_requests','category')) {
  $sets[] = "category=?";
  $params[] = ($data['category']!==''?$data['category']:null);
}

$sets[] = "title=?";
$params[] = $data['title'];

$sets[] = "description=?";
$params[] = ($data['description']!==''?$data['description']:null);

$sets[] = "priority=?";
$params[] = $data['priority'];

$sets[] = "status=?";
$params[] = $data['status'];

$sets[] = "reported_at=?";
$params[] = $reported_at;

$sets[] = "due_date=?";
$params[] = $due_date;

if (db_has_column('maintenance_requests','completed_at')) {
  $sets[] = "completed_at=?";
  $params[] = $completed_at;
}

$sets[] = "reported_by=?";
$params[] = $reported_by;

$sets[] = "assigned_to=?";
$params[] = $assigned_to;

if (db_has_column('maintenance_requests','contractor_id')) {
  $sets[] = "contractor_id=?";
  $params[] = $contractor_id;
}
if (db_has_column('maintenance_requests','contract_id')) {
  $sets[] = "contract_id=?";
  $params[] = $contract_id;
}
if (db_has_column('maintenance_requests','contractor_assigned_at')) {
  $sets[] = "contractor_assigned_at=?";
  $params[] = (($contractor_id || $contract_id) ? now_dt() : null);
}
if (db_has_column('maintenance_requests','contractor_assigned_by')) {
  $sets[] = "contractor_assigned_by=?";
  $params[] = (($contractor_id || $contract_id) ? (auth_user()['id'] ?? null) : null);
}
if (db_has_column('maintenance_requests','estimated_cost')) {
  $sets[] = "estimated_cost=?";
  $params[] = ($data['estimated_cost']!==''?floatval($data['estimated_cost']):null);
}
if (db_has_column('maintenance_requests','actual_cost')) {
  $sets[] = "actual_cost=?";
  $params[] = ($data['actual_cost']!==''?floatval($data['actual_cost']):null);
}

$sets[] = "updated_at=?";
$params[] = now_dt();

$params[] = $id;

db_exec("UPDATE maintenance_requests SET ".implode(', ', $sets)." WHERE id=?", $params);

      $new = mr_find($id);
      audit_log('update','maintenance_request',$id,$old,$new);
      flash_set('ok','تم حفظ التعديلات.');
      redirect(url('/index.php?page=maintenance'));
    }
  }

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

$title = 'الصيانة';

if ($action==='create') {
  $title = 'إضافة صيانة';
  $row = [
    'asset_id'=>0,'category'=>'','title'=>'','description'=>'',
    'priority'=>'medium','status'=>'open',
    'reported_at'=>date('Y-m-d H:i:s'),
    'due_date'=>'','reported_by'=>auth_user()['id'] ?? 0,'assigned_to'=>0,
    'contractor_id'=>0,'contract_id'=>0,
    'estimated_cost'=>'','actual_cost'=>''
  ];
  $contracts = contracts_for_contractor(0);
  $view = __DIR__ . '/maintenance_form.php';
  // layout is rendered by public/index.php

  return;
}

if ($action==='edit' && $id>0) {
  $title = 'تعديل صيانة';
  $row = mr_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=maintenance')); }
  $contracts = contracts_for_contractor(intval($row['contractor_id'] ?? 0));
  $view = __DIR__ . '/maintenance_form.php';
  // layout is rendered by public/index.php

  return;
}

if ($action==='delete' && $id>0) {
  $title = 'حذف صيانة';
  $row = mr_find($id);
  if (!$row) { flash_set('error','غير موجود.'); redirect(url('/index.php?page=maintenance')); }
  $view = __DIR__ . '/maintenance_delete.php';
  // layout is rendered by public/index.php

  return;
}

// list filters
$q = trim($_GET['q'] ?? '');
$status = trim($_GET['status'] ?? '');
$priority = trim($_GET['priority'] ?? '');
$assigned_to = intval($_GET['assigned_to'] ?? 0);
$contractor_id = intval($_GET['contractor_id'] ?? 0);
$from = trim($_GET['from'] ?? '');
$to = trim($_GET['to'] ?? '');

$params = [];
$sql = "SELECT mr.*,
        a.tag asset_tag, a.owner_type, a.owner_id,
        u.name assigned_name,
        ct.name contractor_name, ct.code contractor_code,
        c.contract_no
        FROM maintenance_requests mr
        JOIN assets a ON a.id=mr.asset_id
        LEFT JOIN users u ON u.id=mr.assigned_to
        LEFT JOIN contractors ct ON ct.id=mr.contractor_id
        LEFT JOIN contracts c ON c.id=mr.contract_id
        WHERE 1=1";

if ($q!=='') {
  $sql .= " AND (a.tag LIKE ? OR mr.title LIKE ? OR mr.category LIKE ?)";
  $like="%{$q}%";
  array_push($params,$like,$like,$like);
}
if ($status!=='') { $sql .= " AND mr.status=?"; $params[]=$status; }
if ($priority!=='') { $sql .= " AND mr.priority=?"; $params[]=$priority; }
if ($assigned_to>0) { $sql .= " AND mr.assigned_to=?"; $params[]=$assigned_to; }
if ($contractor_id>0) { $sql .= " AND mr.contractor_id=?"; $params[]=$contractor_id; }
if ($from!=='') { $sql .= " AND mr.reported_at >= ?"; $params[]=$from.' 00:00:00'; }
if ($to!=='') { $sql .= " AND mr.reported_at <= ?"; $params[]=$to.' 23:59:59'; }

$sql .= " ORDER BY mr.reported_at DESC LIMIT 900";
$rows = db_all($sql, $params);

$view = __DIR__ . '/maintenance_list.php';
// layout is rendered by public/index.php

