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

<!-- Header -->
<div class="d-flex justify-content-between align-items-start mb-3 flex-wrap gap-2">
  <div>
    <h5 class="fw-bold mb-1">
      <i class="bi bi-person-circle me-2 text-primary" style="font-size:1.3rem"></i>
      <?= e($customer['customer_name']) ?>
      <?php if($customer['status']==='inactive'):?>
      <span class="badge bg-secondary ms-1" style="font-size:.65rem">Inactive</span>
      <?php endif;?>
    </h5>
    <div class="d-flex gap-3 flex-wrap ms-1">
      <?php if($customer['phone']):?>
      <small class="text-muted"><i class="bi bi-telephone me-1"></i><?= e($customer['phone']) ?></small>
      <?php endif;?>
      <?php if($customer['email']):?>
      <small class="text-muted"><i class="bi bi-envelope me-1"></i><?= e($customer['email']) ?></small>
      <?php endif;?>
      <?php if($customer['address']):?>
      <small class="text-muted"><i class="bi bi-geo-alt me-1"></i><?= e($customer['address']) ?></small>
      <?php endif;?>
    </div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <?php if(Auth::can('sales.create') && $customer['id']!=1):?>
    <a href="<?= APP_URL ?>/pos?customer=<?= $customer['id'] ?>"
       class="btn btn-primary btn-sm fw-semibold">
      <i class="bi bi-cart3 me-1"></i>New Sale
    </a>
    <?php endif;?>
    <?php if(Auth::can('customers.edit')):?>
    <a href="<?= APP_URL ?>/customers/edit/<?= $customer['id'] ?>"
       class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-pencil me-1"></i>Edit
    </a>
    <?php endif;?>
    <a href="<?= APP_URL ?>/customers" class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-arrow-left me-1"></i>Back
    </a>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI row -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-2">
    <div class="card text-center py-3 border-primary h-100">
      <div class="fw-bold fs-4 text-primary"><?= number_format($summary['total_invoices']) ?></div>
      <small class="text-muted">Total Invoices</small>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold text-success"><?= currency($summary['total_revenue']) ?></div>
      <small class="text-muted">Lifetime Revenue</small>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold text-success"><?= currency($summary['total_paid']) ?></div>
      <small class="text-muted">Total Paid</small>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card text-center py-3 <?= $summary['total_balance']>0?'border-danger':'' ?> h-100">
      <div class="fw-bold <?= $summary['total_balance']>0?'text-danger':'text-muted' ?>">
        <?= currency($summary['total_balance']) ?>
      </div>
      <small class="text-muted">Outstanding</small>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold"><?= currency($customer['credit_limit'] ?: 0) ?></div>
      <small class="text-muted">Credit Limit</small>
      <?php if($customer['credit_limit']>0 && $customer['current_balance']>=$customer['credit_limit']):?>
      <div><span class="badge bg-danger" style="font-size:.6rem">Over Limit</span></div>
      <?php endif;?>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold text-warning"><?= number_format($customer['loyalty_points'] ?? 0) ?></div>
      <small class="text-muted">Loyalty Points</small>
    </div>
  </div>
</div>

<!-- Invoice status badges -->
<div class="d-flex gap-2 flex-wrap mb-3">
  <span class="badge bg-success px-3 py-2">✓ Paid: <?= $summary['paid_count'] ?></span>
  <span class="badge bg-warning text-dark px-3 py-2">~ Partial: <?= $summary['partial_count'] ?></span>
  <span class="badge bg-danger px-3 py-2">✗ Due: <?= $summary['due_count'] ?></span>
  <span class="badge bg-secondary px-3 py-2">↩ Returns: <?= $summary['return_count'] ?></span>
  <?php if($summary['first_sale']):?>
  <span class="badge bg-light text-dark border px-3 py-2">
    <i class="bi bi-calendar3 me-1"></i>
    First: <?= fDate($summary['first_sale'],'d M Y') ?>
  </span>
  <span class="badge bg-light text-dark border px-3 py-2">
    <i class="bi bi-clock me-1"></i>
    Last: <?= fDate($summary['last_sale'],'d M Y') ?>
  </span>
  <?php endif;?>
</div>

<div class="row g-3">

  <!-- Left col: Outstanding credit + Top products -->
  <div class="col-lg-4">

    <!-- Outstanding credit sales -->
    <?php if(!empty($creditSales)):?>
    <div class="card mb-3 border-warning">
      <div class="card-header fw-semibold small bg-warning text-dark d-flex justify-content-between">
        <span><i class="bi bi-exclamation-triangle me-1"></i>Outstanding Credit</span>
        <span class="badge bg-dark"><?= currency(array_sum(array_column($creditSales,'balance'))) ?></span>
      </div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <thead class="table-secondary">
            <tr><th>Invoice</th><th>Date</th><th class="text-end">Balance</th></tr>
          </thead>
          <tbody>
            <?php foreach($creditSales as $cs):?>
            <tr>
              <td>
                <a href="<?= APP_URL ?>/sales/view/<?= $cs['id'] ?>"
                   class="text-decoration-none fw-semibold small">
                  <?= e($cs['invoice_no']) ?>
                </a>
              </td>
              <td class="small"><?= fDate($cs['sale_date'],'d M Y') ?></td>
              <td class="text-end fw-bold text-danger small"><?= currency($cs['balance']) ?></td>
            </tr>
            <?php endforeach;?>
          </tbody>
          <tfoot class="table-secondary fw-bold">
            <tr><td colspan="2">Total Outstanding</td>
              <td class="text-end text-danger"><?= currency(array_sum(array_column($creditSales,'balance'))) ?></td>
            </tr>
          </tfoot>
        </table>
        <div class="p-2 border-top">
          <a href="<?= APP_URL ?>/finance/credit-book/<?= $customer['id'] ?>"
             class="btn btn-warning text-dark btn-sm w-100 fw-semibold">
            <i class="bi bi-journal-bookmark me-1"></i>Open Credit Ledger
          </a>
        </div>
      </div>
    </div>
    <?php endif;?>

    <!-- Top products -->
    <?php if(!empty($topProducts)):?>
    <div class="card mb-3">
      <div class="card-header fw-semibold small">
        <i class="bi bi-star me-1 text-warning"></i>Top Purchased Products
      </div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <thead class="table-secondary">
            <tr><th>Product</th><th class="text-end">Qty</th><th class="text-end">Spent</th></tr>
          </thead>
          <tbody>
            <?php foreach($topProducts as $tp):?>
            <tr>
              <td>
                <div class="small fw-semibold"><?= e($tp['product_name']) ?></div>
                <code style="font-size:.65rem" class="text-muted"><?= e($tp['product_code']) ?></code>
              </td>
              <td class="text-end small"><?= number_format($tp['total_qty'],2) ?></td>
              <td class="text-end small fw-semibold text-success"><?= currency($tp['total_spent']) ?></td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif;?>

    <!-- Customer info card -->
    <div class="card">
      <div class="card-header fw-semibold small">
        <i class="bi bi-person-lines-fill me-1"></i>Customer Details
      </div>
      <div class="card-body">
        <table class="table table-sm table-borderless mb-0">
          <tr><td class="text-muted small" style="width:38%">Joined</td>
            <td class="small"><?= fDate($customer['created_at'],'d M Y') ?></td></tr>
          <?php if($customer['opening_balance']>0):?>
          <tr><td class="text-muted small">Opening Bal.</td>
            <td class="small"><?= currency($customer['opening_balance']) ?></td></tr>
          <?php endif;?>
          <tr><td class="text-muted small">Credit Limit</td>
            <td class="small fw-semibold"><?= $customer['credit_limit']>0 ? currency($customer['credit_limit']) : '—' ?></td></tr>
          <tr><td class="text-muted small">Current Balance</td>
            <td class="small fw-semibold <?= $customer['current_balance']>0?'text-danger':'' ?>">
              <?= currency($customer['current_balance']) ?>
            </td></tr>
          <tr><td class="text-muted small">Status</td>
            <td><span class="badge <?= $customer['status']==='active'?'bg-success':'bg-secondary' ?>">
              <?= ucfirst($customer['status']) ?>
            </span></td></tr>
        </table>
      </div>
    </div>

  </div>

  <!-- Right col: Sales history + payment history -->
  <div class="col-lg-8">

    <!-- Sales history -->
    <div class="card mb-3">
      <div class="card-header fw-semibold small d-flex justify-content-between align-items-center">
        <span><i class="bi bi-receipt me-1"></i>Sales History</span>
        <small class="text-muted fw-normal"><?= count($sales) ?> recent</small>
      </div>
      <div class="card-body p-0">
        <table class="table table-sm table-hover mb-0">
          <thead class="table-dark">
            <tr>
              <th>#</th><th>Invoice</th><th>Date</th><th>Cashier</th>
              <th class="text-end">Total</th><th class="text-end">Paid</th>
              <th class="text-end">Balance</th><th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($sales as $i=>$s):
              $ps=$s['payment_status'];
              $rc=$ps==='due'?'table-danger bg-opacity-5':($ps==='partial'?'table-warning bg-opacity-5':'');
            ?>
            <tr class="<?= $rc ?>">
              <td class="text-muted small"><?= $i+1 ?></td>
              <td>
                <a href="<?= APP_URL ?>/sales/view/<?= $s['id'] ?>"
                   class="fw-semibold text-decoration-none small">
                  <?= e($s['invoice_no']) ?>
                </a>
              </td>
              <td class="small"><?= fDate($s['sale_date'],'d M Y') ?></td>
              <td class="small text-muted"><?= e($s['cashier_name'] ?? '—') ?></td>
              <td class="text-end fw-semibold small"><?= currency($s['total']) ?></td>
              <td class="text-end text-success small"><?= currency($s['paid']) ?></td>
              <td class="text-end small <?= $s['balance']>0?'fw-bold text-danger':'' ?>">
                <?= $s['balance']>0 ? currency($s['balance']) : '—' ?>
              </td>
              <td>
                <span class="badge <?= $ps==='paid'?'bg-success':($ps==='partial'?'bg-warning text-dark':'bg-danger') ?>"
                      style="font-size:.62rem">
                  <?= ucfirst($ps) ?>
                </span>
              </td>
            </tr>
            <?php endforeach;?>
            <?php if(empty($sales)):?>
            <tr><td colspan="8" class="text-center text-muted py-4">No sales yet.</td></tr>
            <?php endif;?>
          </tbody>
          <?php if(!empty($sales)):?>
          <tfoot class="table-secondary fw-bold">
            <tr>
              <td colspan="4">TOTAL</td>
              <td class="text-end"><?= currency(array_sum(array_column($sales,'total'))) ?></td>
              <td class="text-end text-success"><?= currency(array_sum(array_column($sales,'paid'))) ?></td>
              <td class="text-end text-danger"><?php $b=array_sum(array_column($sales,'balance')); echo $b>0?currency($b):'—'; ?></td>
              <td></td>
            </tr>
          </tfoot>
          <?php endif;?>
        </table>
      </div>
      <?php if($summary['total_invoices'] > 25):?>
      <div class="card-footer py-2 text-center">
        <small class="text-muted">Showing last 25 of <?= $summary['total_invoices'] ?> invoices</small>
      </div>
      <?php endif;?>
    </div>

    <!-- Payment history -->
    <?php if(!empty($payments)):?>
    <div class="card">
      <div class="card-header fw-semibold small d-flex justify-content-between align-items-center">
        <span><i class="bi bi-cash-coin me-1 text-success"></i>Payment History</span>
        <small class="text-muted fw-normal"><?= count($payments) ?> recent</small>
      </div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <thead class="table-secondary">
            <tr>
              <th>Date</th><th>Invoice</th><th>Method</th><th>Reference</th>
              <th class="text-end">Amount</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $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'];
            foreach($payments as $p):?>
            <tr>
              <td class="small"><?= fDate($p['payment_date'],'d M Y') ?></td>
              <td class="small">
                <?php if($p['invoice_no']):?>
                <a href="<?= APP_URL ?>/sales/view/<?= $p['sale_id'] ?>"
                   class="text-decoration-none small"><?= e($p['invoice_no']) ?></a>
                <?php else:?>—<?php endif;?>
              </td>
              <td>
                <span class="badge <?= $mc[$p['payment_method']] ?? 'bg-secondary' ?>"
                      style="font-size:.62rem">
                  <?= 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 small"><?= currency($p['amount']) ?></td>
            </tr>
            <?php endforeach;?>
          </tbody>
          <tfoot class="table-secondary fw-bold">
            <tr><td colspan="4">Total Payments</td>
              <td class="text-end text-success"><?= currency(array_sum(array_column($payments,'amount'))) ?></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
    <?php endif;?>

  </div>
</div>