<?php /* finance/credit_book.php */
$sym = setting('currency_symbol','Rs.');
?>

<style>
.cb-hero{background:linear-gradient(135deg,#1e1b4b,#4338ca 55%,#7c3aed);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:13px 16px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.35rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.65rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px;opacity:.85}
.cust-card{border-radius:12px;border:1.5px solid #e2e8f0;overflow:hidden;
  margin-bottom:10px;transition:box-shadow .15s}
.cust-card:hover{box-shadow:0 4px 16px rgba(0,0,0,.08)}
.cust-card.over-limit{border-color:#fca5a5}
.cust-header{padding:13px 16px;display:flex;align-items:center;gap:12px;
  background:#fff;cursor:pointer;user-select:none}
.cust-body{background:#fafafa;border-top:1px solid #f1f5f9;display:none}
.inv-table td{padding:5px 10px;font-size:.76rem;border-bottom:1px solid #f1f5f9}
.inv-table tr:last-child td{border:none}
.limit-bar{height:7px;border-radius:4px;background:#f1f5f9;margin-top:3px;overflow:hidden}
.limit-fill{height:7px;border-radius:4px;transition:width .5s}
.avatar{width:38px;height:38px;border-radius:50%;display:flex;align-items:center;
  justify-content:center;font-size:.8rem;font-weight:700;flex-shrink:0}
</style>

<!-- Hero -->
<div class="cb-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-journal-bookmark me-2"></i>Credit Book</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?=$totalCustomers?> customers on credit &nbsp;·&nbsp;
        <?=$totalInvoices?> open invoices &nbsp;·&nbsp;
        Total outstanding: <strong><?=$sym?><?=number_format($totalOutstanding,2)?></strong>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/customers"
         class="btn btn-outline-light btn-sm">
        <i class="bi bi-people me-1"></i>Customers
      </a>
      <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 Pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#ede9fe;border:2px solid #7c3aed">
      <div class="val" style="color:#7c3aed"><?=$sym?><?=number_format($totalOutstanding,0)?></div>
      <div class="lbl" style="color:#7c3aed">Total Outstanding</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#eff6ff;border:2px solid #3b82f6">
      <div class="val" style="color:#3b82f6"><?=$totalCustomers?></div>
      <div class="lbl" style="color:#3b82f6">Credit Customers</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fff7ed;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?=$totalInvoices?></div>
      <div class="lbl" style="color:#d97706">Open Invoices</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?=count($overLimit)?></div>
      <div class="lbl" style="color:#dc2626">Over Credit Limit</div>
    </div>
  </div>
</div>

<!-- Over limit alert -->
<?php if(!empty($overLimit)):?>
<div class="alert alert-danger d-flex align-items-center gap-2 mb-3 py-2">
  <i class="bi bi-exclamation-octagon-fill fs-5 flex-shrink-0"></i>
  <div class="small">
    <strong><?=count($overLimit)?> customer<?=count($overLimit)>1?'s':''?></strong>
    over credit limit —
    <?=implode(', ',array_map(fn($c)=>'<strong>'.e($c['customer_name']).'</strong>',array_values($overLimit)))?>
  </div>
</div>
<?php endif;?>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/finance/credit-book"
          class="d-flex gap-2 flex-wrap align-items-end">
      <div class="input-group input-group-sm" style="max-width:240px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Customer name, phone…"
               value="<?=e($search)?>">
      </div>
      <select name="sort" class="form-select form-select-sm" style="max-width:170px">
        <option value="balance"  <?=$sortBy==='balance'?  'selected':''?>>Highest Balance</option>
        <option value="name"     <?=$sortBy==='name'?     'selected':''?>>Name A–Z</option>
        <option value="last_txn" <?=$sortBy==='last_txn'? 'selected':''?>>Last Transaction</option>
      </select>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/finance/credit-book"
         class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <?php if(!empty($customers)):?>
      <button type="button" class="btn btn-sm btn-outline-primary ms-2"
              onclick="expandAll()">
        <i class="bi bi-chevron-expand me-1"></i>Expand All
      </button>
      <?php endif;?>
    </form>
  </div>
</div>

<!-- Customer Cards -->
<?php if(empty($customers)):?>
<div class="card">
  <div class="card-body text-center py-5 text-muted">
    <i class="bi bi-journal-check d-block fs-1 mb-2 opacity-25 text-success"></i>
    <div class="fw-bold fs-5">🎉 No outstanding credit balances!</div>
    <div class="small mt-1">All customers are fully paid up.</div>
  </div>
</div>
<?php else:?>

<?php foreach($customers as $cust):
  $outstanding = (float)$cust['outstanding_balance'];
  $limit       = (float)$cust['credit_limit'];
  $isOverLimit = $limit > 0 && $outstanding >= $limit;
  $limitPct    = $limit > 0 ? min(100, round($outstanding/$limit*100)) : 0;
  $initials    = strtoupper(substr($cust['customer_name'],0,1)
               .(strpos($cust['customer_name'],' ')!==false
                 ?substr(strrchr($cust['customer_name'],' '),1,1):''));
  $avatarBg    = $isOverLimit ? '#fef2f2' : '#ede9fe';
  $avatarClr   = $isOverLimit ? '#dc2626' : '#7c3aed';
  $cardId      = 'c'.$cust['id'];
?>
<div class="cust-card <?=$isOverLimit?'over-limit':''?>">

  <!-- Header -->
  <div class="cust-header" onclick="toggleCard('<?=$cardId?>')">
    <div class="avatar" style="background:<?=$avatarBg?>;color:<?=$avatarClr?>">
      <?=e($initials)?>
    </div>

    <div class="flex-grow-1 min-w-0">
      <div class="d-flex align-items-center gap-2 flex-wrap">
        <span class="fw-bold" style="font-size:.92rem"><?=e($cust['customer_name'])?></span>
        <?php if($isOverLimit):?>
        <span class="badge bg-danger" style="font-size:.6rem">⚠ Over Limit</span>
        <?php endif;?>
      </div>
      <div class="d-flex gap-3 mt-1 flex-wrap" style="font-size:.72rem;color:#64748b">
        <?php if($cust['phone']):?>
        <span><i class="bi bi-telephone me-1"></i><?=e($cust['phone'])?></span>
        <?php endif;?>
        <span><i class="bi bi-receipt me-1"></i><?=$cust['open_invoices']?> open invoice<?=$cust['open_invoices']!=1?'s':''?></span>
        <span><i class="bi bi-calendar3 me-1"></i>Last: <?=$cust['last_txn']?date('d M Y',strtotime($cust['last_txn'])):'—'?></span>
        <?php if($limit>0):?>
        <span>Limit: <?=$sym?><?=number_format($limit,0)?></span>
        <?php endif;?>
      </div>
      <?php if($limit>0):?>
      <div class="limit-bar" style="max-width:180px;margin-top:5px">
        <div class="limit-fill"
             style="width:<?=$limitPct?>%;
                    background:<?=$isOverLimit?'#dc2626':($limitPct>75?'#d97706':'#7c3aed')?>">
        </div>
      </div>
      <?php endif;?>
    </div>

    <div class="d-flex align-items-center gap-3">
      <div class="text-end">
        <div class="fw-bold <?=$isOverLimit?'text-danger':'text-primary'?>"
             style="font-size:1.1rem">
          <?=$sym?><?=number_format($outstanding,2)?>
        </div>
        <div style="font-size:.65rem;color:#94a3b8">outstanding</div>
      </div>
      <div class="d-flex gap-1" onclick="event.stopPropagation()">
        <a href="<?=APP_URL?>/finance/credit-book/<?=$cust['id']?>"
           class="btn btn-sm btn-outline-primary py-0 px-2" title="Full Ledger">
          <i class="bi bi-eye"></i>
        </a>
        <?php if(Auth::can('credit_book.view')):?>
        <button class="btn btn-sm btn-success py-0 px-2 fw-semibold"
                onclick="openPayment(<?=$cust['id']?>,'<?=e(addslashes($cust['customer_name']))?>',<?=$outstanding?>,'<?=e($sym)?>')"
                title="Record Payment">
          <i class="bi bi-cash me-1"></i>Pay
        </button>
        <?php endif;?>
      </div>
      <i class="bi bi-chevron-down text-muted"
         id="chv_<?=$cust['id']?>"
         style="font-size:.75rem;transition:transform .2s;flex-shrink:0"></i>
    </div>
  </div>

  <!-- Body: Open invoices -->
  <div id="<?=$cardId?>" class="cust-body">
    <?php
    try {
      $openInvs = Database::fetchAll(
        "SELECT s.id,s.invoice_no,s.sale_date,s.total,s.paid,s.balance,
                s.payment_status
         FROM sales s
         WHERE s.customer_id=? AND s.status='completed' AND s.balance>0.001
         ORDER BY s.sale_date ASC, s.id ASC",
        [$cust['id']]
      );
    } catch(\Exception $e){ $openInvs=[]; }
    ?>
    <?php if(!empty($openInvs)):?>
    <div class="table-responsive">
      <table class="table table-sm mb-0 inv-table">
        <thead style="background:#f8fafc;font-size:.68rem">
          <tr>
            <th class="ps-3">Invoice</th>
            <th>Sale Date</th>
            <th class="text-end">Total</th>
            <th class="text-end">Paid</th>
            <th class="text-end text-danger">Balance</th>
            <th class="text-center">Status</th>
            <?php if(Auth::can('credit_book.view')):?>
            <th class="text-center">Pay</th>
            <?php endif;?>
          </tr>
        </thead>
        <tbody>
          <?php foreach($openInvs as $inv):
            $stCls=['paid'=>'bg-success','partial'=>'bg-warning text-dark','unpaid'=>'bg-danger'][$inv['payment_status']]??'bg-secondary';
          ?>
          <tr>
            <td class="ps-3">
              <a href="<?=APP_URL?>/sales/view/<?=$inv['id']?>"
                 class="fw-bold text-decoration-none text-primary">
                <?=e($inv['invoice_no'])?>
              </a>
            </td>
            <td class="text-muted"><?=date('d M Y',strtotime($inv['sale_date']))?></td>
            <td class="text-end"><?=$sym?><?=number_format($inv['total'],2)?></td>
            <td class="text-end text-success"><?=$sym?><?=number_format($inv['paid'],2)?></td>
            <td class="text-end fw-bold text-danger"><?=$sym?><?=number_format($inv['balance'],2)?></td>
            <td class="text-center">
              <span class="badge <?=$stCls?>" style="font-size:.6rem">
                <?=ucfirst($inv['payment_status'])?>
              </span>
            </td>
            <?php if(Auth::can('credit_book.view')):?>
            <td class="text-center">
              <button class="btn btn-sm btn-outline-success py-0 px-2"
                      style="font-size:.65rem"
                      onclick="openPayment(<?=$cust['id']?>,'<?=e(addslashes($cust['customer_name']))?>',<?=$inv['balance']?>,'<?=e($sym)?>',<?=$inv['id']?>)">
                <i class="bi bi-cash me-1"></i>Pay
              </button>
            </td>
            <?php endif;?>
          </tr>
          <?php endforeach;?>
        </tbody>
        <tfoot style="background:#f1f5f9;font-size:.72rem;font-weight:700">
          <tr>
            <td colspan="4" class="ps-3">TOTAL OUTSTANDING</td>
            <td class="text-end text-danger"><?=$sym?><?=number_format($outstanding,2)?></td>
            <td colspan="<?=Auth::can('credit_book.view')?2:1?>"></td>
          </tr>
        </tfoot>
      </table>
    </div>
    <?php else:?>
    <div class="text-center text-muted py-3 small">No open invoices found.</div>
    <?php endif;?>
  </div>

</div>
<?php endforeach;?>

<?php endif;?>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" 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
        </h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form id="paymentForm" method="POST">
        <?=Auth::csrfField()?>
        <input type="hidden" name="sale_id" id="pay_sale_id">
        <div class="modal-body">
          <div class="p-3 mb-3 rounded text-center" style="background:#f0fdf4">
            <div class="fw-bold fs-5 text-success" id="pay_name">—</div>
            <div class="text-muted small mt-1">
              Outstanding:
              <strong class="text-danger" id="pay_outstanding">—</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" id="pay_sym">Rs.</span>
              <input type="number" name="amount" id="pay_amount"
                     class="form-control fw-bold fs-5"
                     min="0.01" step="0.01" required>
            </div>
            <div class="form-text">
              <a href="#" onclick="setFullAmt();return false"
                 class="fw-semibold text-success">
                Pay full outstanding balance
              </a>
            </div>
          </div>
          <div class="row g-2 mb-3">
            <div class="col-7">
              <label class="form-label small fw-semibold">Payment 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>
const APP_URL = '<?=APP_URL?>';
let _fullAmt  = 0;

function openPayment(custId, name, outstanding, sym, saleId=null) {
  _fullAmt = outstanding;
  document.getElementById('paymentForm').action =
    APP_URL + '/finance/credit-book/payment/' + custId;
  document.getElementById('pay_name').textContent        = name;
  document.getElementById('pay_outstanding').textContent = sym + outstanding.toFixed(2);
  document.getElementById('pay_sym').textContent         = sym;
  document.getElementById('pay_amount').value            = outstanding.toFixed(2);
  document.getElementById('pay_amount').max              = outstanding;
  document.getElementById('pay_sale_id').value           = saleId ?? '';
  new bootstrap.Modal(document.getElementById('paymentModal')).show();
}
function setFullAmt() {
  document.getElementById('pay_amount').value = _fullAmt.toFixed(2);
}
function toggleCard(id) {
  const el  = document.getElementById(id);
  const cid = id.replace('c','');
  const chv = document.getElementById('chv_' + cid);
  const open = el.style.display === 'block';
  el.style.display = open ? 'none' : 'block';
  if(chv) chv.style.transform = open ? '' : 'rotate(180deg)';
}
function expandAll() {
  document.querySelectorAll('.cust-body').forEach(el => el.style.display = 'block');
  document.querySelectorAll('[id^="chv_"]').forEach(el => el.style.transform = 'rotate(180deg)');
}
</script>