<?php
// ============================================================
//  MediCore — Sales Reports
//  File: accounting/reports-sales.php
// ============================================================
$page  = 'accounting/reports-sales';
$title = 'Sales Reports';
require_once '../includes/header.php';

$cur  = $settings['currency'];
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

// ── KPIs ──────────────────────────────────────────────────────
$totalRev    = (float) db_val("SELECT COALESCE(SUM(final_price),0)   FROM sales WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalProfit = (float) db_val("SELECT COALESCE(SUM(approx_profit),0) FROM sales WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalPaid   = (float) db_val("SELECT COALESCE(SUM(paid),0)          FROM sales WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalDue    = (float) db_val("SELECT COALESCE(SUM(due),0)           FROM sales WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalOrders = (int)   db_val("SELECT COUNT(*)                        FROM sales WHERE date BETWEEN ? AND ?", [$from,$to]);
$avgOrder    = $totalOrders > 0 ? $totalRev / $totalOrders : 0;
$margin      = $totalRev > 0 ? ($totalProfit / $totalRev) * 100 : 0;

// ── Tab 1: Daily ───────────────────────────────────────────────
$daily = db_rows(
    "SELECT date, COUNT(*) AS orders,
            SUM(final_price)   AS revenue,
            SUM(approx_profit) AS profit,
            SUM(paid)          AS collected,
            SUM(due)           AS due
       FROM sales
      WHERE date BETWEEN ? AND ?
      GROUP BY date ORDER BY date ASC",
    [$from, $to]
);

// ── Tab 2: Monthly ─────────────────────────────────────────────
$monthly = db_rows(
    "SELECT DATE_FORMAT(date,'%Y-%m') AS month,
            COUNT(*)                   AS orders,
            SUM(final_price)           AS revenue,
            SUM(approx_profit)         AS profit,
            SUM(paid)                  AS collected,
            SUM(due)                   AS due
       FROM sales
      WHERE date BETWEEN ? AND ?
      GROUP BY DATE_FORMAT(date,'%Y-%m')
      ORDER BY month ASC",
    [$from, $to]
);

// ── Tab 3: Product-wise ────────────────────────────────────────
$productWise = db_rows(
    "SELECT si.product_name,
            SUM(si.qty)          AS qty_sold,
            SUM(si.after_disc)   AS revenue,
            SUM(si.cost*si.qty)  AS cost,
            SUM(si.after_disc - si.cost*si.qty) AS profit,
            COUNT(DISTINCT si.sale_id) AS txn_count
       FROM sale_items si
       JOIN sales s ON s.id = si.sale_id
      WHERE s.date BETWEEN ? AND ?
      GROUP BY si.product_name
      ORDER BY revenue DESC",
    [$from, $to]
);

// ── Tab 5: Category-wise ───────────────────────────────────────
// Joins sale_items -> products -> categories. Items whose product has
// no category assigned (or the product was later deleted) are grouped
// under "Uncategorized" rather than silently dropped, so the report
// total always reconciles with the other tabs.
ensure_categories_schema();
$categoryWise = db_rows(
    "SELECT COALESCE(cat.name, '(Uncategorized)') AS category_name,
            SUM(si.qty)          AS qty_sold,
            SUM(si.after_disc)   AS revenue,
            SUM(si.cost*si.qty)  AS cost,
            SUM(si.after_disc - si.cost*si.qty) AS profit,
            COUNT(DISTINCT si.sale_id) AS txn_count
       FROM sale_items si
       JOIN sales s ON s.id = si.sale_id
  LEFT JOIN products   p   ON p.id   = si.product_id
  LEFT JOIN categories cat ON cat.id = p.category_id
      WHERE s.date BETWEEN ? AND ?
      GROUP BY cat.id, cat.name
      ORDER BY revenue DESC",
    [$from, $to]
);

// ── Tab 4: Customer-wise ───────────────────────────────────────
$customerWise = db_rows(
    "SELECT customer_name,
            COUNT(*)           AS invoices,
            SUM(final_price)   AS total_purchase,
            SUM(paid)          AS paid,
            SUM(due)           AS due,
            SUM(approx_profit) AS profit
       FROM sales
      WHERE date BETWEEN ? AND ?
      GROUP BY customer_name
      ORDER BY total_purchase DESC",
    [$from, $to]
);
?>

<!-- ── Date range filter ──────────────────────────── -->
<form method="GET" style="display:flex;gap:9px;align-items:center;
      flex-wrap:wrap;margin-bottom:14px;padding:10px 14px;
      background:var(--surface);border:1px solid var(--border);border-radius:var(--r)">
  <span style="font-size:12px;font-weight:600;color:var(--text2)">📅 Range:</span>
  <input type="date" name="from" value="<?= $from ?>"
    style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-size:12px;outline:none">
  <span style="color:var(--text3);font-size:11px">to</span>
  <input type="date" name="to" value="<?= $to ?>"
    style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-size:12px;outline:none">
  <?php
  $ranges = [
    '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'))],
    'This Year'  => [date('Y-01-01'), date('Y-m-d')],
  ];
  foreach ($ranges as $label => [$rf, $rt]):
    $active = ($from===$rf && $to===$rt);
  ?>
  <a href="?from=<?= $rf ?>&to=<?= $rt ?>" class="btn btn-sm"
     style="<?= $active ? 'background:var(--brand);color:#fff;border-color:var(--brand)' : '' ?>">
    <?= $label ?>
  </a>
  <?php endforeach; ?>
  <button type="submit" class="btn btn-primary btn-sm">Apply</button>
  <div style="margin-left:auto">
    <button class="btn btn-sm" type="button" onclick="exportCurrentTab()">📤 Export CSV</button>
  </div>
</form>

<!-- ── KPI Cards ──────────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(6,1fr);gap:8px;margin-bottom:14px">
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total Revenue</div>
    <div class="sval b" style="color:var(--brand);font-size:14px">
      <?= $cur . number_format($totalRev, 2) ?>
    </div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Collected</div>
    <div class="sval b" style="color:var(--accent);font-size:14px">
      <?= $cur . number_format($totalPaid, 2) ?>
    </div>
  </div>
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Outstanding Due</div>
    <div class="sval b" style="color:var(--danger);font-size:14px">
      <?= $cur . number_format($totalDue, 2) ?>
    </div>
  </div>
  <div class="sc" style="border-top:3px solid var(--teal)">
    <div class="slabel">Profit</div>
    <div class="sval b" style="color:var(--teal);font-size:14px">
      <?= $cur . number_format($totalProfit, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">
      <?= number_format($margin, 1) ?>% margin
    </div>
  </div>
  <div class="sc" style="border-top:3px solid var(--text2)">
    <div class="slabel">Total Orders</div>
    <div class="sval b"><?= number_format($totalOrders) ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--purple)">
    <div class="slabel">Avg Order Value</div>
    <div class="sval b" style="color:var(--purple);font-size:13px">
      <?= $cur . number_format($avgOrder, 2) ?>
    </div>
  </div>
</div>

<!-- ── Tabs ───────────────────────────────────────── -->
<div style="display:flex;gap:0;margin-bottom:14px;border-bottom:2px solid var(--border)">
  <?php
  $tabs = [
    'daily'    => ['📅', 'Daily Sales',   'var(--brand)'],
    'monthly'  => ['📆', 'Monthly Sales', 'var(--accent)'],
    'product'  => ['💊', 'Product-wise',  'var(--teal)'],
    'category' => ['🏷️', 'Category-wise', 'var(--warn)'],
    'customer' => ['👤', 'Customer-wise', 'var(--purple)'],
  ];
  foreach ($tabs as $id => [$icon, $label, $color]):
  ?>
  <button id="tab-<?= $id ?>" onclick="switchTab('<?= $id ?>')"
          data-color="<?= $color ?>"
    style="padding:9px 20px;font-size:12.5px;font-weight:600;border:none;
           cursor:pointer;background:transparent;color:var(--text2);
           border-bottom:2px solid transparent;margin-bottom:-2px;transition:all .15s">
    <?= $icon ?> <?= $label ?>
  </button>
  <?php endforeach; ?>
</div>

<!-- ═══════ TAB 1 — Daily Sales ════════════════════ -->
<div id="pane-daily">
  <?php if ($daily): ?>
  <canvas id="dailyChart" height="120" style="margin-bottom:14px"></canvas>
  <?php endif; ?>

  <div class="card" style="padding:0">
    <div class="tw">
      <table>
        <thead><tr>
          <th>Date</th>
          <th style="text-align:center">Orders</th>
          <th style="text-align:right">Revenue</th>
          <th style="text-align:right">Profit</th>
          <th style="text-align:center">Margin</th>
          <th style="text-align:right">Collected</th>
          <th style="text-align:right">Due</th>
        </tr></thead>
        <tbody id="daily-body">
          <?php if ($daily): foreach ($daily as $d):
            $margin_d = (float)$d['revenue'] > 0
              ? ((float)$d['profit'] / (float)$d['revenue']) * 100 : 0;
          ?>
          <tr class="daily-row">
            <td style="font-weight:600"><?= date('d M Y', strtotime($d['date'])) ?></td>
            <td style="text-align:center"><span class="badge"><?= $d['orders'] ?></span></td>
            <td class="mono" style="text-align:right;font-weight:700">
              <?= $cur . number_format($d['revenue'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format($d['profit'], 2) ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $margin_d>=20?'#d4f0e6':($margin_d>=10?'#fff3dc':'#fde8e8') ?>;
                           color:<?= $margin_d>=20?'var(--accent)':($margin_d>=10?'var(--warn)':'var(--danger)') ?>">
                <?= number_format($margin_d,1) ?>%
              </span>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format($d['collected'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;
                                     color:<?= (float)$d['due']>0?'var(--danger)':'var(--text3)' ?>">
              <?= (float)$d['due']>0 ? $cur.number_format($d['due'],2) : '—' ?>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="7" class="empty-state">No sales in this period</td></tr>
          <?php endif; ?>
        </tbody>
        <?php if ($daily): ?>
        <tfoot>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td>Total</td>
            <td style="text-align:center"><?= array_sum(array_column($daily,'orders')) ?></td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format(array_sum(array_column($daily,'revenue')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format(array_sum(array_column($daily,'profit')), 2) ?>
            </td>
            <td style="text-align:center">
              <span class="badge" style="background:var(--brand-xlight);color:var(--brand)">
                <?= number_format($margin, 1) ?>%
              </span>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format(array_sum(array_column($daily,'collected')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--danger)">
              <?= $cur . number_format(array_sum(array_column($daily,'due')), 2) ?>
            </td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>
    <div id="daily-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ═══════ TAB 2 — Monthly Sales ══════════════════ -->
<div id="pane-monthly" style="display:none">
  <?php if ($monthly): ?>
  <canvas id="monthlyChart" height="120" style="margin-bottom:14px"></canvas>
  <?php endif; ?>

  <div class="card" style="padding:0">
    <div class="tw">
      <table>
        <thead><tr>
          <th>Month</th>
          <th style="text-align:center">Orders</th>
          <th style="text-align:right">Revenue</th>
          <th style="text-align:right">Profit</th>
          <th style="text-align:center">Margin</th>
          <th style="text-align:right">Collected</th>
          <th style="text-align:right">Due</th>
        </tr></thead>
        <tbody id="monthly-body">
          <?php if ($monthly): foreach ($monthly as $m):
            $mg = (float)$m['revenue'] > 0
              ? ((float)$m['profit'] / (float)$m['revenue']) * 100 : 0;
          ?>
          <tr class="monthly-row">
            <td style="font-weight:600">
              <?= date('M Y', strtotime($m['month'].'-01')) ?>
            </td>
            <td style="text-align:center"><span class="badge"><?= $m['orders'] ?></span></td>
            <td class="mono" style="text-align:right;font-weight:700">
              <?= $cur . number_format($m['revenue'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format($m['profit'], 2) ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $mg>=20?'#d4f0e6':($mg>=10?'#fff3dc':'#fde8e8') ?>;
                           color:<?= $mg>=20?'var(--accent)':($mg>=10?'var(--warn)':'var(--danger)') ?>">
                <?= number_format($mg,1) ?>%
              </span>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format($m['collected'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;
                                     color:<?= (float)$m['due']>0?'var(--danger)':'var(--text3)' ?>">
              <?= (float)$m['due']>0 ? $cur.number_format($m['due'],2) : '—' ?>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="7" class="empty-state">No sales in this period</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    <div id="monthly-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ═══════ TAB 3 — Product-wise ═══════════════════ -->
<div id="pane-product" style="display:none">

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="prod-search" placeholder="🔍 Search product…"
           oninput="filterProducts()"
      style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
             font-size:12px;outline:none;width:220px">
    <button class="btn btn-sm" onclick="document.getElementById('prod-search').value='';filterProducts()">
      ✕ Clear
    </button>
    <span id="prod-count" style="font-size:11px;color:var(--text3);align-self:center"></span>
  </div>

  <div class="card" style="padding:0">
    <div class="tw">
      <table id="prod-table">
        <thead><tr>
          <th>#</th><th>Product</th>
          <th style="text-align:center">Qty Sold</th>
          <th style="text-align:center">Transactions</th>
          <th style="text-align:right">Revenue</th>
          <th style="text-align:right">Cost</th>
          <th style="text-align:right">Profit</th>
          <th style="text-align:center">Margin</th>
          <th style="width:100px">Revenue Bar</th>
        </tr></thead>
        <tbody id="prod-body">
          <?php
          $maxRev  = max(1, max(array_column($productWise ?: [['']], 'revenue') ?: [1]));
          if ($productWise): foreach ($productWise as $i => $p):
            $mg   = (float)$p['revenue'] > 0
              ? ((float)$p['profit'] / (float)$p['revenue']) * 100 : 0;
            $bar  = min(100, ((float)$p['revenue'] / $maxRev) * 100);
          ?>
          <tr class="prod-row"
              data-name="<?= htmlspecialchars(strtolower($p['product_name'])) ?>">
            <td style="color:var(--text3)">
              <?= $i < 3 ? ['🥇','🥈','🥉'][$i] : $i+1 ?>
            </td>
            <td style="font-weight:600;font-size:12px">
              <?= htmlspecialchars($p['product_name']) ?>
            </td>
            <td class="mono" style="text-align:center;font-weight:700">
              <span class="badge"><?= number_format($p['qty_sold']) ?></span>
            </td>
            <td style="text-align:center;color:var(--text3)">
              <?= $p['txn_count'] ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700">
              <?= $cur . number_format($p['revenue'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--warn)">
              <?= $cur . number_format($p['cost'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;
                                     color:<?= (float)$p['profit']>=0?'var(--teal)':'var(--danger)' ?>">
              <?= $cur . number_format($p['profit'], 2) ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $mg>=20?'#d4f0e6':($mg>=10?'#fff3dc':'#fde8e8') ?>;
                           color:<?= $mg>=20?'var(--accent)':($mg>=10?'var(--warn)':'var(--danger)') ?>">
                <?= number_format($mg,1) ?>%
              </span>
            </td>
            <td style="padding:8px 10px">
              <div style="height:6px;background:var(--border);border-radius:3px;overflow:hidden">
                <div style="height:100%;width:<?= $bar ?>%;
                            background:var(--brand);border-radius:3px"></div>
              </div>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="9" class="empty-state">No sales data in this period</td></tr>
          <?php endif; ?>
        </tbody>
        <?php if ($productWise): ?>
        <tfoot>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td colspan="2">Total</td>
            <td class="mono" style="text-align:center">
              <?= number_format(array_sum(array_column($productWise,'qty_sold'))) ?>
            </td>
            <td></td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format(array_sum(array_column($productWise,'revenue')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--warn)">
              <?= $cur . number_format(array_sum(array_column($productWise,'cost')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format(array_sum(array_column($productWise,'profit')), 2) ?>
            </td>
            <td colspan="2"></td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>
    <div id="prod-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ═══════ TAB — Category-wise ═════════════════════ -->
<div id="pane-category" style="display:none">

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="cat-search" placeholder="🔍 Search category…"
           oninput="filterCategories()"
      style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
             font-size:12px;outline:none;width:220px">
    <button class="btn btn-sm" onclick="document.getElementById('cat-search').value='';filterCategories()">
      ✕ Clear
    </button>
    <span id="cat-count" style="font-size:11px;color:var(--text3);align-self:center"></span>
  </div>

  <div class="card" style="padding:0">
    <div class="tw">
      <table>
        <thead><tr>
          <th>#</th><th>Category</th>
          <th style="text-align:center">Qty Sold</th>
          <th style="text-align:center">Transactions</th>
          <th style="text-align:right">Revenue</th>
          <th style="text-align:right">Cost</th>
          <th style="text-align:right">Profit</th>
          <th style="text-align:center">Margin</th>
          <th style="width:100px">Revenue Bar</th>
        </tr></thead>
        <tbody id="cat-body">
          <?php
          $maxCatRev = max(1, max(array_column($categoryWise ?: [['']], 'revenue') ?: [1]));
          if ($categoryWise): foreach ($categoryWise as $i => $cw):
            $cmg  = (float)$cw['revenue'] > 0
              ? ((float)$cw['profit'] / (float)$cw['revenue']) * 100 : 0;
            $cbar = min(100, ((float)$cw['revenue'] / $maxCatRev) * 100);
          ?>
          <tr class="cat-row" data-name="<?= htmlspecialchars(strtolower($cw['category_name'])) ?>">
            <td style="color:var(--text3)"><?= $i < 3 ? ['🥇','🥈','🥉'][$i] : $i+1 ?></td>
            <td style="font-weight:600;font-size:12px">
              <span class="badge" style="background:var(--teal-light);color:var(--teal)">
                <?= htmlspecialchars($cw['category_name']) ?>
              </span>
            </td>
            <td class="mono" style="text-align:center;font-weight:700">
              <span class="badge"><?= number_format($cw['qty_sold']) ?></span>
            </td>
            <td style="text-align:center;color:var(--text3)"><?= $cw['txn_count'] ?></td>
            <td class="mono" style="text-align:right;font-weight:700">
              <?= $cur . number_format($cw['revenue'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--warn)">
              <?= $cur . number_format($cw['cost'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;
                                     color:<?= (float)$cw['profit']>=0?'var(--teal)':'var(--danger)' ?>">
              <?= $cur . number_format($cw['profit'], 2) ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $cmg>=20?'#d4f0e6':($cmg>=10?'#fff3dc':'#fde8e8') ?>;
                           color:<?= $cmg>=20?'var(--accent)':($cmg>=10?'var(--warn)':'var(--danger)') ?>">
                <?= number_format($cmg,1) ?>%
              </span>
            </td>
            <td style="padding:8px 10px">
              <div style="height:6px;background:var(--border);border-radius:3px;overflow:hidden">
                <div style="height:100%;width:<?= $cbar ?>%;
                            background:var(--warn);border-radius:3px"></div>
              </div>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="9" class="empty-state">No sales data in this period</td></tr>
          <?php endif; ?>
        </tbody>
        <?php if ($categoryWise): ?>
        <tfoot>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td colspan="2">Total</td>
            <td class="mono" style="text-align:center">
              <?= number_format(array_sum(array_column($categoryWise,'qty_sold'))) ?>
            </td>
            <td></td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format(array_sum(array_column($categoryWise,'revenue')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--warn)">
              <?= $cur . number_format(array_sum(array_column($categoryWise,'cost')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format(array_sum(array_column($categoryWise,'profit')), 2) ?>
            </td>
            <td colspan="2"></td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>
    <div id="cat-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ═══════ TAB 4 — Customer-wise ══════════════════ -->
<div id="pane-customer" style="display:none">

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="cust-search" placeholder="🔍 Search customer…"
           oninput="filterCustomers()"
      style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
             font-size:12px;outline:none;width:220px">
    <button class="btn btn-sm"
            onclick="document.getElementById('cust-search').value='';filterCustomers()">
      ✕ Clear
    </button>
  </div>

  <div class="card" style="padding:0">
    <div class="tw">
      <table>
        <thead><tr>
          <th>#</th><th>Customer</th>
          <th style="text-align:center">Invoices</th>
          <th style="text-align:right">Total Purchase</th>
          <th style="text-align:right">Paid</th>
          <th style="text-align:right">Due</th>
          <th style="text-align:right">Profit</th>
          <th style="width:90px">Purchase Bar</th>
        </tr></thead>
        <tbody id="cust-body">
          <?php
          $maxPurch = max(1, max(array_column($customerWise ?: [['']], 'total_purchase') ?: [1]));
          if ($customerWise): foreach ($customerWise as $i => $c):
            $bar = min(100, ((float)$c['total_purchase'] / $maxPurch) * 100);
          ?>
          <tr class="cust-row"
              data-name="<?= htmlspecialchars(strtolower($c['customer_name'])) ?>">
            <td style="color:var(--text3)"><?= $i+1 ?></td>
            <td style="font-weight:600"><?= htmlspecialchars($c['customer_name']) ?></td>
            <td style="text-align:center">
              <span class="badge"><?= $c['invoices'] ?></span>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;color:var(--brand)">
              <?= $cur . number_format($c['total_purchase'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format($c['paid'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;
                                     color:<?= (float)$c['due']>0?'var(--danger)':'var(--text3)' ?>">
              <?= (float)$c['due']>0 ? $cur.number_format($c['due'],2) : '—' ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format($c['profit'], 2) ?>
            </td>
            <td style="padding:8px 10px">
              <div style="height:6px;background:var(--border);border-radius:3px;overflow:hidden">
                <div style="height:100%;width:<?= $bar ?>%;
                            background:var(--purple,#7c3aed);border-radius:3px"></div>
              </div>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="8" class="empty-state">No sales data in this period</td></tr>
          <?php endif; ?>
        </tbody>
        <?php if ($customerWise): ?>
        <tfoot>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td colspan="2">Total</td>
            <td style="text-align:center">
              <?= array_sum(array_column($customerWise,'invoices')) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format(array_sum(array_column($customerWise,'total_purchase')),2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format(array_sum(array_column($customerWise,'paid')),2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--danger)">
              <?= $cur . number_format(array_sum(array_column($customerWise,'due')),2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--teal)">
              <?= $cur . number_format(array_sum(array_column($customerWise,'profit')),2) ?>
            </td>
            <td></td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>
    <div id="cust-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>
</div>

<!-- ── Chart.js ──────────────────────────────────── -->
<?php if ($daily || $monthly): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
<?php if ($daily): ?>
new Chart(document.getElementById('dailyChart').getContext('2d'), {
  data: {
    labels: <?= json_encode(array_map(fn($d) => date('d M', strtotime($d['date'])), $daily)) ?>,
    datasets: [
      { type:'bar',  label:'Revenue', order:2,
        data: <?= json_encode(array_map(fn($d) => round((float)$d['revenue'],2), $daily)) ?>,
        backgroundColor:'rgba(45,58,140,0.6)', borderRadius:3 },
      { type:'line', label:'Profit',  order:1,
        data: <?= json_encode(array_map(fn($d) => round((float)$d['profit'],2), $daily)) ?>,
        borderColor:'rgba(26,158,110,1)', backgroundColor:'rgba(26,158,110,0.08)',
        borderWidth:2, pointRadius:3, fill:true, tension:.35 },
    ]
  },
  options:{plugins:{legend:{labels:{font:{size:10}}}},
           scales:{y:{beginAtZero:true,ticks:{font:{size:10}}},
                   x:{ticks:{font:{size:10}}}}}
});
<?php endif; ?>
<?php if ($monthly): ?>
new Chart(document.getElementById('monthlyChart').getContext('2d'), {
  data: {
    labels: <?= json_encode(array_map(fn($m) => date('M Y', strtotime($m['month'].'-01')), $monthly)) ?>,
    datasets: [
      { type:'bar',  label:'Revenue', order:2,
        data: <?= json_encode(array_map(fn($m) => round((float)$m['revenue'],2), $monthly)) ?>,
        backgroundColor:'rgba(45,58,140,0.6)', borderRadius:4 },
      { type:'line', label:'Profit',  order:1,
        data: <?= json_encode(array_map(fn($m) => round((float)$m['profit'],2), $monthly)) ?>,
        borderColor:'rgba(26,158,110,1)', backgroundColor:'rgba(26,158,110,0.08)',
        borderWidth:2, pointRadius:4, fill:true, tension:.35 },
    ]
  },
  options:{plugins:{legend:{labels:{font:{size:10}}}},
           scales:{y:{beginAtZero:true,ticks:{font:{size:10}}},
                   x:{ticks:{font:{size:10}}}}}
});
<?php endif; ?>
</script>
<?php endif; ?>

<script>
let activeTab = 'daily';

function switchTab(id) {
  activeTab = id;
  document.querySelectorAll('[id^="pane-"]').forEach(p => p.style.display = 'none');
  document.querySelectorAll('[id^="tab-"]').forEach(b => {
    b.style.borderBottomColor = 'transparent'; b.style.color = 'var(--text2)';
  });
  document.getElementById('pane-' + id).style.display = 'block';
  const btn = document.getElementById('tab-' + id);
  btn.style.borderBottomColor = btn.dataset.color;
  btn.style.color = btn.dataset.color;
}

// ── Pagination (all tabs) — see mediPaginate() in includes/footer.php.
// Rows keep their server-baked rank/date text in column 0 (medal
// emojis for top sellers, actual dates/months), so renumber is off
// everywhere here — paging never overwrites that.
let dailyPager, monthlyPager, prodPager, catPager, custPager;

function filterProducts() {
  prodPager.refresh();
}
function filterCategories() {
  catPager.refresh();
}
function filterCustomers() {
  custPager.refresh();
}

function initReportPagers() {
  dailyPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.daily-row')),
    pagerEl: document.getElementById('daily-pager'),
    perPage: 25, renumber: false,
  });
  monthlyPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.monthly-row')),
    pagerEl: document.getElementById('monthly-pager'),
    perPage: 25, renumber: false,
  });
  prodPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.prod-row')),
    predicate: row => {
      const q = document.getElementById('prod-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('prod-pager'),
    countEl: document.getElementById('prod-count'),
    countLabel: 'product',
    perPage: 25, renumber: false,
  });
  catPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.cat-row')),
    predicate: row => {
      const q = document.getElementById('cat-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('cat-pager'),
    countEl: document.getElementById('cat-count'),
    countLabel: 'category',
    perPage: 25, renumber: false,
  });
  custPager = mediPaginate({
    rows: Array.from(document.querySelectorAll('.cust-row')),
    predicate: row => {
      const q = document.getElementById('cust-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('cust-pager'),
    perPage: 25, renumber: false,
  });
}

function exportCurrentTab() {
  const urls = {
    daily:    '?<?= http_build_query(['from'=>$from,'to'=>$to,'export'=>'daily']) ?>',
    monthly:  '?<?= http_build_query(['from'=>$from,'to'=>$to,'export'=>'monthly']) ?>',
    product:  '?<?= http_build_query(['from'=>$from,'to'=>$to,'export'=>'product']) ?>',
    category: '?<?= http_build_query(['from'=>$from,'to'=>$to,'export'=>'category']) ?>',
    customer: '?<?= http_build_query(['from'=>$from,'to'=>$to,'export'=>'customer']) ?>',
  };
  window.location.href = urls[activeTab];
}

document.addEventListener('DOMContentLoaded', () => {
  switchTab('daily');
  initReportPagers();
});
</script>

<?php
// ── CSV Exports ───────────────────────────────────────────────
$export = $_GET['export'] ?? '';
if ($export) {
    $map = [
        'daily'    => [$daily,    ['Date','Orders','Revenue','Profit','Margin%','Collected','Due'],
                       fn($d) => [$d['date'], $d['orders'],
                           number_format((float)$d['revenue'],2), number_format((float)$d['profit'],2),
                           (float)$d['revenue']>0 ? number_format((float)$d['profit']/(float)$d['revenue']*100,1).'%' : '0%',
                           number_format((float)$d['collected'],2), number_format((float)$d['due'],2)]],
        'monthly'  => [$monthly,  ['Month','Orders','Revenue','Profit','Margin%','Collected','Due'],
                       fn($m) => [date('M Y',strtotime($m['month'].'-01')), $m['orders'],
                           number_format((float)$m['revenue'],2), number_format((float)$m['profit'],2),
                           (float)$m['revenue']>0 ? number_format((float)$m['profit']/(float)$m['revenue']*100,1).'%' : '0%',
                           number_format((float)$m['collected'],2), number_format((float)$m['due'],2)]],
        'product'  => [$productWise, ['Product','Qty Sold','Transactions','Revenue','Cost','Profit','Margin%'],
                       fn($p) => [$p['product_name'], $p['qty_sold'], $p['txn_count'],
                           number_format((float)$p['revenue'],2), number_format((float)$p['cost'],2),
                           number_format((float)$p['profit'],2),
                           (float)$p['revenue']>0?number_format((float)$p['profit']/(float)$p['revenue']*100,1).'%':'0%']],
        'category' => [$categoryWise, ['Category','Qty Sold','Transactions','Revenue','Cost','Profit','Margin%'],
                       fn($cw) => [$cw['category_name'], $cw['qty_sold'], $cw['txn_count'],
                           number_format((float)$cw['revenue'],2), number_format((float)$cw['cost'],2),
                           number_format((float)$cw['profit'],2),
                           (float)$cw['revenue']>0?number_format((float)$cw['profit']/(float)$cw['revenue']*100,1).'%':'0%']],
        'customer' => [$customerWise, ['Customer','Invoices','Total Purchase','Paid','Due','Profit'],
                       fn($c) => [$c['customer_name'],$c['invoices'],
                           number_format((float)$c['total_purchase'],2), number_format((float)$c['paid'],2),
                           number_format((float)$c['due'],2), number_format((float)$c['profit'],2)]],
    ];

    if (isset($map[$export])) {
        [$rows, $headers, $rowFn] = $map[$export];
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="sales_' . $export . '_' . $from . '_' . $to . '.csv"');
        $out = fopen('php://output','w');
        fputcsv($out, $headers);
        foreach ($rows as $r) fputcsv($out, $rowFn($r));
        fclose($out);
        exit;
    }
}
require_once '../includes/footer.php';
?>
