<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_once __DIR__ . '/_lib.php';
require_login();

$pdo = db();
$cid = (int)($_SESSION['company_id'] ?? 0);
$uid = (int)($_SESSION['user_id'] ?? 0);
csrf_bootstrap();
fleet_ensure_schema($pdo);

$err = '';
$editingId = (int)($_GET['edit'] ?? 0);

function vehicle_ownership_label(string $v): string {
  return strtoupper($v) === 'EXTERNAL' ? 'غير مملوكة للشركة' : 'مملوكة للشركة';
}
function vehicle_can_delete(PDO $pdo, int $companyId, int $vehicleId): bool {
  foreach ([
    ['vehicle_rental_contracts','vehicle_id'],
    ['fleet_limo_trips','vehicle_id'],
  ] as [$table, $col]) {
    if (!fleet_table_exists($pdo, $table)) continue;
    $st = $pdo->prepare("SELECT COUNT(*) FROM {$table} WHERE company_id=? AND {$col}=?");
    $st->execute([$companyId, $vehicleId]);
    if ((int)$st->fetchColumn() > 0) return false;
  }
  return true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = trim((string)($_POST['action'] ?? ''));
  try {
    if (in_array($action, ['create','update'], true)) {
      $plateNo = trim((string)($_POST['plate_no'] ?? ''));
      $plateCurrent = trim((string)($_POST['plate_no_current'] ?? ''));
      $vehicleTypeId = (int)($_POST['vehicle_type_id'] ?? 0) ?: null;
      $ownershipType = strtoupper(trim((string)($_POST['ownership_type'] ?? 'OWNED')));
      $ownerName = trim((string)($_POST['owner_name'] ?? ''));
      $brand = trim((string)($_POST['brand'] ?? ''));
      $model = trim((string)($_POST['model'] ?? ''));
      $modelYear = trim((string)($_POST['model_year'] ?? ''));
      $color = trim((string)($_POST['color'] ?? ''));
      $chassisNo = trim((string)($_POST['chassis_no'] ?? ''));
      $engineNo = trim((string)($_POST['engine_no'] ?? ''));
      $notes = trim((string)($_POST['notes'] ?? ''));
      $isActive = isset($_POST['is_active']) ? 1 : 0;

      if ($plateNo === '') throw new RuntimeException('رقم اللوحة الأساسي مطلوب.');
      if (!$plateCurrent) $plateCurrent = $plateNo;
      if ($vehicleTypeId <= 0) throw new RuntimeException('اختر نوع المركبة من القائمة.');
      if (!in_array($ownershipType, ['OWNED','EXTERNAL'], true)) $ownershipType = 'OWNED';
      if ($ownershipType === 'EXTERNAL' && $ownerName === '') throw new RuntimeException('اسم المالك مطلوب للمركبات غير المملوكة للشركة.');

      if ($action === 'create') {
        $chk = $pdo->prepare("SELECT id FROM vehicles WHERE company_id=? AND plate_no_current=? LIMIT 1");
        $chk->execute([$cid, $plateCurrent]);
        if ($chk->fetchColumn()) throw new RuntimeException('رقم اللوحة الحالي مستخدم بالفعل.');
        $pdo->prepare("INSERT INTO vehicles (company_id, plate_no, plate_no_current, vehicle_type_id, ownership_type, owner_name, brand, model, model_year, color, chassis_no, engine_no, notes, is_active, created_by, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())")
            ->execute([$cid, $plateNo, $plateCurrent, $vehicleTypeId, $ownershipType, $ownerName ?: null, $brand ?: null, $model ?: null, $modelYear ?: null, $color ?: null, $chassisNo ?: null, $engineNo ?: null, $notes ?: null, $isActive, $uid ?: null]);
        $id = (int)$pdo->lastInsertId();
        audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'CREATE_VEHICLE','entity_type'=>'vehicle','entity_id'=>(string)$id,'description'=>'إضافة مركبة '.$plateCurrent]);
        flash_set('تم إضافة المركبة بنجاح.');
        header('Location: vehicles.php'); exit;
      }

      if ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $chk = $pdo->prepare("SELECT id FROM vehicles WHERE company_id=? AND plate_no_current=? AND id<>? LIMIT 1");
        $chk->execute([$cid, $plateCurrent, $id]);
        if ($chk->fetchColumn()) throw new RuntimeException('رقم اللوحة الحالي مستخدم في مركبة أخرى.');
        $pdo->prepare("UPDATE vehicles SET plate_no=?, plate_no_current=?, vehicle_type_id=?, ownership_type=?, owner_name=?, brand=?, model=?, model_year=?, color=?, chassis_no=?, engine_no=?, notes=?, is_active=?, updated_at=NOW() WHERE id=? AND company_id=?")
            ->execute([$plateNo, $plateCurrent, $vehicleTypeId, $ownershipType, $ownerName ?: null, $brand ?: null, $model ?: null, $modelYear ?: null, $color ?: null, $chassisNo ?: null, $engineNo ?: null, $notes ?: null, $isActive, $id, $cid]);
        audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'UPDATE_VEHICLE','entity_type'=>'vehicle','entity_id'=>(string)$id,'description'=>'تعديل مركبة '.$plateCurrent]);
        flash_set('تم تعديل بيانات المركبة.');
        header('Location: vehicles.php'); exit;
      }
    }

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      $st = $pdo->prepare("SELECT plate_no_current, plate_no FROM vehicles WHERE id=? AND company_id=? LIMIT 1");
      $st->execute([$id, $cid]);
      $row = $st->fetch(PDO::FETCH_ASSOC);
      if (!$row) throw new RuntimeException('المركبة غير موجودة.');
      if (!vehicle_can_delete($pdo, $cid, $id)) throw new RuntimeException('لا يمكن حذف المركبة لوجود ارتباطات تشغيل أو تأجير عليها.');
      $pdo->prepare("DELETE FROM vehicles WHERE id=? AND company_id=?")->execute([$id, $cid]);
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>$uid,'module'=>'fleet','action'=>'DELETE_VEHICLE','entity_type'=>'vehicle','entity_id'=>(string)$id,'description'=>'حذف مركبة '.($row['plate_no_current'] ?: $row['plate_no'])]);
      flash_set('تم حذف المركبة.');
      header('Location: vehicles.php'); exit;
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
    $editingId = (int)($_POST['id'] ?? $editingId);
  }
}

$types = fleet_vehicle_types($pdo, $cid);
$rows = $pdo->prepare("SELECT v.*, vt.name AS vehicle_type_name FROM vehicles v LEFT JOIN vehicle_types vt ON vt.id=v.vehicle_type_id AND vt.company_id=v.company_id WHERE v.company_id=? ORDER BY v.id DESC");
$rows->execute([$cid]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC) ?: [];

$editRow = null;
if ($editingId > 0) {
  foreach ($rows as $r) if ((int)$r['id'] === $editingId) { $editRow = $r; break; }
}

render_layout('تسجيل المركبات','إدارة السيارات <span class="mx-1">/</span> تسجيل المركبات', function() use ($types, $rows, $err, $editRow, $pdo, $cid) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-start align-items-md-center justify-content-between flex-column flex-md-row gap-2 mb-3">
    <div>
      <div class="fw-bold fs-4">تسجيل المركبات</div>
      <div class="text-secondary small">إدارة المركبات المملوكة وغير المملوكة للشركة مع الربط المباشر على قائمة أنواع المركبات.</div>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <a class="btn btn-outline-primary" href="vehicle_types.php"><i class="bi bi-tags"></i> أنواع المركبات</a>
      <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#createVehicleModal"><i class="bi bi-plus-lg"></i> إضافة مركبة</button>
    </div>
  </div>

  <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

  <div class="card cardx">
    <div class="p-3 d-flex align-items-center justify-content-between">
      <div class="fw-bold">قائمة المركبات</div>
      <span class="text-secondary small"><?= count($rows) ?> مركبة</span>
    </div>
    <div class="table-responsive px-3 pb-3">
      <table class="table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <th>#</th>
            <th>اللوحة الحالية</th>
            <th>نوع المركبة</th>
            <th>الماركة / الموديل</th>
            <th>الملكية</th>
            <th>الحالة</th>
            <th class="text-end">إجراءات</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td class="text-secondary"><?= (int)$r['id'] ?></td>
            <td>
              <div class="fw-semibold"><?= h($r['plate_no_current'] ?: $r['plate_no']) ?></div>
              <div class="small text-secondary">اللوحة الأساسية: <?= h($r['plate_no']) ?></div>
            </td>
            <td><?= h($r['vehicle_type_name'] ?: '-') ?></td>
            <td><?= h(trim(($r['brand'] ?? '') . ' ' . ($r['model'] ?? '')) ?: '-') ?></td>
            <td>
              <div><?= h(vehicle_ownership_label((string)$r['ownership_type'])) ?></div>
              <?php if(($r['ownership_type'] ?? '') === 'EXTERNAL' && !empty($r['owner_name'])): ?>
                <div class="small text-secondary">المالك: <?= h($r['owner_name']) ?></div>
              <?php endif; ?>
            </td>
            <td>
              <?php if((int)($r['is_active'] ?? 1) === 1): ?>
                <span class="badge bg-success-subtle text-success border">نشطة</span>
              <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary border">موقوفة</span>
              <?php endif; ?>
            </td>
            <td class="text-end">
              <a class="btn btn-sm btn-outline-primary" href="?edit=<?= (int)$r['id'] ?>"><i class="bi bi-pencil-square"></i> تعديل</a>
              <?php if(vehicle_can_delete($pdo, $cid, (int)$r['id'])): ?>
              <form method="post" class="d-inline" onsubmit="return confirm('حذف المركبة؟');">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i> حذف</button>
              </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?>
          <tr><td colspan="7" class="text-center text-secondary py-4">لا توجد مركبات مسجلة بعد.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php
$ownershipValue = ($_POST['action'] ?? '') === 'create' ? ($_POST['ownership_type'] ?? 'OWNED') : 'OWNED';
?>
<div class="modal fade modal-erp" id="createVehicleModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create">
        <div class="modal-header">
          <h5 class="modal-title">إضافة مركبة</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-md-4">
              <label class="form-label">رقم اللوحة الأساسي</label>
              <input class="form-control" name="plate_no" required value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['plate_no'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">رقم اللوحة الحالي</label>
              <input class="form-control" name="plate_no_current" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['plate_no_current'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">نوع المركبة</label>
              <select class="form-select" name="vehicle_type_id" required>
                <option value="">اختر النوع</option>
                <?php foreach($types as $t): ?>
                  <option value="<?= (int)$t['id'] ?>" <?= ((int)($_POST['action'] ?? '' === 'create' ? ($_POST['vehicle_type_id'] ?? 0) : 0) === (int)$t['id']) ? 'selected' : '' ?>><?= h($t['name']) ?><?= !empty($t['category']) ? ' - ' . h($t['category']) : '' ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">الملكية</label>
              <select class="form-select js-ownership" name="ownership_type">
                <option value="OWNED" <?= $ownershipValue === 'OWNED' ? 'selected' : '' ?>>مملوكة للشركة</option>
                <option value="EXTERNAL" <?= $ownershipValue === 'EXTERNAL' ? 'selected' : '' ?>>غير مملوكة للشركة</option>
              </select>
            </div>
            <div class="col-md-4 js-owner-name-wrap" style="display:<?= $ownershipValue === 'EXTERNAL' ? 'block' : 'none' ?>;">
              <label class="form-label">اسم المالك</label>
              <input class="form-control js-owner-name" name="owner_name" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['owner_name'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">الماركة</label>
              <input class="form-control" name="brand" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['brand'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">الموديل</label>
              <input class="form-control" name="model" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['model'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">سنة الموديل</label>
              <input class="form-control" name="model_year" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['model_year'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">اللون</label>
              <input class="form-control" name="color" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['color'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">رقم الشاسيه</label>
              <input class="form-control" name="chassis_no" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['chassis_no'] ?? '') : '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">رقم المحرك</label>
              <input class="form-control" name="engine_no" value="<?= h($_POST['action'] ?? '' === 'create' ? ($_POST['engine_no'] ?? '') : '') ?>">
            </div>
            <div class="col-md-12">
              <label class="form-label">ملاحظات</label>
              <textarea class="form-control" name="notes" rows="3"><?= h($_POST['action'] ?? '' === 'create' ? ($_POST['notes'] ?? '') : '') ?></textarea>
            </div>
            <div class="col-md-12">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="createVehicleActive" name="is_active" <?= (($_POST['action'] ?? '') === 'create' ? isset($_POST['is_active']) : true) ? 'checked' : '' ?>>
                <label class="form-check-label" for="createVehicleActive">المركبة نشطة</label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if($editRow): ?>
<div class="modal fade modal-erp" id="editVehicleModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>">
        <div class="modal-header">
          <h5 class="modal-title">تعديل مركبة</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-md-4"><label class="form-label">رقم اللوحة الأساسي</label><input class="form-control" name="plate_no" required value="<?= h($editRow['plate_no']) ?>"></div>
            <div class="col-md-4"><label class="form-label">رقم اللوحة الحالي</label><input class="form-control" name="plate_no_current" value="<?= h($editRow['plate_no_current'] ?: $editRow['plate_no']) ?>"></div>
            <div class="col-md-4">
              <label class="form-label">نوع المركبة</label>
              <select class="form-select" name="vehicle_type_id" required>
                <option value="">اختر النوع</option>
                <?php foreach($types as $t): ?>
                  <option value="<?= (int)$t['id'] ?>" <?= ((int)$editRow['vehicle_type_id'] === (int)$t['id']) ? 'selected' : '' ?>><?= h($t['name']) ?><?= !empty($t['category']) ? ' - ' . h($t['category']) : '' ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">الملكية</label>
              <select class="form-select js-ownership" name="ownership_type">
                <option value="OWNED" <?= ($editRow['ownership_type'] ?? 'OWNED') === 'OWNED' ? 'selected' : '' ?>>مملوكة للشركة</option>
                <option value="EXTERNAL" <?= ($editRow['ownership_type'] ?? '') === 'EXTERNAL' ? 'selected' : '' ?>>غير مملوكة للشركة</option>
              </select>
            </div>
            <div class="col-md-4 js-owner-name-wrap" style="display:<?= ($editRow['ownership_type'] ?? '') === 'EXTERNAL' ? 'block' : 'none' ?>;">
              <label class="form-label">اسم المالك</label>
              <input class="form-control js-owner-name" name="owner_name" value="<?= h($editRow['owner_name'] ?? '') ?>">
            </div>
            <div class="col-md-4"><label class="form-label">الماركة</label><input class="form-control" name="brand" value="<?= h($editRow['brand'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">الموديل</label><input class="form-control" name="model" value="<?= h($editRow['model'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">سنة الموديل</label><input class="form-control" name="model_year" value="<?= h($editRow['model_year'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">اللون</label><input class="form-control" name="color" value="<?= h($editRow['color'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">رقم الشاسيه</label><input class="form-control" name="chassis_no" value="<?= h($editRow['chassis_no'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">رقم المحرك</label><input class="form-control" name="engine_no" value="<?= h($editRow['engine_no'] ?? '') ?>"></div>
            <div class="col-md-12"><label class="form-label">ملاحظات</label><textarea class="form-control" name="notes" rows="3"><?= h($editRow['notes'] ?? '') ?></textarea></div>
            <div class="col-md-12">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="editVehicleActive" name="is_active" <?= (int)($editRow['is_active'] ?? 1) === 1 ? 'checked' : '' ?>>
                <label class="form-check-label" for="editVehicleActive">المركبة نشطة</label>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ التعديلات</button>
          <a class="btn btn-outline-secondary" href="vehicles.php">إغلاق</a>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('editVehicleModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function(){
  document.querySelectorAll('.js-ownership').forEach(function(select){
    const modalBody = select.closest('.modal-body') || document;
    const wrap = modalBody.querySelector('.js-owner-name-wrap');
    const input = modalBody.querySelector('.js-owner-name');
    const sync = function(){
      const external = select.value === 'EXTERNAL';
      if (wrap) wrap.style.display = external ? 'block' : 'none';
      if (input) input.required = external;
    };
    select.addEventListener('change', sync);
    sync();
  });

  <?php if(!$editRow && $err && (($_POST['action'] ?? '') === 'create')): ?>
  const createEl = document.getElementById('createVehicleModal');
  if (createEl && window.bootstrap) new bootstrap.Modal(createEl).show();
  <?php endif; ?>
});
</script>
<?php }); ?>
