<?php /* customers/index.php */
$sym  = setting('currency_symbol','Rs.');
$data     = $pagination['data'];
$lastPage = $pagination['pages'];
$curPage  = $pagination['current'];
$perPage  = $pagination['perPage'];
?>

<style>
.cust-hero{background:linear-gradient(135deg,#064e3b,#059669 60%,#10b981);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;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;opacity:.8;margin-top:2px}
.ct-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.ct-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.ct-table tr:hover td{background:#f8fafc}
.balance-bar{height:5px;border-radius:3px;background:#f1f5f9;margin-top:3px}
.balance-fill{height:5px;border-radius:3px}
.avatar{width:34px;height:34px;border-radius:50%;display:flex;align-items:center;
  justify-content:center;font-size:.72rem;font-weight:700;flex-shrink:0}
</style>

<!-- Hero -->
<div class="cust-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-people me-2"></i>Customers</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= $totalCustomers ?> active customers &nbsp;·&nbsp;
        <?= $customersWithDue ?> with outstanding balance &nbsp;·&nbsp;
        Total due: <strong><?= $sym ?><?= number_format($totalBalance,2) ?></strong>
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('customers.create')):?>
      <a href="<?= APP_URL ?>/customers/create"
         class="btn btn-light btn-sm fw-semibold" style="color:#059669">
        <i class="bi bi-person-plus me-1"></i>Add Customer
      </a>
      <?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 Pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #059669">
      <div class="val" style="color:#059669"><?= $totalCustomers ?></div>
      <div class="lbl" style="color:#059669">Total Active</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"><?= $customersWithDue ?></div>
      <div class="lbl" style="color:#dc2626">With Due Balance</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?= $sym ?><?= number_format($totalBalance,0) ?></div>
      <div class="lbl" style="color:#d97706">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"><?= number_format($pagination['total']) ?></div>
      <div class="lbl" style="color:#3b82f6">Filtered Results</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?= APP_URL ?>/customers"
          class="d-flex gap-2 flex-wrap align-items-end">
      <div class="input-group input-group-sm" style="max-width:230px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Name, phone, email…"
               value="<?= e($search) ?>">
      </div>
      <select name="status" class="form-select form-select-sm" style="max-width:120px">
        <option value="active"  <?=$status==='active'? 'selected':''?>>✓ Active</option>
        <option value="inactive"<?=$status==='inactive'?'selected':''?>>✗ Inactive</option>
        <option value="all"     <?=$status==='all'?    'selected':''?>>All</option>
      </select>
      <select name="balance" class="form-select form-select-sm" style="max-width:130px">
        <option value="all"  <?=$balance==='all'?  'selected':''?>>All Balances</option>
        <option value="due"  <?=$balance==='due'?  'selected':''?>>💳 Has Due</option>
        <option value="clear"<?=$balance==='clear'?'selected':''?>>✅ Clear</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 ?>/customers" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
    </form>
  </div>
</div>

<!-- Customer Table -->
<div class="card">
  <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
    <span class="fw-semibold small">
      <i class="bi bi-people me-1"></i>Customer List
    </span>
    <span class="badge bg-secondary">
      <?= number_format($pagination['total']) ?> records · Page <?= $curPage ?>/<?= $lastPage ?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 ct-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3" style="width:32px">#</th>
          <th>Customer</th>
          <th>Contact</th>
          <th class="text-center">Invoices</th>
          <th class="text-end">Total Spent</th>
          <th class="text-center">Credit Limit</th>
          <th class="text-end">Balance Due</th>
          <th class="text-center">Last Purchase</th>
          <th class="text-center">Status</th>
          <th class="text-center">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($data)):?>
        <tr>
          <td colspan="10" class="text-center text-muted py-5">
            <i class="bi bi-people d-block fs-2 mb-2 opacity-25"></i>
            No customers found.
            <?php if(Auth::can('customers.create')):?>
            <div class="mt-2">
              <a href="<?=APP_URL?>/customers/create" class="btn btn-sm btn-outline-success">
                <i class="bi bi-person-plus me-1"></i>Add First Customer
              </a>
            </div>
            <?php endif;?>
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage - 1) * $perPage;
        foreach($data as $cust):
          $rowNum++;
          $balance    = (float)$cust['current_balance'];
          $limit      = (float)$cust['credit_limit'];
          $limitPct   = $limit > 0 ? min(100, round($balance/$limit*100)) : 0;
          $isOverLimit= $limit > 0 && $balance >= $limit;
          $hasBalance = $balance > 0.01;
          $initials   = strtoupper(substr($cust['customer_name'],0,1)
                      .(strpos($cust['customer_name'],' ')!==false
                        ?substr(strrchr($cust['customer_name'],' '),1,1):''));
          $avatarBg   = $isOverLimit ? '#fef2f2' : ($hasBalance ? '#fffbeb' : '#f0fdf4');
          $avatarClr  = $isOverLimit ? '#dc2626' : ($hasBalance ? '#d97706' : '#059669');
        ?>
        <tr>
          <td class="ps-3 text-muted small"><?= $rowNum ?></td>

          <!-- Customer -->
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="avatar" style="background:<?=$avatarBg?>;color:<?=$avatarClr?>">
                <?= e($initials) ?>
              </div>
              <div>
                <a href="<?=APP_URL?>/customers/view/<?=$cust['id']?>"
                   class="fw-semibold text-decoration-none text-dark">
                  <?= e($cust['customer_name']) ?>
                </a>
                <?php if($isOverLimit):?>
                <span class="badge bg-danger ms-1" style="font-size:.55rem">Over Limit</span>
                <?php endif;?>
                <?php if($cust['loyalty_points'] > 0):?>
                <div style="font-size:.62rem;color:#7c3aed">
                  <i class="bi bi-star-fill me-1"></i><?= number_format($cust['loyalty_points']) ?> pts
                </div>
                <?php endif;?>
              </div>
            </div>
          </td>

          <!-- Contact -->
          <td>
            <?php if($cust['phone']):?>
            <div class="small">
              <i class="bi bi-telephone me-1 text-muted"></i><?= e($cust['phone']) ?>
            </div>
            <?php endif;?>
            <?php if($cust['email']):?>
            <div class="text-muted" style="font-size:.68rem">
              <i class="bi bi-envelope me-1"></i><?= e($cust['email']) ?>
            </div>
            <?php endif;?>
            <?php if(!$cust['phone'] && !$cust['email']):?>
            <span class="text-muted small">—</span>
            <?php endif;?>
          </td>

          <!-- Invoices -->
          <td class="text-center">
            <span class="badge bg-primary" style="font-size:.68rem">
              <?= number_format($cust['total_invoices']) ?>
            </span>
          </td>

          <!-- Total Spent -->
          <td class="text-end fw-semibold small">
            <?= $sym ?><?= number_format($cust['total_spent'],2) ?>
          </td>

          <!-- Credit Limit -->
          <td class="text-center">
            <?php if($limit > 0):?>
            <div class="small fw-semibold"><?=$sym?><?=number_format($limit,0)?></div>
            <div class="balance-bar" style="max-width:60px;margin:2px auto">
              <div class="balance-fill" style="width:<?=$limitPct?>%;background:<?=$isOverLimit?'#dc2626':($limitPct>75?'#d97706':'#059669')?>"></div>
            </div>
            <div style="font-size:.6rem;color:#94a3b8"><?=$limitPct?>%</div>
            <?php else:?>
            <span class="text-muted small">—</span>
            <?php endif;?>
          </td>

          <!-- Balance -->
          <td class="text-end">
            <?php if($hasBalance):?>
            <span class="fw-bold <?=$isOverLimit?'text-danger':'text-warning'?>">
              <?=$sym?><?=number_format($balance,2)?>
            </span>
            <?php else:?>
            <span class="text-success fw-semibold">✓ Clear</span>
            <?php endif;?>
          </td>

          <!-- Last Purchase -->
          <td class="text-center text-muted small">
            <?= $cust['last_purchase']
              ? date('d M Y', strtotime($cust['last_purchase']))
              : '—' ?>
          </td>

          <!-- Status -->
          <td class="text-center">
            <span class="badge <?=$cust['status']==='active'?'bg-success':'bg-secondary'?>"
                  style="font-size:.62rem">
              <?= ucfirst($cust['status']) ?>
            </span>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <a href="<?=APP_URL?>/customers/view/<?=$cust['id']?>"
                 class="btn btn-sm btn-outline-primary py-0 px-2" title="View">
                <i class="bi bi-eye"></i>
              </a>
              <?php if(Auth::can('customers.edit')):?>
              <a href="<?=APP_URL?>/customers/edit/<?=$cust['id']?>"
                 class="btn btn-sm btn-outline-secondary py-0 px-2" title="Edit">
                <i class="bi bi-pencil"></i>
              </a>
              <?php endif;?>
              <?php if($hasBalance && Auth::can('credit_book.view')):?>
              <a href="<?=APP_URL?>/finance/credit-book/<?=$cust['id']?>"
                 class="btn btn-sm btn-outline-warning py-0 px-2" title="Credit Book">
                <i class="bi bi-journal-bookmark"></i>
              </a>
              <?php endif;?>
              <?php if(Auth::can('customers.delete') && $cust['id'] != 1):?>
              <form method="POST" action="<?=APP_URL?>/customers/delete/<?=$cust['id']?>"
                    class="customer-delete-form"
                    data-has-history="<?= ($cust['total_invoices'] ?? 0) > 0 ? '1' : '0' ?>"
                    data-name="<?= e($cust['customer_name']) ?>">
                <?=Auth::csrfField()?>
                <button type="button" class="btn btn-sm btn-outline-danger py-0 px-1 customer-delete-btn" title="Delete">
                  <i class="bi bi-trash3"></i>
                </button>
              </form>
              <?php endif;?>
            </div>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>

      <?php if(!empty($data)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <tr>
          <td colspan="4" class="ps-3">PAGE TOTAL (<?=count($data)?>)</td>
          <td class="text-end"><?=$sym?><?=number_format(array_sum(array_column($data,'total_spent')),2)?></td>
          <td></td>
          <td class="text-end text-warning"><?=$sym?><?=number_format(array_sum(array_column($data,'current_balance')),2)?></td>
          <td colspan="3"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>

  <!-- Pagination -->
  <?php if($lastPage > 1):?>
  <div class="card-footer d-flex justify-content-between align-items-center py-2">
    <span class="text-muted small">
      Page <?=$curPage?> of <?=$lastPage?> · <?=number_format($pagination['total'])?> customers
    </span>
    <nav>
      <ul class="pagination pagination-sm mb-0">
        <li class="page-item <?=$curPage<=1?'disabled':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage-1]))?>">‹</a>
        </li>
        <?php foreach(range(max(1,$curPage-2),min($lastPage,$curPage+2)) as $p):?>
        <li class="page-item <?=$p===$curPage?'active':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$p]))?>"><?=$p?></a>
        </li>
        <?php endforeach;?>
        <li class="page-item <?=$curPage>=$lastPage?'disabled':''?>">
          <a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage+1]))?>">›</a>
        </li>
      </ul>
    </nav>
  </div>
  <?php endif;?>
</div>

<script>
document.querySelectorAll('.customer-delete-btn').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = btn.closest('.customer-delete-form');
    var hasHistory = form.getAttribute('data-has-history') === '1';
    var name = form.getAttribute('data-name');
    var msg = hasHistory
      ? 'This customer has invoice history and will be DEACTIVATED (not deleted) to preserve records. Continue?'
      : 'Permanently delete ' + name + '? This cannot be undone.';
    if (confirm(msg)) {
      form.submit();
    }
  });
});
</script>