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

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">
    Sale: <span class="text-primary"><?= e($sale['invoice_no']) ?></span>
  </h5>
  <div class="d-flex gap-2">
    <a href="<?= APP_URL ?>/pos/receipt/<?= $sale['id'] ?>" target="_blank"
       class="btn btn-sm btn-outline-secondary">
      <i class="bi bi-printer me-1"></i>Print Receipt
    </a>
    <?php if ($sale['status'] === 'completed' && Auth::can('sales.return')): ?>
    <a href="<?= APP_URL ?>/sales/return/<?= $sale['id'] ?>"
       class="btn btn-sm btn-outline-warning">
      <i class="bi bi-arrow-return-left me-1"></i>Return
    </a>
    <?php endif; ?>
    <?php if ($sale['status'] === 'completed' && Auth::can('sales.create')): ?>
    <form method="POST" action="<?= APP_URL ?>/sales/cancel/<?= $sale['id'] ?>"
          onsubmit="return confirm('Cancel this sale and restore stock?')">
      <?= Auth::csrfField() ?>
      <button class="btn btn-sm btn-outline-danger">
        <i class="bi bi-x-circle me-1"></i>Cancel
      </button>
    </form>
    <?php endif; ?>
    <a href="<?= APP_URL ?>/sales" class="btn btn-sm btn-outline-secondary">
      <i class="bi bi-arrow-left me-1"></i>Back
    </a>
  </div>
</div>

<div class="row g-3 mb-3">

  <!-- Sale Info -->
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-header bg-transparent fw-semibold small">Sale Details</div>
      <div class="card-body">
        <dl class="row mb-0 small">
          <dt class="col-5 text-muted">Invoice No</dt>
          <dd class="col-7 fw-semibold"><?= e($sale['invoice_no']) ?></dd>

          <dt class="col-5 text-muted">Customer</dt>
          <dd class="col-7">
            <?php if ($sale['customer_id']): ?>
              <a href="<?= APP_URL ?>/customers/view/<?= $sale['customer_id'] ?>">
                <?= e($sale['customer_name']) ?>
              </a>
            <?php else: ?>
              <?= e($sale['customer_name']) ?>
            <?php endif; ?>
          </dd>

          <?php if ($sale['customer_phone']): ?>
          <dt class="col-5 text-muted">Phone</dt>
          <dd class="col-7"><?= e($sale['customer_phone']) ?></dd>
          <?php endif; ?>

          <dt class="col-5 text-muted">Cashier</dt>
          <dd class="col-7"><?= e($sale['cashier_name']) ?></dd>

          <dt class="col-5 text-muted">Date</dt>
          <dd class="col-7"><?= fDate($sale['sale_date'], 'd M Y H:i') ?></dd>

          <dt class="col-5 text-muted">Status</dt>
          <dd class="col-7">
            <span class="badge <?= $sale['status']==='completed'?'bg-success':($sale['status']==='returned'?'bg-warning text-dark':'bg-danger') ?>">
              <?= ucfirst($sale['status']) ?>
            </span>
          </dd>

          <?php if ($sale['note']): ?>
          <dt class="col-5 text-muted">Note</dt>
          <dd class="col-7"><?= e($sale['note']) ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <!-- Payment Summary -->
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-header bg-transparent fw-semibold small">Payment Summary</div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <tr>
            <td class="text-muted ps-3">Subtotal</td>
            <td class="text-end pe-3"><?= currency($sale['subtotal']) ?></td>
          </tr>
          <?php if ($sale['discount'] > 0): ?>
          <tr>
            <td class="text-muted ps-3">Discount</td>
            <td class="text-end pe-3 text-danger">− <?= currency($sale['discount']) ?></td>
          </tr>
          <?php endif; ?>
          <?php if ($sale['tax'] > 0): ?>
          <tr>
            <td class="text-muted ps-3">Tax</td>
            <td class="text-end pe-3"><?= currency($sale['tax']) ?></td>
          </tr>
          <?php endif; ?>
          <tr class="border-top">
            <td class="fw-bold ps-3">Total</td>
            <td class="text-end pe-3 fw-bold text-primary"><?= currency($sale['total']) ?></td>
          </tr>
          <tr>
            <td class="text-muted ps-3">Total Paid</td>
            <td class="text-end pe-3 text-success fw-semibold"><?= currency($sale['paid']) ?></td>
          </tr>
          <tr class="<?= $sale['balance']>0?'table-warning':'' ?>">
            <td class="fw-bold ps-3">Balance Due</td>
            <td class="text-end pe-3 fw-bold <?= $sale['balance']>0?'text-danger':'' ?>">
              <?= currency($sale['balance']) ?>
            </td>
          </tr>
          <tr>
            <td class="ps-3 text-muted">Payment Status</td>
            <td class="text-end pe-3">
              <?php $ps = $sale['payment_status']; ?>
              <span class="badge <?= $ps==='paid'?'bg-success':($ps==='partial'?'bg-warning text-dark':'bg-danger') ?>">
                <?= ucfirst($ps) ?>
              </span>
            </td>
          </tr>
        </table>

        <!-- Original payments breakdown -->
        <?php if (!empty($payments)): ?>
        <div class="px-3 pb-2 pt-1 border-top">
          <div class="text-muted small mb-1 fw-semibold">Payment Methods</div>
          <?php foreach ($payments as $p): ?>
          <div class="d-flex justify-content-between small align-items-center mb-1">
            <span>
              <?= ucfirst(str_replace('_',' ',$p['payment_method'])) ?>
              <?php if ($p['payment_method'] === 'cheque'): ?>
                <span class="badge bg-warning text-dark ms-1" style="font-size:.65rem">
                  <i class="bi bi-hourglass me-1"></i>Pending Clearance
                </span>
              <?php endif; ?>
              <?php if ($p['reference']): ?>
                <small class="text-muted d-block"><?= e($p['reference']) ?></small>
              <?php endif; ?>
            </span>
            <span class="fw-semibold"><?= currency($p['amount']) ?></span>
          </div>
          <?php endforeach; ?>
          <?php
          $pendingCheque = array_sum(array_map(
            fn($p) => $p['payment_method']==='cheque' ? (float)$p['amount'] : 0,
            $payments
          ));
          if ($pendingCheque > 0):
          ?>
          <div class="alert alert-warning py-1 px-2 mt-2 mb-0 small">
            <i class="bi bi-exclamation-triangle me-1"></i>
            <strong><?= currency($pendingCheque) ?></strong> cheque pending — balance clears only after cheque is cleared in
            <a href="<?= APP_URL ?>/cheques" class="alert-link no-print">Cheque Management</a>.
          </div>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Record Payment / Fully Paid -->
  <?php if ($sale['balance'] > 0 && $sale['status'] === 'completed' && Auth::can('sales.create')): ?>
  <div class="col-md-4">
    <div class="card h-100 border-warning">
      <div class="card-header bg-warning bg-opacity-10 fw-semibold small text-warning">
        <i class="bi bi-cash-coin me-1"></i>Record Payment
      </div>
      <div class="card-body">
        <form method="POST" action="<?= APP_URL ?>/sales/payment/<?= $sale['id'] ?>">
          <?= Auth::csrfField() ?>

          <div class="mb-2">
            <label class="form-label small mb-1 fw-semibold">Amount *</label>
            <div class="input-group">
              <span class="input-group-text"><?= e(setting('currency_symbol','Rs.')) ?></span>
              <input type="number" name="amount" class="form-control fw-bold"
                     step="0.01" min="0.01"
                     max="<?= $sale['balance'] ?>"
                     value="<?= number_format((float)$sale['balance'],2,'.','') ?>"
                     required>
            </div>
            <small class="text-muted">
              Outstanding: <strong class="text-danger"><?= currency($sale['balance']) ?></strong>
            </small>
          </div>

          <div class="mb-2">
            <label class="form-label small mb-1">Payment Method</label>
            <select name="payment_method" class="form-select form-select-sm">
              <option value="cash">Cash</option>
              <option value="card">Card</option>
              <option value="bank_transfer">Bank Transfer</option>
              <option value="mobile">Mobile Pay</option>
            </select>
          </div>

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

          <div class="mb-2">
            <label class="form-label small mb-1">Reference No.</label>
            <input type="text" name="reference" class="form-control form-control-sm"
                   placeholder="Transaction / receipt number">
          </div>

          <div class="mb-3">
            <label class="form-label small mb-1">Note</label>
            <input type="text" name="note" class="form-control form-control-sm"
                   placeholder="Optional note">
          </div>

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

  <?php elseif ($sale['balance'] <= 0): ?>
  <div class="col-md-4">
    <div class="card h-100 border-success">
      <div class="card-body d-flex flex-column align-items-center justify-content-center text-center py-4">
        <i class="bi bi-check-circle-fill text-success fs-1 mb-2"></i>
        <div class="fw-semibold text-success fs-5">Fully Paid</div>
        <div class="text-muted small mt-1">No outstanding balance</div>
      </div>
    </div>
  </div>
  <?php endif; ?>

</div>

<!-- Customer Payment History -->
<?php
$custPayments = Database::fetchAll(
    'SELECT cp.*, u.name AS received_by
     FROM customer_payments cp
     LEFT JOIN users u ON u.id = cp.created_by
     WHERE cp.sale_id = ?
     ORDER BY cp.payment_date DESC, cp.id DESC',
    [(int)$sale['id']]
);
if (!empty($custPayments)):
?>
<div class="card mb-3">
  <div class="card-header bg-transparent fw-semibold small">
    <i class="bi bi-clock-history me-1"></i>Payment History
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-sm mb-0">
        <thead class="table-light">
          <tr>
            <th>#</th>
            <th>Date</th>
            <th>Method</th>
            <th>Reference</th>
            <th>Note</th>
            <th>Received By</th>
            <th class="text-end">Amount</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($custPayments as $i => $p): ?>
          <tr>
            <td class="text-muted small"><?= $i + 1 ?></td>
            <td><?= fDate($p['payment_date']) ?></td>
            <td>
              <span class="badge bg-secondary">
                <?= ucfirst(str_replace('_', ' ', $p['payment_method'])) ?>
              </span>
            </td>
            <td><?= e($p['reference'] ?? '-') ?></td>
            <td class="text-muted small"><?= e($p['note'] ?? '') ?></td>
            <td><small><?= e($p['received_by'] ?? '-') ?></small></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="6">Total Received</td>
            <td class="text-end text-success">
              <?= currency(array_sum(array_column($custPayments, 'amount'))) ?>
            </td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Returns -->
<?php if (!empty($returns)): ?>
<div class="card mb-3">
  <div class="card-header bg-transparent fw-semibold small text-warning">
    <i class="bi bi-arrow-return-left me-1"></i>Returns
  </div>
  <div class="card-body p-0">
    <ul class="list-group list-group-flush">
      <?php foreach ($returns as $r): ?>
      <li class="list-group-item d-flex justify-content-between align-items-center small">
        <div>
          <span class="fw-semibold"><?= e($r['invoice_no']) ?></span>
          <span class="text-muted ms-2"><?= fDate($r['return_date']) ?></span>
          <span class="badge bg-secondary ms-1"><?= ucfirst(str_replace('_',' ',$r['refund_method'])) ?></span>
        </div>
        <span class="text-danger fw-semibold"><?= currency($r['total']) ?></span>
      </li>
      <?php endforeach; ?>
    </ul>
  </div>
</div>
<?php endif; ?>

<!-- Sale Items -->
<div class="card">
  <div class="card-header bg-transparent fw-semibold small">
    <i class="bi bi-cart3 me-1"></i>Sale Items
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-sm mb-0">
        <thead class="table-light">
          <tr>
            <th>#</th>
            <th>Product</th>
            <th>Code</th>
            <th class="text-end">Qty</th>
            <th class="text-end">Unit Price</th>
            <th class="text-end">Discount</th>
            <th class="text-end">Tax</th>
            <th class="text-end">Total</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($items as $i => $item): ?>
          <tr>
            <td class="text-muted small"><?= $i + 1 ?></td>
            <td class="fw-semibold"><?= e($item['product_name']) ?></td>
            <td><small class="text-muted"><?= e($item['product_code']) ?></small></td>
            <td class="text-end"><?= number_format((float)$item['quantity'], 2) ?></td>
            <td class="text-end"><?= currency($item['selling_price']) ?></td>
            <td class="text-end text-danger"><?= $item['discount']>0 ? '− '.currency($item['discount']) : '—' ?></td>
            <td class="text-end"><?= $item['tax']>0 ? currency($item['tax']) : '—' ?></td>
            <td class="text-end fw-semibold"><?= currency($item['total']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot class="table-secondary fw-bold">
          <tr>
            <td colspan="7">Total</td>
            <td class="text-end"><?= currency($sale['total']) ?></td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>
