<?php /* sales/payment.php */ ?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">
    <i class="bi bi-cash-coin me-2 text-success"></i>Record Payment
  </h5>
  <a href="<?= APP_URL ?>/sales/view/<?= $sale['id'] ?>"
     class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Back to Invoice
  </a>
</div>

<?= flashMessages() ?>

<!-- Sale Summary -->
<div class="card mb-3 border-primary">
  <div class="card-body py-2">
    <div class="row g-2">
      <div class="col-md-3">
        <div class="small text-muted">Invoice</div>
        <div class="fw-bold"><?= e($sale['invoice_no']) ?></div>
      </div>
      <div class="col-md-3">
        <div class="small text-muted">Customer</div>
        <div class="fw-semibold"><?= e($sale['customer_name'] ?? 'Walk-in') ?></div>
        <?php if($sale['customer_phone']):?>
        <small class="text-muted"><?= e($sale['customer_phone']) ?></small>
        <?php endif;?>
      </div>
      <div class="col-md-2">
        <div class="small text-muted">Invoice Total</div>
        <div class="fw-bold"><?= currency($sale['total']) ?></div>
      </div>
      <div class="col-md-2">
        <div class="small text-muted">Amount Paid</div>
        <div class="fw-bold text-success"><?= currency($sale['paid']) ?></div>
      </div>
      <div class="col-md-2">
        <div class="small text-muted">Balance Due</div>
        <div class="fw-bold fs-5 text-danger"><?= currency($sale['balance']) ?></div>
      </div>
    </div>
  </div>
</div>

<div class="row g-3">
  <!-- Payment Form -->
  <div class="col-md-6">
    <div class="card">
      <div class="card-header fw-semibold small bg-success text-white">
        <i class="bi bi-plus-circle me-1"></i>New Payment
      </div>
      <div class="card-body">
        <form method="POST"
              action="<?= APP_URL ?>/sales/payment/<?= $sale['id'] ?>">
          <?= Auth::csrfField() ?>

          <div class="mb-3">
            <label class="form-label fw-semibold small">Payment Date</label>
            <input type="date" name="payment_date" class="form-control"
                   value="<?= date('Y-m-d') ?>" required>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold small">Payment Method</label>
            <select name="payment_method" class="form-select" id="pmtMethod"
                    onchange="toggleRef()">
              <option value="cash">💵 Cash</option>
              <option value="card">💳 Card</option>
              <option value="bank_transfer">🏦 Bank Transfer</option>
              <option value="mobile">📱 Mobile Pay</option>
              <option value="cheque">📝 Cheque</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold small">
              Amount
              <button type="button" class="btn btn-link btn-sm py-0 ms-2"
                      onclick="setFull()">
                Pay Full Balance (<?= currency($sale['balance']) ?>)
              </button>
            </label>
            <div class="input-group">
              <span class="input-group-text"><?= setting('currency_symbol','Rs.') ?></span>
              <input type="number" name="amount" id="amountInput"
                     class="form-control form-control-lg fw-bold"
                     step="0.01" min="0.01"
                     max="<?= $sale['balance'] ?>"
                     value="<?= $sale['balance'] ?>" required>
            </div>
          </div>

          <div class="mb-3" id="refRow">
            <label class="form-label fw-semibold small" id="refLabel">
              Reference / Cheque No.
            </label>
            <input type="text" name="reference" class="form-control"
                   placeholder="e.g. CHQ001, TXN123456"
                   id="refInput">
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold small">Note (optional)</label>
            <textarea name="note" class="form-control" rows="2"
                      placeholder="Any remarks…"></textarea>
          </div>

          <button type="submit" class="btn btn-success w-100 fw-semibold py-2">
            <i class="bi bi-check-circle me-1"></i>Confirm Payment
          </button>
        </form>
      </div>
    </div>
  </div>

  <!-- Payment History -->
  <div class="col-md-6">
    <div class="card h-100">
      <div class="card-header fw-semibold small">
        <i class="bi bi-clock-history me-1"></i>Payment History
        <span class="badge bg-secondary ms-1"><?= count($payments) ?></span>
      </div>
      <div class="card-body p-0">
        <?php if(empty($payments)):?>
        <div class="text-center text-muted py-4">
          <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
          No payments recorded yet.
        </div>
        <?php else:?>
        <table class="table table-sm mb-0">
          <thead class="table-secondary">
            <tr>
              <th>Date</th>
              <th>Method</th>
              <th>Reference</th>
              <th class="text-end">Amount</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($payments as $p):
              $mc=['cash'=>'bg-success','card'=>'bg-primary','bank_transfer'=>'bg-info text-dark',
                   'mobile'=>'bg-info text-dark','cheque'=>'bg-secondary','credit'=>'bg-warning text-dark'];
            ?>
            <tr>
              <td class="small"><?= fDate($p['created_at'],'d M Y') ?></td>
              <td>
                <span class="badge <?= $mc[$p['payment_method']] ?? 'bg-secondary' ?>"
                      style="font-size:.68rem">
                  <?= e(ucfirst(str_replace('_',' ',$p['payment_method']))) ?>
                </span>
              </td>
              <td class="small text-muted"><?= e($p['reference'] ?: '—') ?></td>
              <td class="text-end fw-semibold text-success">
                <?= currency($p['amount']) ?>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
          <tfoot class="table-secondary fw-bold">
            <tr>
              <td colspan="3">Total Paid</td>
              <td class="text-end text-success"><?= currency($sale['paid']) ?></td>
            </tr>
          </tfoot>
        </table>
        <?php endif;?>
      </div>
    </div>
  </div>
</div>

<script>
function setFull() {
  document.getElementById('amountInput').value = <?= (float)$sale['balance'] ?>;
}
function toggleRef() {
  const m   = document.getElementById('pmtMethod').value;
  const row = document.getElementById('refRow');
  const lbl = document.getElementById('refLabel');
  const inp = document.getElementById('refInput');
  const labels = {
    card:'Card / POS Reference', bank_transfer:'Transfer Reference / TXN ID',
    mobile:'Mobile Reference No.', cheque:'Cheque Number',
    cash:'Reference (optional)'
  };
  lbl.textContent = labels[m] || 'Reference';
  inp.required    = (m === 'cheque');
  inp.placeholder = m === 'cheque' ? 'Cheque number is required' : 'Optional reference';
}
toggleRef();
</script>