<?php
// public/officer/payment.php — دفع رسوم المخالفة
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/Violation.php';

$user      = requireAuth(['officer']);
$id        = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$violation = $id ? Violation::find($id) : null;

if (!$violation) {
    flash('officer_msg', t('violation_not_found'), 'danger');
    redirect(BASE_URL . '/officer/violations.php');
}

if ($violation['status'] !== 'unpaid') {
    flash('officer_msg', t('already_processed'), 'info');
    redirect(BASE_URL . '/officer/violation.php?action=view&id=' . $id);
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $method = $_POST['payment_method'] ?? 'cash';
    $ref    = trim($_POST['reference'] ?? '');

    $allowed = ['cash','ccp','baridimob','dahabia'];
    if (!in_array($method, $allowed, true)) {
        $errors[] = t('invalid_payment_method');
    }

    if (empty($errors)) {
        Violation::markPaid($id, $user['id'], $method, $ref ?: null);
        flash('officer_msg', t('payment_success'), 'success');
        redirect(BASE_URL . '/officer/violation.php?action=view&id=' . $id);
    }
}

$methodLabels = [
    'ar' => ['cash'=>'نقداً','ccp'=>'CCP بريد','baridimob'=>'BaridiMob','dahabia'=>'بطاقة داهبية'],
    'en' => ['cash'=>'Cash','ccp'=>'CCP Post','baridimob'=>'BaridiMob','dahabia'=>'Dahabia Card'],
    'fr' => ['cash'=>'Espèces','ccp'=>'CCP Poste','baridimob'=>'BaridiMob','dahabia'=>'Carte Dahabia'],
];
$methods = $methodLabels[lang()] ?? $methodLabels['ar'];

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

<div class="section-header">
  <div class="section-title">💳 <?= t('pay_fine') ?></div>
  <a href="<?= BASE_URL ?>/officer/violation.php?action=view&id=<?= $id ?>" class="btn btn-secondary">← <?= t('back') ?></a>
</div>

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

<div class="card" style="max-width:540px;margin:0 auto">
  <!-- ملخص المخالفة -->
  <div style="background:linear-gradient(135deg,var(--accent),#0f4c9e);color:#fff;padding:24px;border-radius:var(--radius-lg) var(--radius-lg) 0 0">
    <div style="font-size:12px;opacity:.7;margin-bottom:4px">📋 N° VV-<?= str_pad($violation['id'],6,'0',STR_PAD_LEFT) ?></div>
    <div style="font-size:20px;font-weight:800;margin-bottom:4px"><?= e($violation['violation_type']) ?></div>
    <div style="font-family:monospace;font-size:16px;opacity:.85"><?= e($violation['plate_number']) ?> — <?= e($violation['brand'].' '.$violation['model']) ?></div>
    <div style="margin-top:16px;background:rgba(255,255,255,.15);border-radius:10px;padding:14px;text-align:center">
      <div style="font-size:12px;opacity:.8"><?= t('fine_amount') ?></div>
      <div style="font-size:36px;font-weight:900"><?= number_format($violation['amount'],2) ?> <span style="font-size:18px">دج</span></div>
    </div>
  </div>

  <div class="card-body" style="padding:24px">
    <form method="POST" action="<?= BASE_URL ?>/officer/payment.php">
      <?= csrfField() ?>
      <input type="hidden" name="id" value="<?= $violation['id'] ?>">

      <!-- طريقة الدفع -->
      <div class="form-group" style="margin-bottom:20px">
        <label class="form-label" style="font-weight:700;margin-bottom:12px">💳 <?= t('payment_method') ?></label>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
          <?php foreach($methods as $key => $label): ?>
          <?php $icons = ['cash'=>'💵','ccp'=>'📮','baridimob'=>'📱','dahabia'=>'💳']; ?>
          <label style="display:flex;align-items:center;gap:10px;background:var(--bg-primary);border:2px solid var(--border);border-radius:10px;padding:14px;cursor:pointer;transition:all .2s" class="payment-method-card">
            <input type="radio" name="payment_method" value="<?= $key ?>" <?= $key==='cash'?'checked':'' ?> style="display:none" onchange="highlightCard(this)">
            <span style="font-size:22px"><?= $icons[$key] ?></span>
            <span style="font-weight:600;font-size:14px"><?= e($label) ?></span>
          </label>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- رقم المرجع -->
      <div class="form-group" style="margin-bottom:24px" id="refGroup">
        <label class="form-label"><?= t('reference_number') ?> <span style="color:var(--text-muted);font-size:12px">(<?= t('optional') ?>)</span></label>
        <input type="text" name="reference" class="form-control" placeholder="CCP-XXXXX / رقم الوصل">
      </div>

      <button type="submit" class="btn btn-primary" style="width:100%;padding:15px;font-size:17px;font-weight:700">
        ✅ <?= t('confirm_payment') ?>
      </button>
    </form>
  </div>
</div>

<script>
function highlightCard(radio) {
    document.querySelectorAll('.payment-method-card').forEach(c => {
        c.style.borderColor = 'var(--border)';
        c.style.background  = 'var(--bg-primary)';
    });
    const card = radio.closest('.payment-method-card');
    card.style.borderColor = 'var(--accent)';
    card.style.background  = 'rgba(26,86,219,0.07)';
}
// تحديد الأول افتراضياً
document.querySelector('input[type=radio][value=cash]').dispatchEvent(new Event('change'));
</script>

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