<?php
session_start();
require_once '../assets/db_connect.php';

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    echo "Access denied";
    exit;
}

/* ----------------------------------------------
   FETCH STOCK DATA
---------------------------------------------- */
$sql = "
 SELECT p.id AS product_id, p.name AS product_name,
        pb.id AS batch_id, pb.batch_no, pb.qty, pb.cost_price, pb.sell_price, pb.expiry_date,
        s.name AS supplier
 FROM products p
 LEFT JOIN product_batches pb ON pb.product_id = p.id
 LEFT JOIN suppliers s ON s.id = pb.supplier_id
 ORDER BY p.name, pb.expiry_date
";
$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

/* ----------------------------------------------
   EXPORT PDF BEFORE ANY HTML!
---------------------------------------------- */
if (isset($_GET['export']) && $_GET['export'] === 'pdf') {

    require_once __DIR__ . '/../tcpdf/tcpdf.php';

    $pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false);

    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->AddPage();

    $html = '<h2 style="text-align:center;">Current Stock Levels</h2>
        <table border="1" cellpadding="4">
            <tr style="font-weight:bold;">
                <th>Product</th>
                <th>Batch</th>
                <th>Qty</th>
                <th>Cost</th>
                <th>Sell</th>
                <th>Expiry</th>
                <th>Supplier</th>
            </tr>';

    foreach ($rows as $r) {
        $html .= "
            <tr>
                <td>{$r['product_name']}</td>
                <td>{$r['batch_no']}</td>
                <td>{$r['qty']}</td>
                <td>{$r['cost_price']}</td>
                <td>{$r['sell_price']}</td>
                <td>" . ($r['expiry_date'] ? date('d-M-Y', strtotime($r['expiry_date'])) : '-') . "</td>
                <td>{$r['supplier']}</td>
            </tr>";
    }

    $html .= "</table>";

    $pdf->writeHTML($html);
    $pdf->Output('stock_levels.pdf', 'I');
    exit;
}

/* ----------------------------------------------
   EXPORT CSV (can be placed here—no issue)
---------------------------------------------- */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=stock_levels.csv');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['Product', 'Batch', 'Qty', 'Cost', 'Sell', 'Expiry', 'Supplier']);

    foreach ($rows as $r) {
        fputcsv($out, [
            $r['product_name'] ?: '-',
            $r['batch_no'] ?: '-',
            $r['qty'] ?: 0,
            $r['cost_price'],
            $r['sell_price'],
            $r['expiry_date'] ?: '-',
            $r['supplier'] ?: '-'
        ]);
    }
    fclose($out);
    exit;
}

/* ----------------------------------------------
   ONLY NOW load header, sidebar, HTML
---------------------------------------------- */
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<!-- HTML TABLE BELOW… -->
<div class="col-md-10 ml-sm-auto px-4 py-4">
<h3 class="text-success">Current Stock Levels</h3>

<a class="btn btn-outline-primary mb-3" href="?export=csv">Export CSV</a>
<a class="btn btn-outline-danger mb-3" href="?export=pdf" target="_blank">Export PDF</a>

<div class="table-responsive">
<table class="table table-sm table-bordered">
  <thead>
  <tr>
      <th>Product</th>
      <th>Batch</th>
      <th>Qty</th>
      <th>Cost</th>
      <th>Sell</th>
      <th>Expiry</th>
      <th>Supplier</th>
  </tr>
  </thead>
  <tbody>

  <?php foreach ($rows as $r): ?>
    <tr>
      <td><?= htmlspecialchars($r['product_name'] ?: '-'); ?></td>
      <td><?= htmlspecialchars($r['batch_no'] ?: '-'); ?></td>
      <td><?= $r['qty'] ?: '-'; ?></td>
      <td><?= number_format($r['cost_price'],2); ?></td>
      <td><?= number_format($r['sell_price'],2); ?></td>
      <td><?= $r['expiry_date'] ? date('d-M-Y', strtotime($r['expiry_date'])) : '-'; ?></td>
      <td><?= htmlspecialchars($r['supplier'] ?: '-'); ?></td>
    </tr>
  <?php endforeach; ?>

  </tbody>
</table>
</div>
</div>

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