<?php $this->start('body'); ?>
<?php $e = $this->data['e']; $history = $this->data['history']; ?>
<?php $bg = ['draft'=>'secondary','submitted'=>'warning','reviewed'=>'info','approved'=>'primary','paid'=>'success','rejected'=>'danger','cancelled'=>'dark'][$e['status']] ?? 'secondary'; ?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-receipt me-2 text-muted"></i><?= htmlspecialchars($e['expense_no']); ?>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($e['status']); ?></span>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars($e['type_name']); ?>
      <?php if ($e['gl_code']): ?> · <span class="font-monospace"><?= htmlspecialchars($e['gl_code']); ?> <?= htmlspecialchars($e['gl_name']); ?></span><?php endif; ?>
      · <?= humanDate($e['expense_date']); ?>
    </div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a href="<?= PROOT; ?>Expenses" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <?php if (!in_array($e['status'], ['approved','paid','rejected','cancelled'], true)): ?>
      <a href="<?= PROOT; ?>Expenses/edit/<?= (int)$e['c0d']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-pen me-1"></i>Edit</a>
    <?php endif; ?>
  </div>
</div>

<?= flashHtml(); ?>

<?php if ($e['status'] === 'rejected' && $e['rejection_reason']): ?>
  <div class="alert alert-danger py-2 small"><i class="fas fa-times-circle me-1"></i><strong>Rejected:</strong> <?= htmlspecialchars($e['rejection_reason']); ?></div>
<?php endif; ?>

<!-- ── Lifecycle action bar ────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>

    <?php if ($e['status'] === 'draft'): ?>
      <button type="button" class="btn btn-sm btn-primary" onclick="act('submit')"><i class="fas fa-paper-plane me-1"></i>Submit for review</button>
    <?php endif; ?>
    <?php if ($e['status'] === 'submitted'): ?>
      <button type="button" class="btn btn-sm btn-info text-white" onclick="act('review')"><i class="fas fa-search me-1"></i>Mark reviewed</button>
    <?php endif; ?>
    <?php if ($e['status'] === 'reviewed'): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="act('approve')" title="Posts JE Dr Expense / Cr AP"><i class="fas fa-check me-1"></i>Approve &amp; post journal</button>
    <?php endif; ?>
    <?php if ($e['status'] === 'approved'): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="doPay()" title="Posts JE Dr AP / Cr Bank"><i class="fas fa-money-bill-wave me-1"></i>Record payment</button>
    <?php endif; ?>

    <?php if (in_array($e['status'], ['draft','submitted','reviewed'], true)): ?>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="doReject()"><i class="fas fa-times me-1"></i>Reject</button>
    <?php endif; ?>
    <?php if (in_array($e['status'], ['draft','submitted','reviewed'], true)): ?>
      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="act('cancel')"><i class="fas fa-ban me-1"></i>Cancel</button>
    <?php endif; ?>

    <span class="ms-auto text-muted small">
      <strong><?= htmlspecialchars($e['currency']); ?> <?= number_format((float)$e['gross_amount'], 2, '.', ','); ?></strong>
    </span>
  </div>
</div>

<div class="row g-3">
  <!-- ── Details ────────────────────────────────────────── -->
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Details</h6>
        <dl class="row mb-0">
          <dt class="col-4 text-muted fw-normal">Type</dt>       <dd class="col-8"><?= htmlspecialchars($e['type_name']); ?> <span class="text-muted small">(<?= htmlspecialchars($e['scope']); ?>)</span></dd>
          <dt class="col-4 text-muted fw-normal">GL account</dt> <dd class="col-8 font-monospace small"><?= htmlspecialchars(($e['gl_code'] ?? '') . ' ' . ($e['gl_name'] ?? '—')); ?></dd>
          <dt class="col-4 text-muted fw-normal">Description</dt><dd class="col-8"><?= htmlspecialchars($e['description'] ?: '—'); ?></dd>

          <hr class="my-2">
          <dt class="col-4 text-muted fw-normal">Gross</dt>  <dd class="col-8"><?= htmlspecialchars($e['currency']); ?> <?= number_format((float)$e['gross_amount'], 2, '.', ','); ?></dd>
          <?php if ((float)$e['vat_amount'] > 0): ?>
            <dt class="col-4 text-muted fw-normal">VAT</dt><dd class="col-8"><?= htmlspecialchars($e['currency']); ?> <?= number_format((float)$e['vat_amount'], 2, '.', ','); ?></dd>
            <dt class="col-4 text-muted fw-normal">Net</dt><dd class="col-8"><?= htmlspecialchars($e['currency']); ?> <?= number_format((float)$e['net_amount'], 2, '.', ','); ?></dd>
          <?php endif; ?>

          <hr class="my-2">
          <?php if ($e['truck_reg']):    ?><dt class="col-4 text-muted fw-normal">Truck</dt>   <dd class="col-8"><a href="<?= PROOT; ?>Trucks/view/<?= (int)$e['truck_id']; ?>"><?= htmlspecialchars($e['truck_reg']); ?></a></dd><?php endif; ?>
          <?php if ($e['driver_name']):  ?><dt class="col-4 text-muted fw-normal">Driver</dt>  <dd class="col-8"><a href="<?= PROOT; ?>Drivers/view/<?= (int)$e['driver_id']; ?>"><?= htmlspecialchars($e['driver_name']); ?></a></dd><?php endif; ?>
          <?php if ($e['trip_no']):      ?><dt class="col-4 text-muted fw-normal">Trip</dt>    <dd class="col-8"><a href="<?= PROOT; ?>Trips/view/<?= (int)$e['trip_id']; ?>"><?= htmlspecialchars($e['trip_no']); ?></a></dd><?php endif; ?>
          <?php if ($e['customer_name']):?><dt class="col-4 text-muted fw-normal">Customer</dt><dd class="col-8"><a href="<?= PROOT; ?>Customers/view/<?= (int)$e['customer_id']; ?>"><?= htmlspecialchars($e['customer_name']); ?></a></dd><?php endif; ?>
          <?php if ($e['vendor_name']):  ?><dt class="col-4 text-muted fw-normal">Vendor</dt>  <dd class="col-8"><?= htmlspecialchars($e['vendor_name']); ?></dd><?php endif; ?>

          <hr class="my-2">
          <?php if ($e['payment_method']): ?>
            <dt class="col-4 text-muted fw-normal">Payment method</dt><dd class="col-8"><?= htmlspecialchars(ucwords(str_replace('_',' ',$e['payment_method']))); ?></dd>
            <?php if ($e['payment_reference']): ?><dt class="col-4 text-muted fw-normal">Payment ref</dt><dd class="col-8 font-monospace small"><?= htmlspecialchars($e['payment_reference']); ?></dd><?php endif; ?>
          <?php endif; ?>

          <?php if ($e['receipt_url']): ?><dt class="col-4 text-muted fw-normal">Receipt</dt><dd class="col-8"><a href="<?= htmlspecialchars($e['receipt_url']); ?>" target="_blank"><i class="fas fa-external-link-alt me-1"></i><?= htmlspecialchars($e['receipt_file_name'] ?: 'View'); ?></a></dd><?php endif; ?>

          <?php if ($e['accrual_je_no']): ?><dt class="col-4 text-muted fw-normal">Accrual JE</dt><dd class="col-8"><a href="<?= PROOT; ?>Journals/view/<?= (int)$e['accrual_je_id']; ?>" class="font-monospace"><?= htmlspecialchars($e['accrual_je_no']); ?></a></dd><?php endif; ?>
          <?php if ($e['payment_je_no']): ?><dt class="col-4 text-muted fw-normal">Payment JE</dt><dd class="col-8"><a href="<?= PROOT; ?>Journals/view/<?= (int)$e['payment_je_id']; ?>" class="font-monospace"><?= htmlspecialchars($e['payment_je_no']); ?></a></dd><?php endif; ?>

          <?php if ($e['notes']): ?><hr class="my-2"><dt class="col-4 text-muted fw-normal">Notes</dt><dd class="col-8"><?= nl2br(htmlspecialchars($e['notes'])); ?></dd><?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <!-- ── Approval timeline ───────────────────────────── -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3"><i class="fas fa-history me-1"></i>Approval History</h6>
        <?php if (empty($history)): ?>
          <p class="text-muted small mb-0 fst-italic">No activity yet.</p>
        <?php else: ?>
          <ul class="list-unstyled mb-0 small">
            <?php foreach ($history as $h): ?>
              <li class="mb-3 ps-3" style="border-left: 2px solid var(--pacific-navy);">
                <div class="fw-semibold" style="text-transform:capitalize;">
                  <?= htmlspecialchars(str_replace('_',' ',$h['to_status'])); ?>
                  <?php if ($h['from_status']): ?><span class="text-muted small">← <?= htmlspecialchars(str_replace('_',' ',$h['from_status'])); ?></span><?php endif; ?>
                </div>
                <div class="text-muted small"><?= humanDateTime($h['action_at']); ?><?php if ($h['actor_name']): ?> · <?= htmlspecialchars($h['actor_name']); ?><?php endif; ?></div>
                <?php if ($h['note']): ?><div class="small mt-1"><?= htmlspecialchars($h['note']); ?></div><?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<div class="text-end mt-3">
  <button type="button" class="btn btn-sm btn-outline-danger" onclick="doDelete()"><i class="fas fa-trash me-1"></i>Delete record</button>
</div>

<!-- Hidden action forms -->
<form id="actForm" method="POST" action="" class="d-none">
  <?= csrf_field(); ?>
  <input type="hidden" name="rejection_reason"  id="fReason">
  <input type="hidden" name="payment_method"    id="fPayMethod">
  <input type="hidden" name="payment_reference" id="fPayRef">
  <input type="hidden" name="payment_date"      id="fPayDate">
</form>
<form id="delForm" method="POST" action="<?= PROOT; ?>Expenses/delete/<?= (int)$e['c0d']; ?>" class="d-none"><?= csrf_field(); ?></form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const EXP_ID = <?= (int)$e['c0d']; ?>;
const PROOT  = '<?= PROOT; ?>';
const CURR   = '<?= htmlspecialchars($e['currency']); ?>';

function submitAct(verb, extra) {
    const f = document.getElementById('actForm');
    f.action = PROOT + 'Expenses/' + verb + '/' + EXP_ID;
    if (extra) for (const [k, v] of Object.entries(extra)) {
        const el = document.getElementById(k);
        if (el) el.value = v;
    }
    f.submit();
}

function act(verb) {
    const cfg = {
        submit:  { title: 'Submit for review?',  msg: 'Sends this expense to Accountant for review.',                    btn: 'Submit',  cls: 'btn-primary',  colour: 'blue'   },
        review:  { title: 'Mark as reviewed?',   msg: 'Confirms details are correct and passes to Finance Manager.',      btn: 'Review',  cls: 'btn-info',     colour: 'blue'   },
        approve: { title: 'Approve expense?',    msg: 'This posts a journal entry: <strong>Dr <?= htmlspecialchars($e['gl_code'] ?: '—'); ?></strong> / <strong>Cr 2010 Accounts Payable</strong>.', btn: 'Approve &amp; post JE', cls: 'btn-success', colour: 'green'  },
        cancel:  { title: 'Cancel this expense?',msg: 'Marks the expense cancelled. History preserved.',                  btn: 'Cancel',  cls: 'btn-warning',  colour: 'orange' }
    }[verb];
    $.confirm({
        title: cfg.title, content: cfg.msg, type: cfg.colour,
        buttons: { go: { text: cfg.btn, btnClass: cfg.cls, action: () => submitAct(verb) }, back: function () {} }
    });
}

function doReject() {
    $.confirm({
        title: 'Reject this expense?',
        content: '<label class="form-label small">Reason for rejection <span class="text-danger">*</span></label><textarea id="rejReason" class="form-control form-control-sm" rows="3" placeholder="Why is this being rejected?"></textarea>',
        type: 'red',
        buttons: {
            reject: { text: 'Reject', btnClass: 'btn-danger', action: function () {
                const r = document.getElementById('rejReason').value.trim();
                if (!r) { $.alert('Please enter a reason.'); return false; }
                submitAct('reject', { fReason: r });
            }},
            back: function () {}
        }
    });
}

function doPay() {
    const currentMethod = <?= json_encode($e['payment_method'] ?? ''); ?>;
    const methods = [
        ['cash','Cash'],['petty_cash','Petty Cash'],['mobile_money','Mobile Money'],
        ['bank_transfer','Bank Transfer'],['cheque','Cheque'],['fuel_card','Fuel Card']
    ];
    const opts = methods.map(m => `<option value="${m[0]}" ${m[0]===currentMethod ? 'selected':''}>${m[1]}</option>`).join('');
    $.confirm({
        title: 'Record payment',
        content: `
            <div class="mb-2 small text-muted">Posts JE: Dr 2010 AP / Cr the account below.</div>
            <label class="form-label small mb-1">Payment method <span class="text-danger">*</span></label>
            <select id="payMethod" class="form-select form-select-sm mb-2">${opts}</select>
            <label class="form-label small mb-1">Payment reference</label>
            <input type="text" id="payRef" class="form-control form-control-sm mb-2" placeholder="Cheque #, M-Pesa txn, etc">
            <label class="form-label small mb-1">Payment date</label>
            <input type="date" id="payDate" class="form-control form-control-sm" value="<?= date('Y-m-d'); ?>">
        `,
        type: 'green',
        buttons: {
            pay: { text: 'Post payment JE', btnClass: 'btn-success', action: function () {
                submitAct('pay', {
                    fPayMethod: document.getElementById('payMethod').value,
                    fPayRef:    document.getElementById('payRef').value,
                    fPayDate:   document.getElementById('payDate').value
                });
            }},
            back: function () {}
        }
    });
}

function doDelete() {
    $.confirm({
        title: 'Delete this expense?',
        content: 'Soft-deletes the record entirely. If a JE has been posted, it will remain in the ledger.',
        type: 'red',
        buttons: {
            remove: { text: 'Delete', btnClass: 'btn-danger', action: () => document.getElementById('delForm').submit() },
            back: function () {}
        }
    });
}
</script>
<?php $this->end(); ?>
