<?php
// public/officer/tow.php — إجراء السحب
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/Vehicle.php';
require_once __DIR__.'/../../app/Models/TowLog.php';

$user   = requireAuth(['officer']);
$errors = [];
$action = $_POST['action'] ?? $_GET['action'] ?? 'new';

// --- POST: حفظ سحب جديد ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'save') {
    verifyCsrf();
    $plate    = strtoupper(trim($_POST['plate_number'] ?? ''));
    $reason   = trim($_POST['reason'] ?? '');
    $location = trim($_POST['tow_location'] ?? '');
    $notes    = trim($_POST['notes'] ?? '');

    if (!$plate || !$reason) {
        $errors[] = t('fill_all_fields');
    } else {
        $vehicle = Vehicle::findByPlate($plate);
        if (!$vehicle) {
            $errors[] = t('vehicle_not_found');
        } else {
            $tid = TowLog::create([
                'officer_id'   => $user['id'],
                'vehicle_id'   => $vehicle['id'],
                'plate_number' => $plate,
                'reason'       => $reason,
                'tow_location' => $location,
                'notes'        => $notes,
            ]);
            flash('officer_msg', t('tow_issued'), 'success');
            redirect(BASE_URL . '/officer/tow.php?action=view&id=' . $tid);
        }
    }
}

// --- POST: تحرير السيارة ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'release') {
    verifyCsrf();
    $id = (int)$_POST['id'];
    TowLog::release($id);
    flash('officer_msg', t('vehicle_released'), 'success');
    redirect(BASE_URL . '/officer/tow.php?action=list');
}

// --- GET: عرض سجل واحد ---
$towLog = null;
if ($action === 'view' && isset($_GET['id'])) {
    $towLog = TowLog::find((int)$_GET['id']);
}

// --- قائمة ---
$towLogs = [];
if ($action === 'list') {
    $towLogs = TowLog::byOfficer($user['id']);
}

$towReasons = [
    'ar' => [
        'expired_docs'    => 'وثائق منتهية الصلاحية',
        'no_insurance'    => 'عدم حمل التأمين',
        'serious_accident'=> 'حادث جسيم',
        'drunk_driving'   => 'قيادة تحت تأثير الكحول',
        'illegal_parking' => 'وقوف في مكان ممنوع',
        'no_license'      => 'القيادة بدون رخصة',
        'defective_vehicle'=> 'عطل ميكانيكي خطير',
        'other'           => 'أخرى',
    ],
    'en' => [
        'expired_docs'    => 'Expired Documents',
        'no_insurance'    => 'No Insurance',
        'serious_accident'=> 'Serious Accident',
        'drunk_driving'   => 'Drunk Driving',
        'illegal_parking' => 'Illegal Parking',
        'no_license'      => 'No License',
        'defective_vehicle'=> 'Dangerous Defect',
        'other'           => 'Other',
    ],
    'fr' => [
        'expired_docs'    => 'Documents expirés',
        'no_insurance'    => 'Pas d\'assurance',
        'serious_accident'=> 'Accident grave',
        'drunk_driving'   => 'Conduite en état d\'ivresse',
        'illegal_parking' => 'Stationnement illégal',
        'no_license'      => 'Sans permis',
        'defective_vehicle'=> 'Défaut mécanique grave',
        'other'           => 'Autre',
    ],
];
$reasons = $towReasons[lang()] ?? $towReasons['ar'];
$plate_prefill = strtoupper(trim($_GET['plate'] ?? ''));

$pageTitle  = t('tow_vehicle');
$activePage = BASE_URL . '/officer/tow.php';
require __DIR__ . '/../../app/Views/shared/layout.php';
?>

<?php if ($f = flash('officer_msg')): ?>
<div class="alert alert-<?= $f['type'] ?>"><?= e($f['msg']) ?></div>
<?php endif; ?>

<?php if ($action === 'view' && $towLog): ?>
<!-- عرض سجل السحب -->
<div class="section-header">
  <div class="section-title">🚛 <?= t('tow_record') ?> #<?= $towLog['id'] ?></div>
  <div style="display:flex;gap:8px">
    <a href="<?= BASE_URL ?>/officer/tow.php?action=list" class="btn btn-secondary">← <?= t('back') ?></a>
    <button onclick="window.print()" class="btn btn-secondary">🖨️ <?= t('print') ?></button>
  </div>
</div>

<div class="card" style="max-width:600px;margin:0 auto">
  <div style="background:linear-gradient(135deg,#7c3aed,#4c1d95);color:#fff;padding:28px;border-radius:var(--radius-lg) var(--radius-lg) 0 0;text-align:center">
    <div style="font-size:13px;opacity:.7;margin-bottom:4px">🇩🇿 الجمهورية الجزائرية الديمقراطية الشعبية</div>
    <div style="font-size:22px;font-weight:800;margin-top:8px">🚛 محضر حجز مركبة</div>
    <div style="background:rgba(255,255,255,.15);display:inline-block;padding:6px 20px;border-radius:20px;margin-top:12px;font-family:monospace;font-weight:800;font-size:16px">
      TOW-<?= str_pad($towLog['id'],6,'0',STR_PAD_LEFT) ?>
    </div>
  </div>

  <div class="card-body" style="padding:24px">
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:18px">
      <div style="background:var(--bg-primary);border-radius:10px;padding:14px">
        <div style="font-size:11px;color:var(--text-muted)"><?= t('plate_number') ?></div>
        <div style="font-family:monospace;font-weight:800;font-size:20px;margin-top:4px"><?= e($towLog['plate_number']) ?></div>
      </div>
      <div style="background:var(--bg-primary);border-radius:10px;padding:14px">
        <div style="font-size:11px;color:var(--text-muted)"><?= t('brand') ?> / <?= t('model') ?></div>
        <div style="font-weight:600;margin-top:4px"><?= e($towLog['brand'].' '.$towLog['model']) ?></div>
      </div>
    </div>

    <div style="background:var(--bg-primary);border-radius:10px;padding:14px;margin-bottom:14px">
      <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">📍 <?= t('tow_reason') ?></div>
      <div style="font-weight:700;font-size:15px"><?= e($towLog['reason']) ?></div>
    </div>

    <?php if($towLog['tow_location']): ?>
    <div style="background:var(--bg-primary);border-radius:10px;padding:14px;margin-bottom:14px">
      <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px">🏢 <?= t('tow_location') ?></div>
      <div style="font-weight:600"><?= e($towLog['tow_location']) ?></div>
    </div>
    <?php endif; ?>

    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px">
      <div>
        <div style="font-size:11px;color:var(--text-muted)"><?= t('status') ?></div>
        <?php if($towLog['status']==='active'): ?>
          <span class="badge badge-danger">🔴 <?= t('tow_active') ?></span>
        <?php else: ?>
          <span class="badge badge-success">✅ <?= t('tow_released') ?></span>
          <?php if($towLog['released_at']): ?>
          <div style="font-size:12px;color:var(--text-muted);margin-top:4px"><?= e($towLog['released_at']) ?></div>
          <?php endif; ?>
        <?php endif; ?>
      </div>
      <div style="text-align:<?= lang()==='ar'?'left':'right' ?>">
        <div style="font-size:11px;color:var(--text-muted)"><?= t('towed_at') ?></div>
        <div style="font-size:13px;font-weight:600"><?= e($towLog['towed_at']) ?></div>
        <div style="font-size:12px;color:var(--text-muted)"><?= t('officer') ?>: <?= e($towLog['officer_name']) ?></div>
      </div>
    </div>

    <?php if($towLog['status']==='active'): ?>
    <form method="POST" onsubmit="return confirm('<?= t('confirm_release') ?>?')">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="release">
      <input type="hidden" name="id" value="<?= $towLog['id'] ?>">
      <button type="submit" class="btn btn-success" style="width:100%;padding:14px;font-size:16px">✅ <?= t('release_vehicle') ?></button>
    </form>
    <?php endif; ?>
  </div>
</div>

<?php elseif ($action === 'list'): ?>
<!-- قائمة السحب -->
<div class="section-header">
  <div class="section-title">🚛 <?= t('tow_records') ?></div>
  <a href="<?= BASE_URL ?>/officer/tow.php" class="btn btn-primary">+ <?= t('new_tow') ?></a>
</div>
<?php if(empty($towLogs)): ?>
<div class="card"><div class="empty-state"><div class="empty-state-icon">🚛</div><h3><?= t('no_tow_records') ?></h3></div></div>
<?php else: ?>
<div class="card">
  <div class="table-wrapper">
    <table>
      <thead><tr><th>#</th><th><?= t('plate_number') ?></th><th><?= t('tow_reason') ?></th><th><?= t('status') ?></th><th><?= t('towed_at') ?></th><th><?= t('actions') ?></th></tr></thead>
      <tbody>
        <?php foreach($towLogs as $t): ?>
        <tr>
          <td style="font-family:monospace;font-size:12px">TOW-<?= str_pad($t['id'],6,'0',STR_PAD_LEFT) ?></td>
          <td><span style="font-family:monospace;font-weight:800"><?= e($t['plate_number']) ?></span></td>
          <td><?= e($t['reason']) ?></td>
          <td><?= $t['status']==='active' ? '<span class="badge badge-danger">🔴 '.t('tow_active').'</span>' : '<span class="badge badge-success">✅ '.t('tow_released').'</span>' ?></td>
          <td style="font-size:12px;color:var(--text-muted)"><?= e(substr($t['towed_at'],0,16)) ?></td>
          <td><a href="<?= BASE_URL ?>/officer/tow.php?action=view&id=<?= $t['id'] ?>" class="btn btn-sm btn-secondary">👁</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<?php else: ?>
<!-- نموذج سحب جديد -->
<div class="section-header">
  <div class="section-title">🚛 <?= t('new_tow') ?></div>
  <a href="<?= BASE_URL ?>/officer/tow.php?action=list" class="btn btn-secondary">📋 <?= t('tow_records') ?></a>
</div>

<?php foreach($errors as $e): ?><div class="alert alert-danger"><?= e($e) ?></div><?php endforeach; ?>

<div class="card" style="max-width:600px">
  <div class="card-header"><span class="card-title">🚛 <?= t('fill_tow_form') ?></span></div>
  <div class="card-body">
    <form method="POST" action="<?= BASE_URL ?>/officer/tow.php">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="save">

      <div class="form-group" style="margin-bottom:18px">
        <label class="form-label">🚗 <?= t('plate_number') ?> *</label>
        <input type="text" name="plate_number" class="form-control"
               value="<?= e($plate_prefill) ?>" placeholder="16-ABC-01"
               style="text-transform:uppercase;font-size:18px;letter-spacing:.08em;text-align:center;font-family:monospace"
               oninput="this.value=this.value.toUpperCase()" required>
      </div>

      <div class="form-group" style="margin-bottom:18px">
        <label class="form-label">⚠️ <?= t('tow_reason') ?> *</label>
        <select name="reason" class="form-control" required>
          <option value="">— <?= t('select') ?> —</option>
          <?php foreach($reasons as $key => $label): ?>
          <option value="<?= e($label) ?>"><?= e($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="form-group" style="margin-bottom:18px">
        <label class="form-label">🏢 <?= t('tow_location') ?></label>
        <input type="text" name="tow_location" class="form-control" placeholder="<?= t('tow_location_hint') ?>...">
      </div>

      <div class="form-group" style="margin-bottom:24px">
        <label class="form-label">📝 <?= t('notes') ?></label>
        <textarea name="notes" class="form-control" rows="3"></textarea>
      </div>

      <button type="submit" class="btn btn-danger" style="width:100%;padding:14px;font-size:16px">
        🚛 <?= t('execute_tow') ?>
      </button>
    </form>
  </div>
</div>
<?php endif; ?>

<style>@media print { .sidebar,.topbar,.btn,form{display:none!important;} }</style>

<?php require __DIR__ . '/../../app/Views/shared/layout_end.php'; ?>
