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

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

// ── CSV export (GET ?export=...) ──────────────────────────────
$export = $_GET['export'] ?? '';

// ── KPIs ──────────────────────────────────────────────────────
$totalSpend  = (float) db_val("SELECT COALESCE(SUM(final_price),0) FROM purchases WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalPaid   = (float) db_val("SELECT COALESCE(SUM(paid),0)        FROM purchases WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalDue    = (float) db_val("SELECT COALESCE(SUM(due),0)         FROM purchases WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalOrders = (int)   db_val("SELECT COUNT(*)                     FROM purchases WHERE date BETWEEN ? AND ?", [$from,$to]);
$totalItems  = (int)   db_val(
    "SELECT COALESCE(SUM(pi.qty_pcs),0) FROM purchase_items pi
       JOIN purchases p ON p.id = pi.purchase_id
      WHERE p.date BETWEEN ? AND ?", [$from,$to]);
$avgOrder    = $totalOrders > 0 ? $totalSpend / $totalOrders : 0;

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

// ── Tab 2: Supplier-wise ──────────────────────────────────────
$supplierWise = db_rows(
    "SELECT supplier_name,
            COUNT(*)         AS orders,
            SUM(final_price) AS total,
            SUM(paid)        AS paid,
            SUM(due)         AS due
       FROM purchases
      WHERE date BETWEEN ? AND ?
      GROUP BY supplier_name
      ORDER BY total DESC",
    [$from, $to]
);

// ── Tab 3: Product-wise ────────────────────────────────────────
$productWise = db_rows(
    "SELECT pi.product_name,
            SUM(pi.qty_pcs)      AS qty_purchased,
            SUM(pi.total_price)  AS total_cost,
            COUNT(DISTINCT pi.purchase_id) AS po_count,
            AVG(pi.btp_vat)      AS avg_price
       FROM purchase_items pi
       JOIN purchases p ON p.id = pi.purchase_id
      WHERE p.date BETWEEN ? AND ?
      GROUP BY pi.product_name
      ORDER BY total_cost DESC",
    [$from, $to]
);

// ── Handle CSV export ─────────────────────────────────────────
if ($export) {
    $map = [
        'daily' => [$daily,
            ['Date','Orders','Total','Paid','Due','% Paid'],
            fn($d) => [$d['date'], $d['orders'],
                number_format((float)$d['total'],2),
                number_format((float)$d['paid'],2),
                number_format((float)$d['due'],2),
                (float)$d['total']>0 ? number_format((float)$d['paid']/(float)$d['total']*100,1).'%' : '0%']],
        'supplier' => [$supplierWise,
            ['Supplier','Orders','Total','Paid','Due'],
            fn($s) => [$s['supplier_name'], $s['orders'],
                number_format((float)$s['total'],2),
                number_format((float)$s['paid'],2),
                number_format((float)$s['due'],2)]],
        'product' => [$productWise,
            ['Product','Qty Purchased (pcs)','PO Count','Total Cost','Avg Price/pc'],
            fn($p) => [$p['product_name'], $p['qty_purchased'], $p['po_count'],
                number_format((float)$p['total_cost'],2),
                number_format((float)$p['avg_price'],2)]],
    ];
    if (isset($map[$export])) {
        [$rows, $headers, $rowFn] = $map[$export];
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="purchase_'.$export.'_'.$from.'_'.$to.'.csv"');
        $out = fopen('php://output','w');
        fputcsv($out, $headers);
        foreach ($rows as $r) fputcsv($out, $rowFn($r));
        fclose($out); exit;
    }
}
?>

<!-- ── 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 Spend</div>
    <div class="sval b" style="color:var(--brand);font-size:14px">
      <?= $cur . number_format($totalSpend, 2) ?>
    </div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Total Paid</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(--text2)">
    <div class="slabel">Purchase Orders</div>
    <div class="sval b"><?= number_format($totalOrders) ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--teal)">
    <div class="slabel">Total Items (pcs)</div>
    <div class="sval b" style="color:var(--teal)"><?= number_format($totalItems) ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--purple)">
    <div class="slabel">Avg PO 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 Purchase',  'var(--brand)'],
    'supplier' => ['🏢', 'Supplier-wise',   'var(--teal)'],
    'product'  => ['💊', 'Product-wise',    '#ea580c'],
  ];
  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 Purchase ══════════════════ -->
<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">POs</th>
          <th style="text-align:right">Total</th>
          <th style="text-align:right">Paid</th>
          <th style="text-align:right">Due</th>
          <th style="text-align:center">% Paid</th>
        </tr></thead>
        <tbody id="daily-body">
          <?php if ($daily): foreach ($daily as $d):
            $pctPaid = (float)$d['total'] > 0
              ? ((float)$d['paid'] / (float)$d['total']) * 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['total'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format($d['paid'], 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>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $pctPaid>=100?'#d4f0e6':($pctPaid>=50?'#fff3dc':'#fde8e8') ?>;
                           color:<?= $pctPaid>=100?'var(--accent)':($pctPaid>=50?'var(--warn)':'var(--danger)') ?>">
                <?= number_format($pctPaid,0) ?>%
              </span>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="6" class="empty-state">No purchases 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,'total')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format(array_sum(array_column($daily,'paid')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--danger)">
              <?= $cur . number_format(array_sum(array_column($daily,'due')), 2) ?>
            </td>
            <td></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 — Supplier-wise ═══════════════════ -->
<div id="pane-supplier" style="display:none">

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="supp-search" placeholder="🔍 Search supplier…"
           oninput="filterRows('supp-body')"
      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('supp-search').value='';filterRows('supp-body')">
      ✕ Clear
    </button>
    <span id="supp-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>Supplier</th>
          <th style="text-align:center">POs</th>
          <th style="text-align:right">Total Purchased</th>
          <th style="text-align:right">Paid</th>
          <th style="text-align:right">Due</th>
          <th style="text-align:center">% Paid</th>
          <th style="width:90px">Bar</th>
        </tr></thead>
        <tbody id="supp-body">
          <?php
          $maxS = max(1, max(array_column($supplierWise ?: [['']], 'total') ?: [1]));
          if ($supplierWise): foreach ($supplierWise as $i => $s):
            $pct = (float)$s['total']>0 ? ((float)$s['paid']/(float)$s['total'])*100 : 0;
            $bar = min(100, ((float)$s['total']/$maxS)*100);
          ?>
          <tr class="data-row" data-name="<?= htmlspecialchars(strtolower($s['supplier_name'])) ?>">
            <td style="color:var(--text3)"><?= $i+1 ?></td>
            <td style="font-weight:700"><?= htmlspecialchars($s['supplier_name']) ?></td>
            <td style="text-align:center">
              <span class="badge"><?= $s['orders'] ?></span>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;color:var(--brand)">
              <?= $cur . number_format($s['total'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format($s['paid'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;
                color:<?= (float)$s['due']>0?'var(--danger)':'var(--text3)' ?>">
              <?= (float)$s['due']>0 ? $cur.number_format($s['due'],2) : '—' ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $pct>=100?'#d4f0e6':($pct>=50?'#fff3dc':'#fde8e8') ?>;
                           color:<?= $pct>=100?'var(--accent)':($pct>=50?'var(--warn)':'var(--danger)') ?>">
                <?= number_format($pct,0) ?>%
              </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(--teal);border-radius:3px"></div>
              </div>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="8" class="empty-state">No purchases in this period</td></tr>
          <?php endif; ?>
        </tbody>
        <?php if ($supplierWise): ?>
        <tfoot>
          <tr style="background:var(--brand-xlight);font-weight:700">
            <td colspan="2">Total</td>
            <td style="text-align:center"><?= array_sum(array_column($supplierWise,'orders')) ?></td>
            <td class="mono" style="text-align:right;color:var(--brand)">
              <?= $cur . number_format(array_sum(array_column($supplierWise,'total')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--accent)">
              <?= $cur . number_format(array_sum(array_column($supplierWise,'paid')), 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--danger)">
              <?= $cur . number_format(array_sum(array_column($supplierWise,'due')), 2) ?>
            </td>
            <td colspan="2"></td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>
    <div id="supp-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="filterRows('prod-body')"
      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='';filterRows('prod-body')">
      ✕ 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>
        <thead><tr>
          <th>#</th><th>Product</th>
          <th style="text-align:center">Qty Purchased (pcs)</th>
          <th style="text-align:center">POs</th>
          <th style="text-align:right">Total Cost</th>
          <th style="text-align:right">Avg Price/pc</th>
          <th style="width:90px">Cost Bar</th>
        </tr></thead>
        <tbody id="prod-body">
          <?php
          $maxP = max(1, max(array_column($productWise ?: [['']], 'total_cost') ?: [1]));
          if ($productWise): foreach ($productWise as $i => $p):
            $bar = min(100, ((float)$p['total_cost']/$maxP)*100);
          ?>
          <tr class="data-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_purchased']) ?></span>
            </td>
            <td style="text-align:center;color:var(--text3)">
              <?= $p['po_count'] ?>
            </td>
            <td class="mono" style="text-align:right;font-weight:700;color:#ea580c">
              <?= $cur . number_format($p['total_cost'], 2) ?>
            </td>
            <td class="mono" style="text-align:right;color:var(--text2)">
              <?= $cur . number_format($p['avg_price'], 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:#ea580c;border-radius:3px"></div>
              </div>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="7" class="empty-state">No purchases 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_purchased'))) ?>
            </td>
            <td style="text-align:center">
              <?= array_sum(array_column($productWise,'po_count')) ?>
            </td>
            <td class="mono" style="text-align:right;color:#ea580c">
              <?= $cur . number_format(array_sum(array_column($productWise,'total_cost')), 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>

<!-- ── Chart.js ──────────────────────────────────── -->
<?php if ($daily): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
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:'Total Spend', order:2,
        data: <?= json_encode(array_map(fn($d) => round((float)$d['total'],2), $daily)) ?>,
        backgroundColor:'rgba(45,58,140,0.65)', borderRadius:3 },
      { type:'line', label:'Paid',        order:1,
        data: <?= json_encode(array_map(fn($d) => round((float)$d['paid'],2), $daily)) ?>,
        borderColor:'rgba(26,158,110,1)', backgroundColor:'rgba(26,158,110,0.07)',
        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}}} }}
});
</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 — see mediPaginate() in includes/footer.php.
const reportPagers = {};

function filterRows(bodyId) {
  reportPagers[bodyId]?.refresh();
}

function initReportPagers() {
  reportPagers['daily-body'] = mediPaginate({
    rows: Array.from(document.querySelectorAll('#daily-body .daily-row')),
    pagerEl: document.getElementById('daily-pager'),
    perPage: 25, renumber: false,
  });
  reportPagers['supp-body'] = mediPaginate({
    rows: Array.from(document.querySelectorAll('#supp-body .data-row')),
    predicate: row => {
      const q = document.getElementById('supp-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('supp-pager'),
    countEl: document.getElementById('supp-count'),
    countLabel: 'supplier',
    perPage: 25, renumber: false,
  });
  reportPagers['prod-body'] = mediPaginate({
    rows: Array.from(document.querySelectorAll('#prod-body .data-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,
  });
}

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

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

<?php require_once '../includes/footer.php'; ?>
