<?php /* finance/credit_book_customer.php */
$sym = setting('currency_symbol','Rs.');
$outstanding = (float)($customer['current_balance'] ?? 0);
$limit       = (float)($customer['credit_limit']    ?? 0);
$limitPct    = $limit > 0 ? min(100, round($outstanding/$limit*100)) : 0;
$isOverLimit = $limit > 0 && $outstanding >= $limit;
$initials    = strtoupper(substr($customer['customer_name'],0,1)
             .(strpos($customer['customer_name'],' ')!==false
               ? substr(strrchr($customer['customer_name'],' '),1,1) : ''));
?>
<style>
.cl-hero{background:linear-gradient(135deg,#1e1b4b,#4338ca 55%,#7c3aed);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.ledger-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.ledger-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.ledger-table tr:hover td{background:#f8f9ff}
.type-pill{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;
  border-radius:12px;font-size:.63rem;font-weight:700}
.kpi-box{border-radius:10px;padding:12px 14px;text-align:center}
.kpi-box .val{font-size:1.25rem;font-weight:900;line-height:1}
.kpi-box .lbl{font-size:.63rem;text-transform:uppercase;letter-spacing:.05em;margin-top:2px;opacity:.8}
.limit-bar{height:8px;border-radius:4px;background:#ffffff33}
.limit-fill{height:8px;border-radius:4px;background:#fff;transition:width .4s}
</style>

<!-- Hero -->
<div class="cl-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div class="d-flex align-items-center gap-3">
      <div style="width:52px;height:52px;border-radius:50%;
                  background:rgba(255,255,255,.2);display:flex;
                  align-items:center;justify-content:center;
                  font-size:1.3rem;font-weight:900;flex-shrink:0">
        <?=e($initials)?>
      </div>
      <div>
        <h5 class="fw-bold mb-0"><?=e($customer['customer_name'])?></h5>
        <div style="opacity:.8;font-size:.8rem;margin-top:3px">
          <?php if($customer['phone']):?>
          <i class="bi bi-telephone me-1"></i><?=e($customer['phone'])?>
          <?php endif;?>
          <?php if($customer['email']):?>
          &nbsp;·&nbsp;<i class="bi bi-envelope me-1"></i><?=e($customer['email'])?>
          <?php endif;?>
        </div>
        <?php if($limit > 0):?>
        <div class="mt-2" style="max-width:200px">
          <div class="d-flex justify-content-between mb-1" style="font-size:.68rem;opacity:.8">
            <span>Credit Limit: <?=$sym?><?=number_format($limit,0)?></span>
            <span><?=$limitPct?>% used</span>
          </div>
          <div class="limit-bar">
            <div class="limit-fill"
                 style="width:<?=$limitPct?>%;
                        background:<?=$isOverLimit?'#fca5a5':'#a5f3fc'?>">
            </div>
          </div>
        </div>
        <?php endif;?>
      </div>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <a href="<?=APP_URL?>/finance/credit-book"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-arrow-left me-1"></i>Credit Book
      </a>
      <?php if(Auth::can('credit_book.view')):?>
      <button class="btn btn-success btn-sm fw-semibold"
              onclick="showPayModal()">
        <i class="bi bi-cash me-1"></i>Record Payment
      </button>
      <?php endif;?>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Row -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val text-danger"><?=$sym?><?=number_format($outstanding,2)?></div>
      <div class="lbl text-danger">Outstanding</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#ede9fe;border:2px solid #7c3aed">
      <div class="val" style="color:#7c3aed"><?=$sym?><?=number_format($totalDebit,2)?></div>
      <div class="lbl" style="color:#7c3aed">Total Credit Given</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val text-success"><?=$sym?><?=number_format($totalPaid,2)?></div>
      <div class="lbl text-success">Total Paid</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#eff6ff;border:2px solid #3b82f6">
      <div class="val text-primary"><?=count($ledger)?></div>
      <div class="lbl text-primary">Transactions</div>
    </div>
  </div>
</div>

<!-- Ledger Table -->
<div class="card">
  <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
    <span><i class="bi bi-journal-text me-1"></i>Ledger — <?=e($customer['customer_name'])?></span>
    <span class="badge bg-secondary"><?=count($ledger)?> entries</span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 ledger-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Date</th>
          <th>Type</th>
          <th>Reference</th>
          <th class="text-end text-danger">Debit</th>
          <th class="text-end text-success">Credit</th>
          <th class="text-end">Balance</th>
          <th>By / Note</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($ledger)):?>
        <tr>
          <td colspan="8" class="text-center text-muted py-4">No transactions found.</td>
        </tr>
        <?php endif;?>
        <?php
        $runBal = 0;
        // Rebuild ledger in ASC order for running balance
        $ledgerAsc = array_reverse($ledger);
        foreach($ledgerAsc as $i=>$entry):
          if($entry['type']==='sale') {
            $runBal += $entry['debit'] - $entry['credit'];
          } else {
            $runBal -= $entry['credit'];
            $runBal = max(0,$runBal);
          }
          $runBal = round($runBal,2);
        endforeach;

        // Show in DESC order with running balance
        $runBal2 = $outstanding;
        foreach($ledger as $i=>$entry):
          $entryBal = round($runBal2,2);
          if($entry['type']==='sale') {
            $runBal2 = round($runBal2 - $entry['debit'] + $entry['credit'], 2);
          } else {
            $runBal2 = round($runBal2 + $entry['credit'],2);
          }
          $isSale = $entry['type']==='sale';
        ?>
        <tr>
          <td class="ps-3 text-muted small"><?=$i+1?></td>

          <!-- Date -->
          <td>
            <div class="small fw-semibold"><?=date('d M Y',strtotime($entry['date']))?></div>
            <div style="font-size:.63rem;color:#94a3b8"><?=date('H:i',strtotime($entry['date']))?></div>
          </td>

          <!-- Type -->
          <td>
            <?php if($isSale):?>
            <span class="type-pill" style="background:#ede9fe;color:#7c3aed">
              <i class="bi bi-receipt"></i>Sale
            </span>
            <?php else:?>
            <span class="type-pill" style="background:#f0fdf4;color:#16a34a">
              <i class="bi bi-cash"></i>Payment
            </span>
            <?php endif;?>
          </td>

          <!-- Reference -->
          <td>
            <?php if($isSale && ($entry['sale_id']??0)):?>
            <a href="<?=APP_URL?>/sales/view/<?=$entry['sale_id']?>"
               class="fw-semibold text-decoration-none text-primary small">
              <?=e($entry['ref'])?>
            </a>
            <?php else:?>
            <span class="small text-muted"><?=e($entry['ref']??'—')?></span>
            <?php endif;?>
            <?php if(!empty($entry['method'])):?>
            <div style="font-size:.63rem;color:#94a3b8"><?=ucfirst($entry['method'])?></div>
            <?php endif;?>
          </td>

          <!-- Debit (amount owed from sale) -->
          <td class="text-end">
            <?php if($isSale && $entry['debit']>0):?>
            <span class="text-danger fw-semibold"><?=$sym?><?=number_format($entry['debit'],2)?></span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Credit (amount paid) -->
          <td class="text-end">
            <?php if($entry['credit']>0):?>
            <span class="text-success fw-semibold"><?=$sym?><?=number_format($entry['credit'],2)?></span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Running Balance -->
          <td class="text-end">
            <span class="fw-bold <?=$entryBal>0?'text-danger':'text-success'?>">
              <?=$entryBal>0?$sym.number_format($entryBal,2):'✓ 0.00'?>
            </span>
          </td>

          <!-- By / Note -->
          <td>
            <div class="small text-muted"><?=e($entry['by']??'—')?></div>
            <?php if(!empty($entry['note'])):?>
            <div style="font-size:.63rem;color:#94a3b8"><?=e(substr($entry['note'],0,30))?></div>
            <?php endif;?>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <tr>
          <td colspan="4" class="ps-3">SUMMARY</td>
          <td class="text-end text-danger"><?=$sym?><?=number_format($totalDebit,2)?></td>
          <td class="text-end text-success"><?=$sym?><?=number_format($totalPaid,2)?></td>
          <td class="text-end text-danger fw-bold">
            <?=$outstanding>0?$sym.number_format($outstanding,2):'✓ Clear'?>
          </td>
          <td></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="payModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:420px">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h6 class="modal-title fw-bold">
          <i class="bi bi-cash me-2"></i>Record Payment — <?=e($customer['customer_name'])?>
        </h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST"
            action="<?=APP_URL?>/finance/credit-book/payment/<?=$customer['id']?>">
        <?=Auth::csrfField()?>
        <input type="hidden" name="sale_id" id="modal_sale_id" value="">
        <div class="modal-body">
          <div class="p-3 mb-3 rounded text-center" style="background:#f0fdf4">
            <div class="fw-bold fs-5 text-success"><?=e($customer['customer_name'])?></div>
            <div class="text-muted small mt-1">
              Outstanding:
              <strong class="text-danger"><?=$sym?><?=number_format($outstanding,2)?></strong>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">
              Amount <span class="text-danger">*</span>
            </label>
            <div class="input-group">
              <span class="input-group-text fw-bold"><?=$sym?></span>
              <input type="number" name="amount" id="modal_amount"
                     class="form-control fw-bold fs-5"
                     min="0.01" step="0.01"
                     max="<?=$outstanding?>"
                     value="<?=$outstanding?>"
                     required>
            </div>
            <div class="form-text">
              <a href="#"
                 onclick="document.getElementById('modal_amount').value='<?=$outstanding?>';return false"
                 class="fw-semibold text-success">
                Pay full outstanding (<?=$sym?><?=number_format($outstanding,2)?>)
              </a>
            </div>
          </div>
          <div class="row g-2 mb-3">
            <div class="col-7">
              <label class="form-label small fw-semibold">Method</label>
              <select name="payment_method" class="form-select">
                <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="col-5">
              <label class="form-label small fw-semibold">Date</label>
              <input type="date" name="payment_date"
                     class="form-control" value="<?=date('Y-m-d')?>">
            </div>
          </div>
          <div>
            <label class="form-label small fw-semibold">Reference / Note</label>
            <input type="text" name="note" class="form-control"
                   placeholder="Receipt no., reference…">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary"
                  data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-success fw-bold px-4">
            <i class="bi bi-check-circle me-1"></i>Record Payment
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function showPayModal() {
  new bootstrap.Modal(document.getElementById('payModal')).show();
}
</script>