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

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">
    Purchase: <span class="text-primary"><?= e($purchase['invoice_no']) ?></span>
  </h5>
  <div class="d-flex gap-2">
    <?php if ($purchase['status'] === 'received' &&
              in_array(Auth::role(),['super_admin','admin','developer'],true)): ?>
      <a href="<?= APP_URL ?>/purchases/edit/<?= $purchase['id'] ?>"
         class="btn btn-sm btn-warning fw-semibold">
        <i class="bi bi-pencil-square me-1"></i>Edit Purchase
      </a>
    <?php endif; ?>
    <?php if ($purchase['status'] === 'received' && Auth::can('purchases.edit')): ?>
      <a href="<?= APP_URL ?>/purchases/return/<?= $purchase['id'] ?>"
         class="btn btn-sm btn-outline-warning">
        <i class="bi bi-arrow-return-left me-1"></i>Return Items
      </a>
      <form method="POST" action="<?= APP_URL ?>/purchases/cancel/<?= $purchase['id'] ?>"
            onsubmit="return confirm('Cancel this purchase and reverse stock?')">
        <?= Auth::csrfField() ?>
        <button class="btn btn-sm btn-outline-danger">
          <i class="bi bi-x-circle me-1"></i>Cancel Purchase
        </button>
      </form>
    <?php endif; ?>
    <a href="<?= APP_URL ?>/purchases" 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">

  <!-- Purchase Info -->
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-header bg-transparent fw-semibold small">Purchase 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($purchase['invoice_no']) ?></dd>

          <dt class="col-5 text-muted">Supplier</dt>
          <dd class="col-7">
            <a href="<?= APP_URL ?>/suppliers/view/<?= $purchase['supplier_id'] ?>">
              <?= e($purchase['supplier_name']) ?>
            </a>
          </dd>

          <dt class="col-5 text-muted">Phone</dt>
          <dd class="col-7"><?= e($purchase['sup_phone'] ?? '-') ?></dd>

          <dt class="col-5 text-muted">Date</dt>
          <dd class="col-7"><?= fDate($purchase['purchase_date']) ?></dd>

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

          <?php if ($purchase['note']): ?>
          <dt class="col-5 text-muted">Note</dt>
          <dd class="col-7"><?= e($purchase['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($purchase['subtotal']) ?></td>
          </tr>
          <?php if ($purchase['discount'] > 0): ?>
          <tr>
            <td class="text-muted ps-3">Discount</td>
            <td class="text-end pe-3 text-danger">− <?= currency($purchase['discount']) ?></td>
          </tr>
          <?php endif; ?>
          <?php if ($purchase['tax'] > 0): ?>
          <tr>
            <td class="text-muted ps-3">Tax</td>
            <td class="text-end pe-3"><?= currency($purchase['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($purchase['total']) ?></td>
          </tr>
          <tr>
            <td class="text-muted ps-3">Total Paid</td>
            <td class="text-end pe-3 text-success fw-semibold"><?= currency($purchase['paid']) ?></td>
          </tr>
          <tr class="<?= $purchase['balance']>0?'table-warning':'' ?>">
            <td class="fw-bold ps-3">Balance Due</td>
            <td class="text-end pe-3 fw-bold <?= $purchase['balance']>0?'text-danger':'' ?>">
              <?= currency($purchase['balance']) ?>
            </td>
          </tr>
          <tr>
            <td class="ps-3 text-muted">Payment Status</td>
            <td class="text-end pe-3">
              <?php $ps = $purchase['payment_status']; ?>
              <span class="badge <?= $ps==='paid'?'bg-success':($ps==='partial'?'bg-warning text-dark':'bg-danger') ?>">
                <?= ucfirst($ps) ?>
              </span>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>

  <!-- Record Payment -->
  <?php if ($purchase['balance'] > 0 && $purchase['status'] === 'received' && Auth::can('purchases.edit')): ?>
  <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 ?>/purchases/payment/<?= $purchase['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="<?= $purchase['balance'] ?>"
                     value="<?= number_format($purchase['balance'],2,'.','') ?>"
                     required>
            </div>
            <small class="text-muted">Outstanding: <strong><?= currency($purchase['balance']) ?></strong></small>
          </div>

          <div class="mb-2">
            <label class="form-label small mb-1">Payment Method</label>
            <select name="payment_method" id="pur-pmt-method" class="form-select form-select-sm"
                    onchange="togglePurCheque(this.value)">
              <option value="cash">Cash</option>
              <option value="bank_transfer">Bank Transfer</option>
              <option value="cheque">Cheque</option>
              <option value="card">Card</option>
              <option value="mobile">Mobile Pay</option>
            </select>
          </div>

          <!-- Cheque Details — shown when Cheque is selected -->
          <div id="pur-cheque-details" class="mb-2 p-2 rounded"
               style="display:none;background:#f0fff4;border:1px solid #6fcf97">
            <div class="row g-2">
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Cheque No. *</label>
                <input type="text" name="cheque_no" class="form-control form-control-sm"
                       placeholder="Cheque number">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Cheque Date</label>
                <input type="date" name="cheque_date" class="form-control form-control-sm"
                       value="<?= date('Y-m-d') ?>">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Bank</label>
                <input type="text" name="cheque_bank" class="form-control form-control-sm"
                       placeholder="e.g. HNB, BOC">
              </div>
              <div class="col-6">
                <label class="form-label small mb-1 fw-semibold text-success">Branch</label>
                <input type="text" name="cheque_branch" class="form-control form-control-sm"
                       placeholder="Bank branch">
              </div>
              <div class="col-12">
                <label class="form-label small mb-1 fw-semibold text-success">Drawer</label>
                <input type="text" name="cheque_drawer" class="form-control form-control-sm"
                       placeholder="Name on cheque">
              </div>
            </div>
          </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 / Cheque No.</label>
            <input type="text" name="reference" class="form-control form-control-sm"
                   placeholder="Transaction / cheque 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>

        <script>
        function togglePurCheque(method) {
          document.getElementById('pur-cheque-details').style.display =
            method === 'cheque' ? 'block' : 'none';
        }
        </script>
      </div>
    </div>
  </div>
  <?php elseif ($purchase['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">Fully Paid</div>
        <div class="text-muted small">No outstanding balance</div>
      </div>
    </div>
  </div>
  <?php endif; ?>

</div>

<!-- Payment History -->
<?php
$payments = Database::fetchAll(
    'SELECT sp.*, u.name AS paid_by
     FROM supplier_payments sp
     LEFT JOIN users u ON u.id = sp.created_by
     WHERE sp.purchase_id = ?
     ORDER BY sp.payment_date DESC, sp.id DESC',
    [$purchase['id']]
);
if (!empty($payments)):
?>
<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>Paid By</th>
            <th class="text-end">Amount</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($payments 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['paid_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 Paid</td>
            <td class="text-end text-success">
              <?= currency(array_sum(array_column($payments, 'amount'))) ?>
            </td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Purchase Items -->
<div class="card">
  <div class="card-header bg-transparent fw-semibold small">
    <i class="bi bi-box-seam me-1"></i>Purchased 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">Quantity</th>
            <th class="text-end">Cost 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['cost_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($purchase['total']) ?></td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</div>