<?php /* reports/cashier.php — Advanced Edition */
$sym = setting('currency_symbol','Rs.');
function curr($v) { global $sym; return $sym.number_format((float)$v,2); }
?>
<?php include APP_PATH.'/views/partials/report_header.php'; ?>
<style>
.rpt-hero{background:#0f172a;border-radius:14px;padding:20px 26px;color:#fff;
  margin-bottom:18px;border:1px solid #1e293b;box-shadow:0 4px 20px rgba(0,0,0,.15)}
.rpt-hero .page-title{font-size:1.2rem;font-weight:800;display:flex;align-items:center;gap:10px;margin-bottom:4px}
.rpt-hero .page-meta{font-size:.78rem;color:#94a3b8;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.rpt-hero .sep{color:#334155}
.hero-btn{border-radius:10px;font-weight:600;font-size:.8rem;padding:7px 14px;
  display:inline-flex;align-items:center;gap:6px;text-decoration:none;transition:all .15s;border:1px solid #334155;color:#94a3b8;background:transparent}
.hero-btn:hover{background:#1e293b;color:#fff;border-color:#475569}

.kpi-tile{border-radius:12px;padding:16px 18px;height:100%;border:1.5px solid transparent}
.kpi-tile .kv{font-size:1.35rem;font-weight:900;line-height:1;margin-bottom:3px}
.kpi-tile .kl{font-size:.63rem;text-transform:uppercase;letter-spacing:.06em;font-weight:700;opacity:.75}
.kpi-tile .ks{font-size:.72rem;margin-top:5px;opacity:.8}

.date-btn{border-radius:8px;padding:4px 12px;font-size:.72rem;font-weight:600;
  border:1.5px solid #e2e8f0;background:#fff;color:#475569;text-decoration:none;transition:all .12s}
.date-btn.active,.date-btn:hover{background:#0f172a;color:#fff;border-color:#0f172a}

.cr-table th{font-size:.68rem;padding:8px 10px;white-space:nowrap}
.cr-table td{font-size:.77rem;padding:7px 10px;vertical-align:middle}
.cr-table tr:hover td{background:#fafbff}

.cash-avatar{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;
  justify-content:center;font-size:.78rem;font-weight:700;flex-shrink:0}
.perf-bar-wrap{width:80px;height:5px;background:#f1f5f9;border-radius:3px;overflow:hidden;margin-top:3px}
.perf-bar{height:5px;border-radius:3px;background:#3b82f6}

.pmt-cell{font-size:.72rem;text-align:right;font-weight:600}
.pmt-zero{color:#cbd5e1}

.top-badge{display:inline-flex;align-items:center;gap:3px;background:#fef9c3;color:#92400e;
  border-radius:12px;padding:1px 7px;font-size:.6rem;font-weight:700}

@media print{
  .no-print{display:none!important}
  .rpt-hero,.kpi-tile{color-adjust:exact;-webkit-print-color-adjust:exact}
}
</style>


<?= flashMessages() ?>

<!-- ── Date Filters ───────────────────────────────────── -->
<div class="card mb-3 no-print">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/reports/cashier"
          class="d-flex gap-2 flex-wrap align-items-center">
      <input type="date" name="from" class="form-control form-control-sm"
             value="<?=e($from)?>" style="width:136px">
      <span class="text-muted small">to</span>
      <input type="date" name="to" class="form-control form-control-sm"
             value="<?=e($to)?>" style="width:136px">
      <select name="cashier" class="form-select form-select-sm" style="width:160px">
        <option value="0">All Cashiers</option>
        <?php foreach($cashiers as $c):?>
        <option value="<?=$c['id']?>" <?=$cashierId==$c['id']?'selected':''?>>
          <?=e($c['name'])?>
        </option>
        <?php endforeach;?>
      </select>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/reports/cashier" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <!-- Date shortcuts -->
      <?php foreach([
        'Today'      => [date('Y-m-d'),                          date('Y-m-d')],
        'This Week'  => [date('Y-m-d',strtotime('monday')),      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 month'))],
      ] as $lbl=>[$f,$t]):
        $act = ($from===$f && $to===$t);
      ?>
      <a href="?from=<?=$f?>&to=<?=$t?>" class="date-btn <?=$act?'active':''?>"><?=$lbl?></a>
      <?php endforeach;?>
    </form>
  </div>
</div>

<!-- ── KPI Tiles ──────────────────────────────────────── -->
<div class="row g-3 mb-4">
  <div class="col-6 col-md-2">
    <div class="kpi-tile" style="background:#eff6ff;border-color:#bfdbfe">
      <div class="kl text-primary">Cashiers</div>
      <div class="kv text-primary"><?=count($rows)?></div>
      <div class="ks text-muted"><?=$days?> day period</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-tile" style="background:#f5f3ff;border-color:#c4b5fd">
      <div class="kl" style="color:#7c3aed">Total Bills</div>
      <div class="kv" style="color:#7c3aed"><?=number_format($grandBills)?></div>
      <div class="ks text-muted"><?=round($grandBills/$days,1)?>/day avg</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-tile" style="background:#eff6ff;border-color:#93c5fd">
      <div class="kl text-primary">Total Revenue</div>
      <div class="kv text-primary"><?=curr($grandTotal)?></div>
      <div class="ks text-muted">Avg <?=curr($grandBills>0?$grandTotal/$grandBills:0)?>/bill</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="kpi-tile" style="background:#ecfdf5;border-color:#6ee7b7">
      <div class="kl" style="color:#0891b2">Gross Profit</div>
      <div class="kv" style="color:#0891b2"><?=curr($grandProfit)?></div>
      <div class="ks text-muted"><?=$grandTotal>0?round($grandProfit/$grandTotal*100,1):0?>% margin</div>
    </div>
  </div>
  <div class="col-6 col-md-1">
    <div class="kpi-tile" style="background:<?=$grandBal>0?'#fef2f2':'#f0fdf4'?>;border-color:<?=$grandBal>0?'#fca5a5':'#86efac'?>">
      <div class="kl" style="color:<?=$grandBal>0?'#dc2626':'#16a34a'?>">Due</div>
      <div class="kv" style="color:<?=$grandBal>0?'#dc2626':'#16a34a'?>;font-size:1rem">
        <?=$grandBal>0?curr($grandBal):'✅'?>
      </div>
    </div>
  </div>
</div>

<!-- ── Performance Table ──────────────────────────────── -->
<div class="card mb-4">
  <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-bar-chart me-1"></i>
      Cashier Performance &nbsp;·&nbsp;
      <?=date('d M Y',strtotime($from))?> – <?=date('d M Y',strtotime($to))?>
    </span>
    <span class="badge bg-secondary"><?=count($rows)?> cashier<?=count($rows)!=1?'s':''?></span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 cr-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Cashier</th>
          <th class="text-center">Bills</th>
          <th class="text-center">Avg/Day</th>
          <th class="text-end">Total Sales</th>
          <th class="text-end">Discount</th>
          <th class="text-end">Gross Profit</th>
          <th class="text-center">Margin</th>
          <th class="text-center">Share</th>
          <th class="text-end">Due</th>
          <th class="text-center no-print">Action</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $i=>$row):
          $isTop   = (float)$row['total'] >= $maxTotal && $maxTotal > 0;
          $avgDay  = round((float)$row['bills']/$days,1);
          $margin  = (float)$row['total']>0?round((float)$row['gross_profit']/(float)$row['total']*100,1):0;
          $share   = $grandTotal>0?round((float)$row['total']/$grandTotal*100,1):0;
          $perfPct = $maxTotal>0?round((float)$row['total']/$maxTotal*100):0;
          $initials= strtoupper(substr($row['name'],0,1).(strpos($row['name'],' ')!==false?substr(strrchr($row['name'],' '),1,1):''));
          $colors  = ['#3b82f6','#8b5cf6','#ec4899','#f59e0b','#10b981','#6366f1'];
          $ac      = $colors[$i%count($colors)];
          $mClr    = $margin>=20?'#16a34a':($margin>=10?'#d97706':'#dc2626');
          $mBg     = $margin>=20?'#f0fdf4':($margin>=10?'#fffbeb':'#fef2f2');
        ?>
        <tr>
          <td class="ps-3 text-muted small"><?=$i+1?></td>

          <!-- Cashier -->
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="cash-avatar" style="background:<?=$ac?>18;color:<?=$ac?>">
                <?=e($initials)?>
              </div>
              <div>
                <div class="d-flex align-items-center gap-1">
                  <a href="<?=APP_URL?>/reports/cashier/<?=$row['cashier_id']?>?from=<?=$from?>&to=<?=$to?>"
                     class="fw-semibold text-decoration-none text-dark small no-print">
                    <?=e($row['name'])?>
                  </a>
                  <span class="print-only fw-semibold small"><?=e($row['name'])?></span>
                  <?php if($isTop):?>
                  <span class="top-badge no-print">🏆 Top</span>
                  <?php endif;?>
                </div>
                <?php if($row['due_count']>0):?>
                <div style="font-size:.62rem;color:#dc2626">
                  <i class="bi bi-exclamation-circle me-1"></i><?=$row['due_count']?> unpaid bill<?=$row['due_count']>1?'s':''?>
                </div>
                <?php endif;?>
                <div class="perf-bar-wrap">
                  <div class="perf-bar" style="width:<?=$perfPct?>%;background:<?=$ac?>"></div>
                </div>
              </div>
            </div>
          </td>

          <!-- Bills -->
          <td class="text-center fw-bold" style="color:<?=$ac?>"><?=number_format((int)$row['bills'])?></td>
          <td class="text-center text-muted small"><?=$avgDay?>/d</td>

          <!-- Financials -->
          <td class="text-end fw-bold"><?=curr($row['total'])?></td>
          <td class="text-end" style="color:#dc2626;font-size:.72rem">
            <?=(float)$row['discount']>0?curr($row['discount']):'—'?>
          </td>
          <td class="text-end fw-semibold" style="color:#0891b2"><?=curr($row['gross_profit'])?></td>

          <!-- Margin badge -->
          <td class="text-center">
            <span style="background:<?=$mBg?>;color:<?=$mClr?>;border-radius:10px;
                         padding:2px 8px;font-size:.65rem;font-weight:700">
              <?=$margin?>%
            </span>
          </td>

          <!-- Share -->
          <td class="text-center">
            <div style="font-size:.72rem;font-weight:700;color:#475569"><?=$share?>%</div>
          </td>

          <!-- Due -->
          <td class="text-end">
            <?php if((float)$row['balance']>0):?>
            <span style="color:#dc2626;font-weight:700;font-size:.75rem"><?=curr($row['balance'])?></span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Action -->
          <td class="text-center no-print">
            <a href="<?=APP_URL?>/reports/cashier/<?=$row['cashier_id']?>?from=<?=$from?>&to=<?=$to?>"
               class="btn btn-sm btn-outline-primary py-0 px-2" title="Detail">
              <i class="bi bi-eye"></i>
            </a>
          </td>
        </tr>
        <?php endforeach;?>
        <?php if(empty($rows)):?>
        <tr>
          <td colspan="12" class="text-center text-muted py-5">
            <i class="bi bi-person-badge d-block fs-2 mb-2 opacity-25"></i>
            No cashier data for this period.
          </td>
        </tr>
        <?php endif;?>
      </tbody>
      <?php if(!empty($rows)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.73rem">
        <tr>
          <td colspan="2" class="ps-3">TOTAL (<?=count($rows)?> cashiers)</td>
          <td class="text-center"><?=number_format($grandBills)?></td>
          <td class="text-center text-muted"><?=round($grandBills/$days,1)?>/d</td>
          <td class="text-end"><?=curr($grandTotal)?></td>
          <td class="text-end" style="color:#dc2626"><?=curr(array_sum(array_column($rows,'discount')))?></td>
          <td class="text-end" style="color:#0891b2"><?=curr($grandProfit)?></td>
          <td class="text-center">
            <?php $gm=$grandTotal>0?round($grandProfit/$grandTotal*100,1):0;?>
            <span style="font-size:.7rem"><?=$gm?>%</span>
          </td>
          <td class="text-center">100%</td>
          <td class="text-end" style="color:<?=$grandBal>0?'#dc2626':'#16a34a'?>">
            <?=$grandBal>0?curr($grandBal):'—'?>
          </td>
          <td class="no-print"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>
</div>

<!-- ── Payment Method Breakdown ───────────────────────── -->
<?php if(!empty($rows) && !empty($pmtByCashier)):?>
<div class="card">
  <div class="card-header fw-semibold small bg-dark text-white">
    <i class="bi bi-credit-card me-1"></i>Payment Method Breakdown by Cashier
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 cr-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">Cashier</th>
          <th class="text-end">💵 Cash</th>
          <th class="text-end">💳 Card</th>
          <th class="text-end">🏦 Bank</th>
          <th class="text-end">📱 Mobile</th>
          <th class="text-end">📒 Credit</th>
          <th class="text-end">📝 Cheque</th>
          <th class="text-end fw-bold">Total</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $i=>$row):
          $pm = $pmtByCashier[$row['cashier_id']] ?? [];
          $colors2 = ['#3b82f6','#8b5cf6','#ec4899','#f59e0b','#10b981','#6366f1'];
          $ac2 = $colors2[$i%count($colors2)];
          $init2 = strtoupper(substr($row['name'],0,1));
        ?>
        <tr>
          <td class="ps-3">
            <div class="d-flex align-items-center gap-2">
              <div style="width:28px;height:28px;border-radius:8px;background:<?=$ac2?>18;
                          color:<?=$ac2?>;display:flex;align-items:center;justify-content:center;
                          font-size:.65rem;font-weight:700;flex-shrink:0">
                <?=$init2?>
              </div>
              <span class="fw-semibold small"><?=e($row['name'])?></span>
            </div>
          </td>
          <?php foreach(['cash','card','bank_transfer','mobile','credit','cheque'] as $m):
            $v = (float)($pm[$m] ?? 0);
          ?>
          <td class="pmt-cell <?=$v>0?'':'pmt-zero'?>">
            <?=$v>0?curr($v):'—'?>
          </td>
          <?php endforeach;?>
          <td class="text-end fw-bold"><?=curr($row['total'])?></td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <tfoot class="table-secondary fw-bold" style="font-size:.73rem">
        <tr>
          <td class="ps-3">TOTAL</td>
          <?php foreach(['cash','card','bank_transfer','mobile','credit','cheque'] as $m):
            $t = array_sum(array_map(fn($c)=>(float)($pmtByCashier[$c['cashier_id']][$m]??0),$rows));
          ?>
          <td class="text-end"><?=$t>0?curr($t):'—'?></td>
          <?php endforeach;?>
          <td class="text-end"><?=curr($grandTotal)?></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>
<?php endif;?>

<style>
.print-only{display:none}
@media print{
  .print-only{display:inline!important}
  .no-print{display:none!important}
  .card{break-inside:avoid}
  .rpt-hero{background:#0f172a!important;-webkit-print-color-adjust:exact}
}
</style>