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

$pmtConfig = [
  'paid'    => ['bg-success',          '✅','Paid'],
  'partial' => ['bg-warning text-dark','⚡','Partial'],
  'unpaid'  => ['bg-danger',           '❌','Unpaid'],
];
$methIcons = [
  'cash'         => ['bi-cash-stack',           '#16a34a','Cash'],
  'cheque'       => ['bi-bank2',                '#d97706','Cheque'],
  'bank_transfer'=> ['bi-building',             '#0891b2','Bank'],
  'card'         => ['bi-credit-card-2-front',  '#3b82f6','Card'],
  'credit'       => ['bi-person-lines-fill',    '#dc2626','Credit'],
];
?>

<style>
.pur-hero{background:linear-gradient(135deg,#1e1b4b,#4338ca 60%,#6366f1);
  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}
.pur-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.pur-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.pur-table tr:hover td{background:#f8fafc}
</style>

<!-- Hero -->
<div class="pur-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-cart3 me-2"></i>Purchases</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= date('d M Y',strtotime($from)) ?> – <?= date('d M Y',strtotime($to)) ?>
        &nbsp;·&nbsp; <?= number_format($summary['count']) ?> orders
        &nbsp;·&nbsp; Total: <strong><?= $sym ?><?= number_format($summary['total'],2) ?></strong>
        <?php if($pendingCheques > 0):?>
        &nbsp;·&nbsp;
        <a href="<?=APP_URL?>/cheques/pending"
           class="badge bg-warning text-dark text-decoration-none">
          <i class="bi bi-hourglass-split me-1"></i><?=$pendingCheques?> cheque<?=$pendingCheques>1?'s':''?> pending
        </a>
        <?php endif;?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <?php if(Auth::can('purchases.create')):?>
      <a href="<?=APP_URL?>/purchases/create"
         class="btn btn-light btn-sm fw-semibold" style="color:#4338ca">
        <i class="bi bi-plus-circle me-1"></i>New Purchase
      </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:#ede9fe;border:2px solid #4338ca">
      <div class="val" style="color:#4338ca"><?=$sym?><?=number_format($summary['total'],0)?></div>
      <div class="lbl" style="color:#4338ca">Total Purchased (<?=number_format($summary['count'])?>)</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"><?=$sym?><?=number_format($summary['paid'],0)?></div>
      <div class="lbl" style="color:#16a34a">Paid to Suppliers</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"><?=$sym?><?=number_format($summary['balance'],0)?></div>
      <div class="lbl" style="color:#dc2626">Outstanding 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">
        <?= $summary['total']>0
            ? round($summary['paid']/$summary['total']*100,1).'%' : '0%' ?>
      </div>
      <div class="lbl" style="color:#d97706">Payment Rate</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/purchases"
          class="d-flex gap-2 flex-wrap align-items-end">
      <div class="d-flex gap-1 align-items-center">
        <input type="date" name="from" class="form-control form-control-sm"
               value="<?=e($from)?>" style="width:135px">
        <span class="text-muted small">to</span>
        <input type="date" name="to" class="form-control form-control-sm"
               value="<?=e($to)?>" style="width:135px">
      </div>
      <div class="input-group input-group-sm" style="max-width:200px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Invoice no, supplier…"
               value="<?=e($search)?>">
      </div>
      <select name="pmt" class="form-select form-select-sm" style="max-width:120px">
        <option value="all"     <?=$pmtStatus==='all'?    'selected':''?>>All Status</option>
        <option value="paid"    <?=$pmtStatus==='paid'?   'selected':''?>>✅ Paid</option>
        <option value="partial" <?=$pmtStatus==='partial'?'selected':''?>>⚡ Partial</option>
        <option value="unpaid"  <?=$pmtStatus==='unpaid'? 'selected':''?>>❌ Unpaid</option>
      </select>
      <select name="status" class="form-select form-select-sm" style="max-width:130px">
        <option value="received" <?=$purStatus==='received'? 'selected':''?>>✓ Received</option>
        <option value="cancelled"<?=$purStatus==='cancelled'?'selected':''?>>✗ Cancelled</option>
        <option value="all"      <?=$purStatus==='all'?      'selected':''?>>All Orders</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?>/purchases" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <!-- Quick shortcuts -->
      <div class="d-flex gap-1 ms-1">
        <?php foreach([
          'Today'      =>[date('Y-m-d'),     date('Y-m-d')],
          'This Week'  =>[date('Y-m-d',strtotime('monday this week')),date('Y-m-d')],
          'This Month' =>[date('Y-m-01'),    date('Y-m-d')],
          'Last Month' =>[date('Y-m-01',strtotime('first day of last month')),
                          date('Y-m-t',strtotime('last day of last month'))],
        ] as $lbl=>[$f,$t]):
          $active=($from===$f&&$to===$t);
        ?>
        <a href="?from=<?=$f?>&to=<?=$t?>"
           class="btn btn-sm <?=$active?'btn-primary':'btn-outline-secondary'?>">
          <?=$lbl?>
        </a>
        <?php endforeach;?>
      </div>
    </form>
  </div>
</div>

<!-- Purchases 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-table me-1"></i>Purchase Orders
    </span>
    <span class="badge bg-secondary">
      <?=number_format($pagination['total'])?> total · Page <?=$curPage?>/<?=$lastPage?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 pur-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3" style="width:32px">#</th>
          <th>Invoice No</th>
          <th>Supplier</th>
          <th class="text-center">Date</th>
          <th class="text-center">Method</th>
          <th class="text-end">Total</th>
          <th class="text-end text-success">Paid</th>
          <th class="text-end text-danger">Balance</th>
          <th class="text-center">Pmt 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-cart3 d-block fs-2 mb-2 opacity-25"></i>
            No purchases found.
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage-1)*$perPage;
        foreach($data as $pur):
          $rowNum++;
          $pmt       = $pmtConfig[$pur['payment_status']] ?? ['bg-secondary','?','Unknown'];
          $isCancelled = $pur['status']==='cancelled';
          $hasBalance  = (float)$pur['balance'] > 0.01;
          $method      = $pur['payment_method'] ?? 'cash';
          $mi          = $methIcons[$method] ?? ['bi-cash','#64748b',ucfirst($method)];
        ?>
        <tr class="<?=$isCancelled?'opacity-50':''?>">
          <td class="ps-3 text-muted small"><?=$rowNum?></td>

          <!-- Invoice -->
          <td>
            <a href="<?=APP_URL?>/purchases/view/<?=$pur['id']?>"
               class="fw-bold text-decoration-none text-primary">
              <?=e($pur['invoice_no'])?>
            </a>
            <?php if($isCancelled):?>
            <span class="badge bg-danger ms-1" style="font-size:.55rem">Cancelled</span>
            <?php endif;?>
          </td>

          <!-- Supplier -->
          <td>
            <div class="fw-semibold"><?=e($pur['supplier_name'])?></div>
            <?php if($pur['supplier_phone']):?>
            <div style="font-size:.65rem;color:#94a3b8">
              <i class="bi bi-telephone me-1"></i><?=e($pur['supplier_phone'])?>
            </div>
            <?php endif;?>
          </td>

          <!-- Date -->
          <td class="text-center">
            <div class="small fw-semibold"><?=date('d M Y',strtotime($pur['purchase_date']))?></div>
          </td>

          <!-- Method -->
          <td class="text-center">
            <span style="font-size:.72rem;font-weight:700;color:<?=$mi[1]?>">
              <i class="bi <?=$mi[0]?> me-1"></i><?=$mi[2]?>
            </span>
          </td>

          <!-- Total -->
          <td class="text-end fw-bold"><?=$sym?><?=number_format($pur['total'],2)?></td>

          <!-- Paid -->
          <td class="text-end text-success fw-semibold">
            <?=$sym?><?=number_format($pur['paid'],2)?>
          </td>

          <!-- Balance -->
          <td class="text-end <?=$hasBalance?'text-danger fw-bold':'text-muted'?>">
            <?=$hasBalance
              ? $sym.number_format($pur['balance'],2)
              : '<span class="text-success">✓</span>'?>
          </td>

          <!-- Pmt Status -->
          <td class="text-center">
            <span class="badge <?=$pmt[0]?>" style="font-size:.65rem">
              <?=$pmt[1]?> <?=$pmt[2]?>
            </span>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <div class="d-flex gap-1 justify-content-center">
              <a href="<?=APP_URL?>/purchases/view/<?=$pur['id']?>"
                 class="btn btn-sm btn-outline-primary py-0 px-2" title="View">
                <i class="bi bi-eye"></i>
              </a>
              <?php if($hasBalance && !$isCancelled && Auth::can('purchases.create')):?>
              <a href="<?=APP_URL?>/purchases/payment/<?=$pur['id']?>"
                 class="btn btn-sm btn-outline-success py-0 px-2" title="Pay Supplier">
                <i class="bi bi-cash"></i>
              </a>
              <?php endif;?>
              <?php if(!$isCancelled && Auth::can('purchases.delete')):?>
              <form method="POST" action="<?=APP_URL?>/purchases/cancel/<?=$pur['id']?>"
                    onsubmit="return confirm('Cancel <?=e($pur['invoice_no'])?>?')">
                <?=Auth::csrfField()?>
                <button class="btn btn-sm btn-outline-danger py-0 px-1" title="Cancel">
                  <i class="bi bi-x-lg"></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="5" class="ps-3">PAGE TOTAL (<?=count($data)?>)</td>
          <td class="text-end"><?=$sym?><?=number_format(array_sum(array_column($data,'total')),2)?></td>
          <td class="text-end text-success"><?=$sym?><?=number_format(array_sum(array_column($data,'paid')),2)?></td>
          <td class="text-end text-danger"><?=$sym?><?=number_format(array_sum(array_column($data,'balance')),2)?></td>
          <td colspan="2"></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'])?> records
    </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>