<?php $this->start('body'); ?>
<?php $f = $this->data['form']; ?>

<div class="d-flex align-items-center justify-content-between mb-3">
  <h5 class="mb-0 fw-semibold"><i class="fas fa-plus me-2 text-muted"></i>Record Fuel Entry</h5>
  <a href="<?= PROOT; ?>FuelEntries" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= $this->raw('fb_msg'); ?>

<div class="alert alert-info small">
  <i class="fas fa-info-circle me-1"></i>
  On save, this posts a journal automatically: <strong>Dr 5010 Fuel Expense · Cr Bank/Cash</strong> based on payment method.
  If the numbers are wrong, void the entry (which posts a reversing JE) and record a fresh one.
</div>

<form method="POST" action="<?= PROOT; ?>FuelEntries/save" class="card border-0 shadow-sm" autocomplete="off">
  <?= csrf_field(); ?>
  <div class="card-body">

    <h6 class="text-uppercase text-muted small mb-3">Truck · Driver · Trip</h6>
    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Truck <span class="text-danger">*</span></label>
        <select name="truck_id" id="truckSel" class="form-select" required>
          <option value="">— select truck —</option>
          <?php foreach ($this->data['trucks'] as $t): ?>
            <option value="<?= (int)$t['c0d']; ?>"
                    data-tank="<?= (int)$t['fuel_tank_liters']; ?>"
                    data-odo="<?= (int)$t['current_odometer']; ?>"
                    <?= ($f['truck_id'] ?? '')==$t['c0d']?'selected':''; ?>>
              <?= htmlspecialchars($t['reg_no']); ?><?php if ($t['make']): ?> · <?= htmlspecialchars(trim($t['make'] . ' ' . $t['model'])); ?><?php endif; ?>
            </option>
          <?php endforeach; ?>
        </select>
        <div id="truckHint" class="form-text small mt-1"></div>
      </div>
      <div class="col-md-4">
        <label class="form-label">Driver</label>
        <select name="driver_id" class="form-select">
          <option value="">— none —</option>
          <?php foreach ($this->data['drivers'] as $d): ?>
            <option value="<?= (int)$d['c0d']; ?>" <?= ($f['driver_id'] ?? '')==$d['c0d']?'selected':''; ?>>
              <?= htmlspecialchars($d['full_name']); ?><?php if ($d['employee_no']): ?> · <?= htmlspecialchars($d['employee_no']); ?><?php endif; ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Trip (optional)</label>
        <select name="trip_id" class="form-select">
          <option value="">— none —</option>
          <?php foreach ($this->data['trips'] as $t): ?>
            <option value="<?= (int)$t['c0d']; ?>" <?= ($f['trip_id'] ?? '')==$t['c0d']?'selected':''; ?>>
              <?= htmlspecialchars($t['trip_no']); ?><?php if ($t['cargo_description']): ?> · <?= htmlspecialchars($t['cargo_description']); ?><?php endif; ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <hr class="my-4">

    <h6 class="text-uppercase text-muted small mb-3">Refuel Details</h6>
    <div class="row g-3">
      <div class="col-md-3">
        <label class="form-label">Date <span class="text-danger">*</span></label>
        <input type="date" name="entry_date" class="form-control" required value="<?= htmlspecialchars($f['entry_date'] ?? date('Y-m-d')); ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Time</label>
        <input type="time" name="entry_time" class="form-control" value="<?= htmlspecialchars($f['entry_time'] ?? ''); ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Fuel type</label>
        <select name="fuel_type" class="form-select">
          <?php foreach (['diesel'=>'Diesel','petrol'=>'Petrol','other'=>'Other'] as $k=>$v): ?>
            <option value="<?= $k; ?>" <?= ($f['fuel_type'] ?? 'diesel')===$k?'selected':''; ?>><?= $v; ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-5">
        <label class="form-label">Station name</label>
        <input type="text" name="station_name" class="form-control" value="<?= htmlspecialchars($f['station_name'] ?? ''); ?>" placeholder="e.g. Puma Nyerere Road">
      </div>

      <div class="col-md-3">
        <label class="form-label">Litres <span class="text-danger">*</span></label>
        <input type="text" name="liters" class="form-control js-liters" required value="<?= htmlspecialchars((string)($f['liters'] ?? '')); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Price per litre</label>
        <input type="text" name="price_per_liter" class="form-control js-money" value="<?= htmlspecialchars((string)($f['price_per_liter'] ?? '')); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Total amount <span class="text-danger">*</span></label>
        <input type="text" name="gross_amount" class="form-control js-money" required value="<?= htmlspecialchars((string)($f['gross_amount'] ?? '')); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Currency</label>
        <select name="currency" class="form-select">
          <?php foreach (['TZS','USD','EUR','KES','UGX'] as $c): ?>
            <option value="<?= $c; ?>" <?= ($f['currency'] ?? 'TZS')===$c?'selected':''; ?>><?= $c; ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-4">
        <label class="form-label">Odometer at refuel (km)</label>
        <input type="text" name="odometer_reading" id="odoInput" class="form-control js-int" value="<?= htmlspecialchars((string)($f['odometer_reading'] ?? '')); ?>">
        <div id="odoHint" class="form-text small mt-1"></div>
      </div>
      <div class="col-md-4">
        <label class="form-label">Station location</label>
        <input type="text" name="station_location" class="form-control" value="<?= htmlspecialchars($f['station_location'] ?? ''); ?>" placeholder="City / area">
      </div>
      <div class="col-md-4">
        <label class="form-label">Receipt #</label>
        <input type="text" name="receipt_no" class="form-control" value="<?= htmlspecialchars($f['receipt_no'] ?? ''); ?>">
      </div>
    </div>

    <hr class="my-4">

    <h6 class="text-uppercase text-muted small mb-3">Payment</h6>
    <div class="row g-3">
      <div class="col-md-3"><label class="form-label">Payment method <span class="text-danger">*</span></label>
        <select name="payment_method" class="form-select" required>
          <?php foreach (['cash'=>'Cash','petty_cash'=>'Petty Cash','mobile_money'=>'Mobile Money','bank_transfer'=>'Bank Transfer','cheque'=>'Cheque','fuel_card'=>'Fuel Card'] as $k=>$v): ?>
            <option value="<?= $k; ?>" <?= ($f['payment_method'] ?? 'cash')===$k?'selected':''; ?>><?= $v; ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-4"><label class="form-label">Payment reference</label>
        <input type="text" name="payment_reference" class="form-control" value="<?= htmlspecialchars($f['payment_reference'] ?? ''); ?>" placeholder="Card #, M-Pesa txn, cheque #"></div>
      <div class="col-md-5"><label class="form-label">Notes</label>
        <input type="text" name="notes" class="form-control" value="<?= htmlspecialchars($f['notes'] ?? ''); ?>"></div>
    </div>

  </div>
  <div class="card-footer bg-white d-flex justify-content-end gap-2 py-3">
    <a href="<?= PROOT; ?>FuelEntries" class="btn btn-outline-secondary">Cancel</a>
    <button class="btn btn-primary"><i class="fas fa-save me-1"></i>Save &amp; post JE</button>
  </div>
</form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
document.querySelectorAll('.js-liters').forEach(el => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 3 }));
document.querySelectorAll('.js-money').forEach(el  => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 2 }));
document.querySelectorAll('.js-int').forEach(el    => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 0 }));

// Auto-compute Gross = Litres × PPL as user types (only when gross is empty)
const litersIn = document.querySelector('input[name="liters"]');
const pplIn    = document.querySelector('input[name="price_per_liter"]');
const grossIn  = document.querySelector('input[name="gross_amount"]');
function autoGross() {
    if (!litersIn || !pplIn || !grossIn) return;
    const L = parseFloat((litersIn.value || '').replace(/,/g, '')) || 0;
    const P = parseFloat((pplIn.value    || '').replace(/,/g, '')) || 0;
    if (L > 0 && P > 0 && !grossIn.value.trim()) {
        const total = (L * P).toFixed(2);
        // apply through Cleave — direct assignment might get overwritten
        grossIn.value = total;
        grossIn.dispatchEvent(new Event('input', { bubbles: true }));
    }
}
litersIn?.addEventListener('blur', autoGross);
pplIn?.addEventListener('blur',    autoGross);

// Truck hint — show tank + current odo
const truckSel = document.getElementById('truckSel');
const hint     = document.getElementById('truckHint');
const odoInput = document.getElementById('odoInput');
const odoHint  = document.getElementById('odoHint');
function refreshTruckHint() {
    const opt = truckSel.options[truckSel.selectedIndex]; if (!opt || !opt.value) { hint.innerHTML = ''; odoHint.innerHTML=''; return; }
    const tank = opt.getAttribute('data-tank');
    const odo  = opt.getAttribute('data-odo');
    hint.innerHTML = '<i class="fas fa-info-circle fa-xs me-1"></i>' +
        (tank && parseInt(tank) > 0 ? 'Tank capacity: ' + Number(tank).toLocaleString() + ' L · ' : '') +
        (odo ? 'Last odometer: ' + Number(odo).toLocaleString() + ' km' : '');
    if (odo && odoInput && !odoInput.value.trim()) {
        odoHint.innerHTML = 'Suggest odometer ≥ ' + Number(odo).toLocaleString();
    }
}
truckSel?.addEventListener('change', refreshTruckHint);
refreshTruckHint();
</script>
<?php $this->end(); ?>
