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

<style>
.sup-hero{background:linear-gradient(135deg,#0c4a6e,#0369a1 60%,#0891b2);
  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;margin-top:3px}
.sup-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.sup-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.sup-table tr:hover td{background:#f8fafc}
.sup-avatar{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;
  justify-content:center;font-size:.75rem;font-weight:700;flex-shrink:0}
.activity-dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:4px}
</style>

<!-- Hero -->
<div class="sup-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-truck me-2"></i>Suppliers</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= $totalSuppliers ?> active suppliers &nbsp;·&nbsp;
        <?= $suppliersWithDue ?> with outstanding payable &nbsp;·&nbsp;
        Total payable: <strong><?= $sym ?><?= number_format($totalBalance,2) ?></strong>
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('suppliers.create')):?>
      <a href="<?=APP_URL?>/suppliers/create"
         class="btn btn-light btn-sm fw-semibold" style="color:#0369a1">
        <i class="bi bi-plus-circle me-1"></i>Add Supplier
      </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:#e0f2fe;border:2px solid #0369a1">
      <div class="val" style="color:#0369a1"><?= $totalSuppliers ?></div>
      <div class="lbl" style="color:#0369a1">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"><?= $suppliersWithDue ?></div>
      <div class="lbl" style="color:#dc2626">With Payable</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 Payable</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val" style="color:#16a34a"><?=number_format($pagination['total'])?></div>
      <div class="lbl" style="color:#16a34a">Filtered Results</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/suppliers"
          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="Name, phone, contact person…"
               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:140px">
        <option value="all"  <?=$balance==='all'?  'selected':''?>>All Balances</option>
        <option value="due"  <?=$balance==='due'?  'selected':''?>>💳 Has Payable</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?>/suppliers" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
    </form>
  </div>
</div>

<!-- Suppliers 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-truck me-1"></i>Supplier 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 sup-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3" style="width:32px">#</th>
          <th>Supplier</th>
          <th>Contact</th>
          <th class="text-center">Orders</th>
          <th class="text-end">Total Purchased</th>
          <th class="text-end">Payable</th>
          <th class="text-center">Last Order</th>
          <th class="text-center">Status</th>
          <th class="text-center">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($data)):?>
        <tr>
          <td colspan="9" class="text-center text-muted py-5">
            <i class="bi bi-truck d-block fs-2 mb-2 opacity-25"></i>
            No suppliers found.
            <?php if(Auth::can('suppliers.create')):?>
            <div class="mt-2">
              <a href="<?=APP_URL?>/suppliers/create" class="btn btn-sm btn-outline-primary">
                <i class="bi bi-plus-circle me-1"></i>Add First Supplier
              </a>
            </div>
            <?php endif;?>
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage-1)*$perPage;
        foreach($data as $sup):
          $rowNum++;
          $balance    = (float)$sup['current_balance'];
          $hasBalance = $balance > 0.01;
          $initials   = strtoupper(substr($sup['supplier_name'],0,1)
                      .(strpos($sup['supplier_name'],' ')!==false
                        ?substr(strrchr($sup['supplier_name'],' '),1,1):''));
          $avatarBg   = $hasBalance ? '#fef9c3' : '#f0fdf4';
          $avatarClr  = $hasBalance ? '#d97706' : '#16a34a';

          // Last purchase age for activity indicator
          $lastDate   = $sup['last_purchase'];
          $daysSince  = $lastDate
            ? (int)((time()-strtotime($lastDate))/86400) : 999;
          $actColor   = $daysSince<=7?'#16a34a':($daysSince<=30?'#d97706':'#94a3b8');
        ?>
        <tr>
          <td class="ps-3 text-muted small"><?=$rowNum?></td>

          <!-- Supplier -->
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="sup-avatar" style="background:<?=$avatarBg?>;color:<?=$avatarClr?>">
                <?=e($initials)?>
              </div>
              <div>
                <a href="<?=APP_URL?>/suppliers/view/<?=$sup['id']?>"
                   class="fw-bold text-decoration-none text-dark d-flex align-items-center gap-1">
                  <span class="activity-dot" style="background:<?=$actColor?>"
                        title="<?=$daysSince<=7?'Active this week':($daysSince<=30?'Active this month':'Inactive > 30 days')?>">
                  </span>
                  <?=e($sup['supplier_name'])?>
                </a>
                <?php if($sup['address']):?>
                <div style="font-size:.65rem;color:#94a3b8">
                  <i class="bi bi-geo-alt me-1"></i><?=e(substr($sup['address'],0,35)).(strlen($sup['address'])>35?'…':'')?>
                </div>
                <?php endif;?>
              </div>
            </div>
          </td>

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

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

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

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

          <!-- Last Order -->
          <td class="text-center">
            <?php if($lastDate):?>
            <div class="small" style="color:<?=$actColor?>;font-weight:600">
              <?=date('d M Y',strtotime($lastDate))?>
            </div>
            <div style="font-size:.62rem;color:#94a3b8">
              <?=$daysSince===0?'Today':($daysSince===1?'Yesterday':"{$daysSince} days ago")?>
            </div>
            <?php else:?>
            <span class="text-muted small">No orders yet</span>
            <?php endif;?>
          </td>

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

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <a href="<?=APP_URL?>/suppliers/view/<?=$sup['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('suppliers.edit')):?>
              <a href="<?=APP_URL?>/suppliers/edit/<?=$sup['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(Auth::can('purchases.create')):?>
              <a href="<?=APP_URL?>/purchases/create?supplier_id=<?=$sup['id']?>"
                 class="btn btn-sm btn-outline-success py-0 px-2" title="New Purchase">
                <i class="bi bi-cart-plus"></i>
              </a>
              <?php endif;?>
              <?php if(Auth::can('suppliers.delete')):?>
              <form method="POST" action="<?=APP_URL?>/suppliers/delete/<?=$sup['id']?>"
                    class="supplier-delete-form"
                    data-has-history="<?= ($sup['total_purchases'] ?? 0) > 0 ? '1' : '0' ?>"
                    data-name="<?= e($sup['supplier_name']) ?>">
                <?=Auth::csrfField()?>
                <button type="button" class="btn btn-sm btn-outline-danger py-0 px-1 supplier-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_purchased')),2)?></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'])?> suppliers
    </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('.supplier-delete-btn').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = btn.closest('.supplier-delete-form');
    var hasHistory = form.getAttribute('data-has-history') === '1';
    var name = form.getAttribute('data-name');
    var msg = hasHistory
      ? 'This supplier has purchase order history and will be DEACTIVATED (not deleted) to preserve records. Continue?'
      : 'Permanently delete ' + name + '? This cannot be undone.';
    if (confirm(msg)) {
      form.submit();
    }
  });
});
</script>