<?php
// public/officer/violation.php — تحرير محضر المخالفة
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/Vehicle.php';
require_once __DIR__.'/../../app/Models/Violation.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'] ?? ''));
    $type   = trim($_POST['violation_type'] ?? '');
    $amount = (float)($_POST['amount'] ?? 0);
    $notes  = trim($_POST['notes'] ?? '');

    if (!$plate || !$type || $amount <= 0) {
        $errors[] = t('fill_all_fields');
    } else {
        $vehicle = Vehicle::findByPlate($plate);
        if (!$vehicle) {
            $errors[] = t('vehicle_not_found');
        } else {
            $vid = Violation::create([
                'officer_id'     => $user['id'],
                'vehicle_id'     => $vehicle['id'],
                'plate_number'   => $plate,
                'violation_type' => $type,
                'amount'         => $amount,
                'notes'          => $notes,
            ]);
            flash('officer_msg', t('violation_issued'), 'success');
            redirect(BASE_URL . '/officer/violation.php?action=view&id=' . $vid);
        }
    }
}

// --- POST: إلغاء مخالفة ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'cancel') {
    verifyCsrf();
    $id = (int)$_POST['id'];
    Violation::cancel($id);
    flash('officer_msg', t('violation_cancelled'), 'success');
    redirect(BASE_URL . '/officer/violations.php');
}

// --- GET: عرض مخالفة واحدة ---
$violation = null;
if ($action === 'view' && isset($_GET['id'])) {
    $violation = Violation::find((int)$_GET['id']);
}

// قائمة أنواع المخالفات
$violationTypes = [
    'ar' => [
        'speeding'          => 'تجاوز السرعة',
        'red_light'         => 'تجاوز الإشارة الحمراء',
        'no_insurance'      => 'عدم حمل التأمين',
        'no_gray_card'      => 'عدم حمل البطاقة الرمادية',
        'expired_technical' => 'انتهاء الفحص التقني',
        'wrong_parking'     => 'الوقوف في مكان محظور',
        'no_seatbelt'       => 'عدم ارتداء حزام الأمان',
        'phone_driving'     => 'استخدام الهاتف أثناء القيادة',
        'no_license'        => 'القيادة بدون رخصة',
        'other'             => 'أخرى',
    ],
    'en' => [
        'speeding'          => 'Speeding',
        'red_light'         => 'Red Light Violation',
        'no_insurance'      => 'No Insurance',
        'no_gray_card'      => 'No Gray Card',
        'expired_technical' => 'Expired Technical',
        'wrong_parking'     => 'Wrong Parking',
        'no_seatbelt'       => 'No Seatbelt',
        'phone_driving'     => 'Phone While Driving',
        'no_license'        => 'No License',
        'other'             => 'Other',
    ],
    'fr' => [
        'speeding'          => 'Excès de vitesse',
        'red_light'         => 'Passage au rouge',
        'no_insurance'      => 'Pas d\'assurance',
        'no_gray_card'      => 'Pas de carte grise',
        'expired_technical' => 'Contrôle technique expiré',
        'wrong_parking'     => 'Stationnement interdit',
        'no_seatbelt'       => 'Pas de ceinture',
        'phone_driving'     => 'Téléphone au volant',
        'no_license'        => 'Sans permis',
        'other'             => 'Autre',
    ],
];
$vtypes = $violationTypes[lang()] ?? $violationTypes['ar'];

// قيم المخالفات الافتراضية (دج)
$defaultAmounts = [
    'speeding'=>3000,'red_light'=>5000,'no_insurance'=>6000,
    'no_gray_card'=>2000,'expired_technical'=>2000,'wrong_parking'=>1500,
    'no_seatbelt'=>1000,'phone_driving'=>2000,'no_license'=>10000,'other'=>1000,
];

$plate_prefill = strtoupper(trim($_GET['plate'] ?? ''));

$pageTitle  = t('new_violation');
$activePage = BASE_URL . '/officer/violation.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 foreach($errors as $e): ?>
<div class="alert alert-danger"><?= e($e) ?></div>
<?php endforeach; ?>

<?php if ($action === 'view' && $violation): ?>
<!-- ===== عرض المحضر ===== -->
<div class="section-header">
  <div class="section-title">📋 <?= t('violation_receipt') ?> #<?= $violation['id'] ?></div>
  <div style="display:flex;gap:8px">
    <a href="<?= BASE_URL ?>/officer/violations.php" 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:640px;margin:0 auto" id="violation-print">
  <!-- Header محضر -->
  <div style="background:linear-gradient(135deg,#0f2140,#1a3a6e);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:11px;opacity:.6;margin-bottom:16px">Direction Générale de la Sûreté Nationale</div>
    <div style="font-size:22px;font-weight:800">📋 محضر مخالفة مرورية</div>
    <div style="font-size:13px;opacity:.75;margin-top:6px">Procès-verbal d'infraction routière</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">
      N° VV-<?= str_pad($violation['id'], 6, '0', STR_PAD_LEFT) ?>
    </div>
  </div>

  <div class="card-body" style="padding:24px">
    <!-- معلومات السيارة -->
    <div style="background:var(--bg-primary);border-radius:10px;padding:16px;margin-bottom:16px">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:12px">🚗 <?= t('vehicle_info') ?></div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
        <div><div style="font-size:11px;color:var(--text-muted)"><?= t('plate_number') ?></div><div style="font-family:monospace;font-weight:800;font-size:18px;margin-top:2px"><?= e($violation['plate_number']) ?></div></div>
        <div><div style="font-size:11px;color:var(--text-muted)"><?= t('brand') ?> / <?= t('model') ?></div><div style="font-weight:600;margin-top:2px"><?= e($violation['brand'].' '.$violation['model']) ?></div></div>
      </div>
    </div>

    <!-- المخالفة -->
    <div style="background:var(--bg-primary);border-radius:10px;padding:16px;margin-bottom:16px">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:12px">⚖️ <?= t('violation_details') ?></div>
      <div style="margin-bottom:10px"><strong><?= e($violation['violation_type']) ?></strong></div>
      <?php if($violation['notes']): ?>
      <div style="font-size:13px;color:var(--text-muted);margin-bottom:10px"><?= e($violation['notes']) ?></div>
      <?php endif; ?>
      <div style="display:flex;align-items:center;justify-content:space-between;background:<?= $violation['status']==='paid'?'#d1fae5':($violation['status']==='cancelled'?'#f3f4f6':'#fef3c7') ?>;border-radius:8px;padding:12px 16px">
        <div style="font-size:13px;color:var(--text-muted)"><?= t('fine_amount') ?></div>
        <div style="font-size:26px;font-weight:900;color:<?= $violation['status']==='paid'?'#065f46':'#92400e' ?>"><?= number_format($violation['amount'],2) ?> <span style="font-size:14px">دج</span></div>
      </div>
    </div>

    <!-- الحالة -->
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <div>
        <div style="font-size:11px;color:var(--text-muted)"><?= t('status') ?></div>
        <?php if($violation['status']==='paid'): ?>
          <span class="badge badge-success">✅ <?= t('paid') ?></span>
        <?php elseif($violation['status']==='cancelled'): ?>
          <span class="badge badge-info">❌ <?= t('cancelled') ?></span>
        <?php else: ?>
          <span class="badge badge-warning">⏳ <?= t('unpaid') ?></span>
        <?php endif; ?>
      </div>
      <div style="text-align:<?= lang()==='ar'?'left':'right' ?>">
        <div style="font-size:11px;color:var(--text-muted)"><?= t('issued_at') ?></div>
        <div style="font-size:13px;font-weight:600"><?= e($violation['issued_at']) ?></div>
        <div style="font-size:12px;color:var(--text-muted)"><?= t('officer') ?>: <?= e($violation['officer_name']) ?></div>
      </div>
    </div>

    <!-- أزرار -->
    <div style="display:flex;gap:10px;flex-wrap:wrap">
      <?php if($violation['status']==='unpaid'): ?>
      <a href="<?= BASE_URL ?>/officer/payment.php?id=<?= $violation['id'] ?>" class="btn btn-primary">💳 <?= t('pay_fine') ?></a>
      <form method="POST" style="display:inline" onsubmit="return confirm('<?= t('confirm') ?>?')">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="cancel">
        <input type="hidden" name="id" value="<?= $violation['id'] ?>">
        <button type="submit" class="btn btn-danger">✖ <?= t('cancel_violation') ?></button>
      </form>
      <?php endif; ?>
      <a href="<?= BASE_URL ?>/officer/violations.php" class="btn btn-secondary">← <?= t('back') ?></a>
    </div>
  </div>
</div>

<?php else: ?>
<!-- ===== نموذج مخالفة جديدة ===== -->
<div class="section-header">
  <div class="section-title">📋 <?= t('new_violation') ?></div>
  <a href="<?= BASE_URL ?>/officer/violations.php" class="btn btn-secondary">📋 <?= t('violations_list') ?></a>
</div>

<div class="card" style="max-width:640px">
  <div class="card-header"><span class="card-title">📝 <?= t('fill_violation_form') ?></span></div>
  <div class="card-body">
    <form method="POST" action="<?= BASE_URL ?>/officer/violation.php" id="violationForm">
      <?= 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" id="plateInput" 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"
               required>
      </div>

      <!-- نوع المخالفة -->
      <div class="form-group" style="margin-bottom:18px">
        <label class="form-label">⚖️ <?= t('violation_type') ?> *</label>
        <select name="violation_type" id="vtypeSelect" class="form-control" required onchange="setDefaultAmount(this.value)">
          <option value="">— <?= t('select') ?> —</option>
          <?php foreach($vtypes as $key => $label): ?>
          <option value="<?= e($label) ?>" data-amount="<?= $defaultAmounts[$key] ?? 1000 ?>"><?= e($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- المبلغ -->
      <div class="form-group" style="margin-bottom:18px">
        <label class="form-label">💰 <?= t('fine_amount') ?> (دج) *</label>
        <input type="number" name="amount" id="amountInput" class="form-control"
               value="1000" min="100" step="100" required
               style="font-size:20px;font-weight:700;text-align:center">
      </div>

      <!-- ملاحظات -->
      <div class="form-group" style="margin-bottom:24px">
        <label class="form-label">📝 <?= t('notes') ?></label>
        <textarea name="notes" class="form-control" rows="3" placeholder="<?= t('optional_notes') ?>..."></textarea>
      </div>

      <button type="submit" class="btn btn-primary" style="width:100%;padding:14px;font-size:16px">
        📋 <?= t('issue_violation') ?>
      </button>
    </form>
  </div>
</div>

<script>
const amounts = <?= json_encode($defaultAmounts) ?>;
const typeKeys = <?= json_encode(array_keys($vtypes)) ?>;
function setDefaultAmount(label) {
    const sel = document.getElementById('vtypeSelect');
    const opt = sel.options[sel.selectedIndex];
    const amt = opt.getAttribute('data-amount');
    if(amt) document.getElementById('amountInput').value = amt;
}
document.getElementById('plateInput').addEventListener('input', function(){
    this.value = this.value.toUpperCase();
});
</script>
<?php endif; ?>

<style>
@media print {
  .sidebar, .topbar, .btn, form { display:none!important; }
  .card { box-shadow:none!important; border:1px solid #ccc!important; }
}
</style>

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