<?php /* reports/sales.php — Advanced Edition */
$sym = setting('currency_symbol','Rs.');
?>
<?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}

.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}

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

.pmt-bar{height:5px;border-radius:3px;background:#f1f5f9;overflow:hidden;margin-top:4px}
.pmt-fill{height:5px;border-radius:3px}

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


<?= flashMessages() ?>

<!-- ── Filters ────────────────────────────────────────── -->
<div class="card mb-3 no-print">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/reports/sales"
          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="group" class="form-select form-select-sm" style="width:120px">
        <option value="day"   <?=$groupBy==='day'?  'selected':''?>>Daily</option>
        <option value="week"  <?=$groupBy==='week'? 'selected':''?>>Weekly</option>
        <option value="month" <?=$groupBy==='month'?'selected':''?>>Monthly</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?>/reports/sales" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <?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'))],
        'This Year'  => [date('Y-01-01'),                       date('Y-m-d')],
      ] as $lbl=>[$f,$t]):
        $act = ($from===$f && $to===$t);
      ?>
      <a href="?from=<?=$f?>&to=<?=$t?>&group=<?=e($groupBy)?>"
         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-3">
    <div class="kpi-tile" style="background:#f5f3ff;border-color:#c4b5fd">
      <div class="kl" style="color:#7c3aed">Total Invoices</div>
      <div class="kv" style="color:#7c3aed"><?=number_format($totals['count'])?></div>
      <div class="ks text-muted">
        <?php $days=max(1,(int)((strtotime($to)-strtotime($from))/86400)+1);?>
        <?=round($totals['count']/$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">Gross Revenue</div>
      <div class="kv text-primary"><?=currency($totals['total'])?></div>
      <div class="ks text-muted">
        Avg <?=currency($totals['count']>0?$totals['total']/$totals['count']:0)?>/invoice
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-tile" style="background:#fff7ed;border-color:#fed7aa">
      <div class="kl" style="color:#ea580c">Total Discount</div>
      <div class="kv" style="color:#ea580c"><?=currency($totals['discount'])?></div>
      <div class="ks text-muted">
        <?=$totals['total']>0?round($totals['discount']/$totals['total']*100,1):0?>% of revenue
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-tile"
         style="background:<?=$totals['balance']>0?'#fef2f2':'#f0fdf4'?>;
                border-color:<?=$totals['balance']>0?'#fca5a5':'#86efac'?>">
      <div class="kl" style="color:<?=$totals['balance']>0?'#dc2626':'#16a34a'?>">
        Balance Due
      </div>
      <div class="kv" style="color:<?=$totals['balance']>0?'#dc2626':'#16a34a'?>">
        <?=$totals['balance']>0?currency($totals['balance']):'✅ Rs.0'?>
      </div>
    </div>
  </div>
</div>

<!-- ── Period Breakdown 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-table me-1"></i>
      Sales Breakdown — <?=ucfirst($groupBy)?> &nbsp;·&nbsp;
      <?=fDate($from,'d M Y')?> to <?=fDate($to,'d M Y')?>
    </span>
    <span class="badge bg-secondary"><?=count($rows)?> period<?=count($rows)!=1?'s':''?></span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 rpt-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Period</th>
          <th class="text-end">Invoices</th>
          <th class="text-end">Subtotal</th>
          <th class="text-end">Discount</th>
          <th class="text-end">Tax</th>
          <th class="text-end fw-bold">Total</th>
          <th class="text-end">Balance</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $i=>$r):
          $isTop = (float)$r['total'] >= $maxTotal && $maxTotal > 0;
          $sharePct = $totals['total']>0?round($r['total']/$totals['total']*100,1):0;
        ?>
        <tr>
          <td class="ps-3 text-muted"><?=$i+1?></td>
          <td class="fw-semibold">
            <?=e($r['period'])?>
            <?php if($isTop):?>
            <span class="badge bg-warning text-dark no-print" style="font-size:.58rem">★ Peak</span>
            <?php endif;?>
            <div style="font-size:.62rem;color:#94a3b8"><?=$sharePct?>% of period total</div>
          </td>
          <td class="text-end"><?=number_format($r['count'])?></td>
          <td class="text-end text-muted"><?=currency($r['subtotal'])?></td>
          <td class="text-end" style="color:#ea580c"><?=(float)$r['discount']>0?currency($r['discount']):'—'?></td>
          <td class="text-end text-muted"><?=(float)$r['tax']>0?currency($r['tax']):'—'?></td>
          <td class="text-end fw-bold"><?=currency($r['total'])?></td>
          <td class="text-end">
            <?php if((float)$r['balance']>0):?>
            <span style="color:#dc2626;font-weight:700"><?=currency($r['balance'])?></span>
            <?php else:?>
            <span style="color:#16a34a"><i class="bi bi-check-circle-fill"></i></span>
            <?php endif;?>
          </td>
        </tr>
        <?php endforeach;?>
        <?php if(empty($rows)):?>
        <tr>
          <td colspan="8" class="text-center text-muted py-5">
            <i class="bi bi-bar-chart d-block fs-2 mb-2 opacity-25"></i>
            No sales in 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)?> periods)</td>
          <td class="text-end"><?=number_format($totals['count'])?></td>
          <td class="text-end"><?=currency((float)$totals['total']-(float)$totals['discount']-(float)$totals['tax'])?></td>
          <td class="text-end" style="color:#ea580c"><?=currency($totals['discount'])?></td>
          <td class="text-end"><?=currency($totals['tax'])?></td>
          <td class="text-end"><?=currency($totals['total'])?></td>
          <td class="text-end">
            <?=$totals['balance']>0
              ? '<span style="color:#dc2626">'.currency($totals['balance']).'</span>'
              : '<span style="color:#16a34a">—</span>'?>
          </td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>
</div>

<!-- ── Payment Method Breakdown ──────────────────────── -->
<?php if(!empty($pmtBreakdown)):?>
<div class="card">
  <div class="card-header bg-dark text-white fw-semibold small">
    <i class="bi bi-credit-card me-1"></i>Payment Method Breakdown
  </div>
  <div class="card-body">
    <?php
    $pmtTotal  = array_sum(array_column($pmtBreakdown,'total'));
    $pmtColors = ['cash'=>'#16a34a','card'=>'#1d4ed8','bank_transfer'=>'#0891b2',
                  'mobile'=>'#7c3aed','credit'=>'#d97706','cheque'=>'#64748b'];
    $pmtIcons  = ['cash'=>'💵','card'=>'💳','bank_transfer'=>'🏦',
                  'mobile'=>'📱','credit'=>'📒','cheque'=>'📝'];
    foreach($pmtBreakdown as $i=>$p):
      $pct  = $pmtTotal>0?round((float)$p['total']/$pmtTotal*100,1):0;
      $mc   = $pmtColors[$p['payment_method']]??'#64748b';
    ?>
    <div class="mb-3">
      <div class="d-flex justify-content-between align-items-center mb-1">
        <span class="fw-semibold small" style="color:<?=$mc?>">
          <?=$pmtIcons[$p['payment_method']]??'💰'?>
          <?=ucfirst(str_replace('_',' ',$p['payment_method']))?>
          <span class="text-muted fw-normal" style="font-size:.7rem">
            (<?=number_format($p['txn_count'])?> txns)
          </span>
        </span>
        <div class="text-end">
          <span class="fw-bold"><?=currency($p['total'])?></span>
          <span class="text-muted ms-1" style="font-size:.7rem"><?=$pct?>%</span>
        </div>
      </div>
      <div class="pmt-bar">
        <div class="pmt-fill" style="width:<?=$pct?>%;background:<?=$mc?>"></div>
      </div>
    </div>
    <?php endforeach;?>
    <div class="d-flex justify-content-between fw-bold pt-2"
         style="border-top:2px solid #f1f5f9;font-size:.78rem">
      <span>TOTAL</span>
      <span><?=currency($pmtTotal)?></span>
    </div>
  </div>
</div>
<?php endif;?>