<?php include APP_PATH.'/views/partials/report_header.php'; ?>

<!-- Date navigation -->
<div class="rpt-btn-bar no-print">
  <div class="d-flex gap-2 align-items-center flex-wrap">
    <a href="?date=<?= date('Y-m-d') ?>"
       class="btn btn-sm <?= $date===date('Y-m-d')?'btn-primary':'btn-outline-secondary' ?> fw-semibold">
      <i class="bi bi-calendar-check me-1"></i>Today
    </a>
    <a href="?date=<?= date('Y-m-d',strtotime('-1 day')) ?>"
       class="btn btn-sm <?= $date===date('Y-m-d',strtotime('-1 day'))?'btn-primary':'btn-outline-secondary' ?>">
      Yesterday
    </a>
    <a href="?date=<?= date('Y-m-d',strtotime('-2 day')) ?>"
       class="btn btn-sm btn-outline-secondary">
      <?= date('d M',strtotime('-2 day')) ?>
    </a>
    <div class="input-group input-group-sm ms-2" style="width:180px">
      <span class="input-group-text"><i class="bi bi-calendar3"></i></span>
      <input type="date" id="datePicker" class="form-control fw-semibold"
             value="<?= e($date) ?>"
             max="<?= date('Y-m-d') ?>"
             onchange="window.location='?date='+this.value">
    </div>
    <div class="d-flex gap-1 ms-auto">
      <a href="?date=<?= date('Y-m-d',strtotime($date.' -1 day')) ?>"
         class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-chevron-left"></i>
      </a>
      <a href="?date=<?= date('Y-m-d',strtotime($date.' +1 day')) ?>"
         class="btn btn-sm btn-outline-secondary"
         <?= $date>=date('Y-m-d')?'disabled':'' ?>>
        <i class="bi bi-chevron-right"></i>
      </a>
    </div>
  </div>
</div>

<!-- Day heading -->
<div class="alert border-0 mb-3 py-2"
     style="background:linear-gradient(90deg,#eff6ff,#f8faff);border-left:4px solid #2563eb!important;border-left-width:4px">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <span class="fw-bold fs-5 text-primary"><?= date('l', strtotime($date)) ?></span>
      <span class="text-muted ms-2"><?= date('d F Y', strtotime($date)) ?></span>
      <?php if($date === date('Y-m-d')):?>
      <span class="badge bg-primary ms-2">Today</span>
      <?php elseif($date === date('Y-m-d',strtotime('-1 day'))):?>
      <span class="badge bg-secondary ms-2">Yesterday</span>
      <?php endif;?>
    </div>
    <?php if($dayChange !== null):?>
    <div class="text-end">
      <small class="text-muted">vs previous day</small>
      <div class="fw-bold <?= $dayChange>=0?'text-success':'text-danger' ?>">
        <?= $dayChange>=0?'↑':'↓' ?> <?= abs($dayChange) ?>%
      </div>
    </div>
    <?php endif;?>
  </div>
</div>

<!-- ── KPI Row 1: Sales ─────────────────────────────── -->
<div class="row g-2 mb-2">
  <div class="col-6 col-md">
    <div class="card text-center py-3 border-primary h-100">
      <div class="fw-bold fs-3 text-primary"><?= number_format($salesSummary['count']) ?></div>
      <small class="text-muted">Bills</small>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold text-success"><?= currency($salesSummary['total']) ?></div>
      <small class="text-muted">Sales Revenue</small>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold text-info"><?= currency($grossProfit) ?></div>
      <small class="text-muted">Gross Profit</small>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="card text-center py-3 h-100">
      <div class="fw-bold text-danger"><?= currency($expenseSummary['total']) ?></div>
      <small class="text-muted">Expenses</small>
    </div>
  </div>
  <div class="col-6 col-md">
    <div class="card text-center py-3 border-<?= $netProfit>=0?'success':'danger' ?> h-100">
      <div class="fw-bold fs-5 <?= $netProfit>=0?'text-success':'text-danger' ?>">
        <?= currency(abs($netProfit)) ?>
      </div>
      <small class="text-muted"><?= $netProfit>=0?'Net Profit':'Net Loss' ?></small>
    </div>
  </div>
</div>

<!-- Status badges -->
<div class="d-flex gap-2 mb-3 flex-wrap">
  <span class="badge bg-success px-3 py-2">✓ Paid: <?= $salesSummary['paid_count'] ?></span>
  <span class="badge bg-warning text-dark px-3 py-2">~ Partial: <?= $salesSummary['partial_count'] ?></span>
  <span class="badge bg-danger px-3 py-2">✗ Due: <?= $salesSummary['due_count'] ?></span>
  <span class="badge bg-secondary px-3 py-2">Discount: <?= currency($salesSummary['discount']) ?></span>
  <span class="badge bg-warning text-dark px-3 py-2">Tax: <?= currency($salesSummary['tax']) ?></span>
  <?php if($purchaseSummary['count']>0):?>
  <span class="badge bg-info text-dark px-3 py-2">Purchases: <?= $purchaseSummary['count'] ?></span>
  <?php endif;?>
</div>

<div class="row g-3 mb-3">

  <!-- Payment Methods -->
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-credit-card me-1 text-primary"></i>Payment Methods
      </div>
      <div class="card-body p-0">
        <?php if(!empty($payments)):
          $pmtIcons=['cash'=>'💵','card'=>'💳','bank_transfer'=>'🏦','mobile'=>'📱','cheque'=>'📝','credit'=>'📒'];
          $pmtTotal=array_sum(array_column($payments,'amount'));
        ?>
        <table class="table table-sm mb-0">
          <thead class="table-secondary"><tr><th>Method</th><th class="text-end">Txns</th><th class="text-end">Amount</th><th class="text-end">%</th></tr></thead>
          <tbody>
            <?php foreach($payments as $p):
              $pct=$pmtTotal>0?round($p['amount']/$pmtTotal*100,1):0;
            ?>
            <tr>
              <td class="small"><?=$pmtIcons[$p['method']]??'💰'?> <?=e(ucfirst(str_replace('_',' ',$p['method'])))?></td>
              <td class="text-end small"><?=$p['txn_count']?></td>
              <td class="text-end fw-semibold small"><?=currency($p['amount'])?></td>
              <td class="text-end"><span class="badge bg-primary bg-opacity-75" style="font-size:.62rem"><?=$pct?>%</span></td>
            </tr>
            <?php endforeach;?>
          </tbody>
          <tfoot class="table-secondary fw-bold"><tr><td>Total</td><td class="text-end"><?=array_sum(array_column($payments,'txn_count'))?></td><td class="text-end"><?=currency($pmtTotal)?></td><td></td></tr></tfoot>
        </table>
        <?php else:?>
        <div class="text-center text-muted py-4 small">No payments today.</div>
        <?php endif;?>
      </div>
    </div>
  </div>

  <!-- Cashier Performance -->
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-person-badge me-1 text-info"></i>Cashier Performance
      </div>
      <div class="card-body p-0">
        <?php if(!empty($cashiers)):?>
        <table class="table table-sm mb-0">
          <thead class="table-secondary"><tr><th>Cashier</th><th class="text-end">Bills</th><th class="text-end">Total</th></tr></thead>
          <tbody>
            <?php $maxTotal=max(array_column($cashiers,'total'));
            foreach($cashiers as $i=>$c):
              $pct=$maxTotal>0?round($c['total']/$maxTotal*100):0;
            ?>
            <tr>
              <td>
                <div class="small fw-semibold"><?=e($c['cashier_name'])?><?php if($i===0):?> <span class="badge bg-warning text-dark" style="font-size:.55rem">★</span><?php endif;?></div>
                <div class="bg-light rounded" style="height:4px;margin-top:2px"><div class="bg-info rounded" style="height:4px;width:<?=$pct?>%"></div></div>
              </td>
              <td class="text-end small"><?=$c['bills']?></td>
              <td class="text-end small fw-semibold"><?=currency($c['total'])?></td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
        <?php else:?>
        <div class="text-center text-muted py-4 small">No sales today.</div>
        <?php endif;?>
      </div>
    </div>
  </div>

  <!-- Expenses breakdown -->
  <div class="col-md-4">
    <div class="card h-100">
      <div class="card-header fw-semibold small bg-transparent d-flex justify-content-between">
        <span><i class="bi bi-wallet2 me-1 text-danger"></i>Expenses</span>
        <span class="fw-bold text-danger"><?=currency($expenseSummary['total'])?></span>
      </div>
      <div class="card-body p-0">
        <?php if(!empty($expenses)):?>
        <table class="table table-sm mb-0">
          <thead class="table-secondary"><tr><th>Title</th><th>Category</th><th class="text-end">Amount</th></tr></thead>
          <tbody>
            <?php foreach($expenses as $e):?>
            <tr><td class="small fw-semibold"><?=e($e['title'])?></td><td class="small text-muted"><?=e($e['category_name'])?></td><td class="text-end small text-danger fw-semibold"><?=currency($e['amount'])?></td></tr>
            <?php endforeach;?>
          </tbody>
          <tfoot class="table-secondary fw-bold"><tr><td colspan="2">Total</td><td class="text-end text-danger"><?=currency($expenseSummary['total'])?></td></tr></tfoot>
        </table>
        <?php else:?>
        <div class="text-center text-muted py-4 small">No expenses today.</div>
        <?php endif;?>
      </div>
    </div>
  </div>

</div>

<!-- Top 10 Products -->
<?php if(!empty($topProducts)):?>
<div class="row g-3 mb-3">
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header fw-semibold small bg-transparent d-flex justify-content-between">
        <span><i class="bi bi-trophy me-1 text-warning"></i>Top 10 Products Today</span>
        <small class="text-muted fw-normal"><?=count($topProducts)?> products</small>
      </div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <thead class="table-dark"><tr><th>#</th><th>Product</th><th class="text-end">Qty</th><th class="text-end">Revenue</th><th class="text-end">Profit</th></tr></thead>
          <tbody>
            <?php foreach($topProducts as $i=>$p):
              $m=$p['revenue']>0?round($p['profit']/$p['revenue']*100,1):0;
            ?>
            <tr>
              <td class="text-muted"><?=$i+1?></td>
              <td>
                <div class="small fw-semibold"><?=e($p['product_name'])?></div>
                <code style="font-size:.65rem" class="text-muted"><?=e($p['product_code'])?></code>
              </td>
              <td class="text-end small"><?=number_format($p['qty_sold'],2)?></td>
              <td class="text-end fw-semibold small"><?=currency($p['revenue'])?></td>
              <td class="text-end small">
                <span class="badge <?=$m>=20?'bg-success':($m>=10?'bg-warning text-dark':'bg-secondary')?>"><?=$m?>%</span>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- P&L summary box -->
  <div class="col-lg-5">
    <div class="card h-100">
      <div class="card-header fw-semibold small bg-transparent">
        <i class="bi bi-graph-up me-1 text-success"></i>Day Summary
      </div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <tbody>
            <tr class="table-light"><td colspan="2" class="fw-bold small ps-3 py-2" style="color:#0f2557;text-transform:uppercase;letter-spacing:.5px;font-size:.7rem">Revenue</td></tr>
            <tr><td class="ps-4 small">Gross Sales</td><td class="text-end pe-3 fw-semibold text-success small"><?=currency($salesSummary['total'])?></td></tr>
            <tr><td class="ps-4 small text-danger">Less: Discounts</td><td class="text-end pe-3 text-danger small">(<?=currency($salesSummary['discount'])?>)</td></tr>
            <tr class="table-light"><td colspan="2" class="fw-bold small ps-3 py-2" style="color:#0f2557;text-transform:uppercase;letter-spacing:.5px;font-size:.7rem">Cost</td></tr>
            <tr><td class="ps-4 small text-danger">Cost of Goods Sold</td><td class="text-end pe-3 text-danger small">(<?=currency($cogs)?>)</td></tr>
            <tr class="fw-bold" style="background:#e8edf5"><td class="ps-3 small">Gross Profit</td><td class="text-end pe-3 <?=$grossProfit>=0?'text-success':'text-danger'?> small"><?=currency(abs($grossProfit))?></td></tr>
            <tr class="table-light"><td colspan="2" class="fw-bold small ps-3 py-2" style="color:#0f2557;text-transform:uppercase;letter-spacing:.5px;font-size:.7rem">Expenses</td></tr>
            <tr><td class="ps-4 small text-danger">Total Expenses</td><td class="text-end pe-3 text-danger small">(<?=currency($expenseSummary['total'])?>)</td></tr>
            <?php if($purchaseSummary['total']>0):?>
            <tr class="table-light"><td colspan="2" class="fw-bold small ps-3 py-2" style="color:#0f2557;text-transform:uppercase;letter-spacing:.5px;font-size:.7rem">Purchases</td></tr>
            <tr><td class="ps-4 small">Purchases Total</td><td class="text-end pe-3 small"><?=currency($purchaseSummary['total'])?></td></tr>
            <?php endif;?>
            <tr style="background:#0f2557;color:#fff" class="fw-bold">
              <td class="ps-3 py-2">NET <?=$netProfit>=0?'PROFIT':'LOSS'?></td>
              <td class="text-end pe-3" style="font-size:11pt;color:<?=$netProfit>=0?'#4ade80':'#f87171'?>"><?=currency(abs($netProfit))?></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php endif;?>

<!-- Sales List -->
<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 Invoices — <?=date('d M Y',strtotime($date))?></span>
    <small class="text-muted fw-normal"><?=count($sales)?> invoices</small>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0">
      <thead class="table-dark"><tr><th>#</th><th>Invoice</th><th>Customer</th><th>Time</th><th>Cashier</th><th>Method</th><th class="text-end">Total</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"><?=$i+1?></td>
          <td><a href="<?=APP_URL?>/sales/view/<?=$s['id']?>" class="fw-semibold text-decoration-none small no-print"><?=e($s['invoice_no'])?></a><span class="print-only fw-semibold small"><?=e($s['invoice_no'])?></span></td>
          <td class="small"><?=e($s['customer_name'])?></td>
          <td class="small text-muted"><?=fDate($s['sale_date'],'H:i')?></td>
          <td class="small text-muted"><?=e($s['cashier_name']??'—')?></td>
          <td><span class="badge bg-light text-dark border" style="font-size:.62rem"><?=e($s['methods']??'—')?></span></td>
          <td class="text-end fw-semibold small"><?=currency($s['total'])?></td>
        </tr>
        <?php endforeach;?>
        <?php if(empty($sales)):?><tr><td colspan="7" class="text-center text-muted py-4">No sales on this date.</td></tr><?php endif;?>
      </tbody>
      <?php if(!empty($sales)):?>
      <tfoot class="table-secondary fw-bold">
        <tr><td colspan="6">TOTAL (<?=count($sales)?> invoices)</td>
          <td class="text-end"><?=currency($salesSummary['total'])?></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>
</div>

<!-- Purchases -->
<?php if(!empty($purchases)):?>
<div class="card">
  <div class="card-header fw-semibold small d-flex justify-content-between align-items-center">
    <span><i class="bi bi-truck me-1"></i>Purchases — <?=date('d M Y',strtotime($date))?></span>
    <span class="badge bg-info text-dark"><?=count($purchases)?> orders</span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm mb-0">
      <thead class="table-dark"><tr><th>#</th><th>Invoice</th><th>Supplier</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($purchases as $i=>$p):?>
        <tr>
          <td class="text-muted"><?=$i+1?></td>
          <td class="fw-semibold small"><?=e($p['invoice_no'])?></td>
          <td class="small"><?=e($p['supplier_name'])?></td>
          <td class="text-end small fw-semibold"><?=currency($p['total'])?></td>
          <td class="text-end text-success small"><?=currency($p['paid'])?></td>
          <td class="text-end small <?=$p['balance']>0?'text-danger fw-bold':''?>"><?=$p['balance']>0?currency($p['balance']):'—'?></td>
          <td><span class="badge <?=$p['payment_status']==='paid'?'bg-success':($p['payment_status']==='partial'?'bg-warning text-dark':'bg-danger')?>" style="font-size:.62rem"><?=ucfirst($p['payment_status'])?></span></td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <tfoot class="table-secondary fw-bold">
        <tr><td colspan="3">TOTAL</td>
          <td class="text-end"><?=currency($purchaseSummary['total'])?></td>
          <td class="text-end text-success"><?=currency($purchaseSummary['paid'])?></td>
          <td class="text-end text-danger"><?=$purchaseSummary['balance']>0?currency($purchaseSummary['balance']):'—'?></td>
          <td></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>
<?php endif;?>
<style>.print-only{display:none}@media print{.print-only{display:inline}.no-print{display:none!important}}</style>

<!-- ═══════════════════════════════════════════════════════════ -->
<!-- PAYROLL SECTION — Attendance + Payroll Period              -->
<!-- ═══════════════════════════════════════════════════════════ -->
<?php if($payrollShowable && !empty($attSummary)): ?>

<hr class="my-4">

<!-- Section header -->
<div class="d-flex justify-content-between align-items-center mb-3">
  <h6 class="fw-bold mb-0 d-flex align-items-center gap-2">
    <i class="bi bi-fingerprint text-success fs-5"></i>
    Payroll & Attendance — <?= date('d F Y', strtotime($date)) ?>
  </h6>
  <a href="<?= APP_URL ?>/payroll/attendance-chart?date=<?= $date ?>"
     class="btn btn-sm btn-outline-success no-print">
    <i class="bi bi-bar-chart-line me-1"></i>Full Chart
  </a>
</div>

<!-- Attendance KPI row -->
<div class="row g-2 mb-3">
  <?php
  $totalEmp = (int)($attSummary['total_employees'] ?? 0);
  $present  = (int)($attSummary['present']  ?? 0);
  $absent   = (int)($attSummary['absent']   ?? 0);
  $late     = (int)($attSummary['late']     ?? 0);
  $halfDay  = (int)($attSummary['half_day'] ?? 0);
  $leave    = (int)($attSummary['leave_days'] ?? 0);
  $fpCount  = (int)($attSummary['fp_count'] ?? 0);
  $totalOT  = (float)($attSummary['total_ot'] ?? 0);
  $totalWrk = (float)($attSummary['total_worked'] ?? 0);
  $attPct   = $totalEmp > 0 ? round(($present+$late+$halfDay)/$totalEmp*100) : 0;
  foreach([
    [$present, 'Present',  '#16a34a', 'bi-person-check'],
    [$absent,  'Absent',   '#dc2626', 'bi-person-x'],
    [$late,    'Late',     '#d97706', 'bi-clock'],
    [$halfDay, 'Half Day', '#0891b2', 'bi-person-dash'],
    [$leave,   'Leave',    '#7c3aed', 'bi-calendar-x'],
    [$fpCount, 'FP Scans', '#059669', 'bi-fingerprint'],
  ] as[$val,$lbl,$clr,$icon]):?>
  <div class="col-6 col-md-2">
    <div class="card text-center py-2" style="border-top:3px solid <?=$clr?>">
      <i class="bi <?=$icon?> mb-1" style="color:<?=$clr?>;font-size:1.1rem"></i>
      <div class="fw-bold" style="color:<?=$clr?>;font-size:1.1rem"><?=$val?></div>
      <div style="font-size:.65rem;color:#94a3b8;text-transform:uppercase"><?=$lbl?></div>
    </div>
  </div>
  <?php endforeach;?>
</div>

<!-- Attendance progress + stats -->
<div class="row g-3 mb-3">
  <div class="col-md-4">
    <div class="card p-3 h-100">
      <div class="fw-semibold small mb-2 text-muted">Attendance Rate</div>
      <div class="fw-bold" style="font-size:2rem;color:<?=$attPct>=80?'#16a34a':($attPct>=60?'#d97706':'#dc2626')?>"><?=$attPct?>%</div>
      <div style="height:10px;background:#f1f5f9;border-radius:5px;margin:8px 0">
        <div style="height:10px;border-radius:5px;width:<?=$attPct?>%;background:<?=$attPct>=80?'#16a34a':($attPct>=60?'#d97706':'#dc2626')?>"></div>
      </div>
      <div class="text-muted small"><?=$present+$late+$halfDay?> of <?=$totalEmp?> employees in</div>
      <div class="mt-2 d-flex gap-2 small">
        <span class="text-warning"><i class="bi bi-clock me-1"></i><?=number_format($totalOT,1)?>h OT</span>
        <span class="text-muted"><i class="bi bi-hourglass me-1"></i><?=number_format($totalWrk,1)?>h worked</span>
      </div>
    </div>
  </div>
  <div class="col-md-8">
    <canvas id="attChart" height="100"></canvas>
  </div>
</div>

<!-- Attendance detail table -->
<?php if(!empty($attDetail)): ?>
<div class="card mb-3">
  <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
    <span><i class="bi bi-table me-1"></i>Employee Attendance Detail</span>
    <span class="badge bg-secondary"><?=count($attDetail)?> records</span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 align-middle" style="font-size:.78rem">
      <thead class="table-secondary">
        <tr>
          <th class="ps-3">#</th>
          <th>Employee</th>
          <th>Dept</th>
          <th class="text-center">Status</th>
          <th class="text-center">Check In</th>
          <th class="text-center">Check Out</th>
          <th class="text-center">Worked</th>
          <th class="text-center">OT</th>
          <th class="text-center">Method</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $stColors=['present'=>'#16a34a','late'=>'#d97706','absent'=>'#dc2626',
                   'half_day'=>'#0891b2','leave'=>'#7c3aed'];
        $stBadge=['present'=>'bg-success','late'=>'bg-warning text-dark','absent'=>'bg-danger',
                  'half_day'=>'bg-info text-dark','leave'=>'bg-primary'];
        $methodIcon=['fingerprint'=>'bi-fingerprint','manual'=>'bi-pencil',
                     'qr'=>'bi-qr-code','card'=>'bi-credit-card','face'=>'bi-person-bounding-box'];
        foreach($attDetail as $i=>$a):
          $clr = $stColors[$a['status']] ?? '#64748b';
        ?>
        <tr>
          <td class="ps-3 text-muted"><?=$i+1?></td>
          <td>
            <div class="fw-semibold"><?=e($a['full_name'])?></div>
            <div style="font-size:.65rem;color:#94a3b8">
              <code><?=e($a['emp_code'])?></code>
              <?=e($a['designation']??' ')?>&nbsp;
              <?php if($a['fingerprint_id']):?>
              <i class="bi bi-fingerprint text-success" title="<?=e($a['fingerprint_id'])?>"></i>
              <?php endif;?>
            </div>
          </td>
          <td class="text-muted small"><?=e($a['department']??'—')?></td>
          <td class="text-center">
            <span class="badge <?=$stBadge[$a['status']]??'bg-secondary'?>" style="font-size:.65rem">
              <?=ucfirst(str_replace('_',' ',$a['status']))?>
            </span>
          </td>
          <td class="text-center fw-semibold"><?=$a['check_in']?substr($a['check_in'],0,5):'—'?></td>
          <td class="text-center <?=$a['check_out']?'':'text-muted'?>"><?=$a['check_out']?substr($a['check_out'],0,5):'—'?></td>
          <td class="text-center"><?=$a['worked_hours']>0?number_format($a['worked_hours'],1).'h':'—'?></td>
          <td class="text-center <?=$a['ot_hours']>0?'text-warning fw-bold':''?>">
            <?=$a['ot_hours']>0?number_format($a['ot_hours'],1).'h':'—'?>
          </td>
          <td class="text-center">
            <i class="bi <?=$methodIcon[$a['method']]??'bi-dot'?>"
               style="color:<?=$a['method']==='fingerprint'?'#16a34a':'#94a3b8'?>"
               title="<?=ucfirst($a['method'])?>"></i>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <tfoot class="table-secondary fw-bold" style="font-size:.72rem">
        <tr>
          <td colspan="6" class="ps-3">TOTAL (<?=count($attDetail)?> records)</td>
          <td class="text-center"><?=number_format($totalWrk,1)?>h</td>
          <td class="text-center text-warning"><?=$totalOT>0?number_format($totalOT,1).'h':'—'?></td>
          <td></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>
<?php endif;?>

<!-- Payroll Period for this month -->
<?php if($payrollPeriodInfo): ?>
<div class="card mb-3">
  <div class="card-header bg-success text-white fw-semibold small d-flex justify-content-between">
    <span><i class="bi bi-cash-coin me-1"></i>Payroll Period — <?=e($payrollPeriodInfo['period_name'])?></span>
    <?php $stBadgeP=['draft'=>'bg-secondary','processing'=>'bg-warning text-dark','approved'=>'bg-info text-dark','paid'=>'bg-light text-success'];?>
    <span class="badge <?=$stBadgeP[$payrollPeriodInfo['status']]??'bg-secondary'?>">
      <?=ucfirst($payrollPeriodInfo['status'])?>
    </span>
  </div>
  <div class="card-body">
    <div class="row g-3 text-center">
      <div class="col-md-3">
        <div class="fw-bold fs-5 text-primary"><?=(int)$payrollPeriodInfo['emp_processed']?></div>
        <div class="text-muted small">Employees Processed</div>
      </div>
      <div class="col-md-3">
        <div class="fw-bold fs-5 text-success"><?=currency($payrollPeriodInfo['total_gross'])?></div>
        <div class="text-muted small">Gross Salary</div>
      </div>
      <div class="col-md-3">
        <div class="fw-bold fs-5 text-danger"><?=currency($payrollPeriodInfo['total_statutory'])?></div>
        <div class="text-muted small">EPF + ETF Deductions</div>
      </div>
      <div class="col-md-3">
        <div class="fw-bold fs-5 text-success"><?=currency($payrollPeriodInfo['total_net'])?></div>
        <div class="text-muted small">Net Payable</div>
      </div>
    </div>
  </div>
</div>
<?php endif;?>

<!-- Attendance doughnut chart -->
<script>
(function(){
  const ctx = document.getElementById('attChart');
  if (!ctx) return;
  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['Present','Late','Half Day','Leave','Absent'],
      datasets:[{
        data: [<?=$present?>,<?=$late?>,<?=$halfDay?>,<?=$leave?>,<?=$absent?>],
        backgroundColor:['#16a34a','#d97706','#0891b2','#7c3aed','#dc2626'],
        borderWidth:2, borderColor:'#fff'
      }]
    },
    options:{responsive:true,plugins:{
      legend:{position:'right',labels:{font:{size:11},boxWidth:12}},
      tooltip:{callbacks:{label:ctx=>`${ctx.label}: ${ctx.raw} (${Math.round(ctx.raw/<?=max($totalEmp,1)?>*100)}%)`}}
    }}
  });
})();
</script>

<?php endif; // payrollShowable ?>