<?php
if (ob_get_level()) { ob_end_clean(); }
ob_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);

require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/PdfHelper.php';
requireLogin();

$format = $_GET['format'] ?? 'csv';
$search = trim($_GET['search'] ?? '');
$where = ''; $params = [];
if ($search) {
    $where  = "WHERE i.item_name LIKE ? OR i.item_code LIKE ?";
    $params = ["%$search%","%$search%"];
}

ob_end_clean();

$stmt = $pdo->prepare("SELECT i.item_code, i.item_name, c.category_name, i.brand, i.model, i.unit,
    i.gst_percent, i.sale_price, i.min_stock_level,
    COALESCE(sl.purchased_qty,0) purchased_qty,
    COALESCE(sl.available_qty,0) available_qty,
    COALESCE(sl.freeze_qty,0) freeze_qty,
    COALESCE(sl.sold_qty,0) sold_qty,
    COALESCE(sl.avg_purchase_price,0) avg_purchase_price
    FROM items i
    LEFT JOIN categories c ON c.id=i.category_id
    LEFT JOIN stock_ledger sl ON sl.item_id=i.id
    $where ORDER BY i.item_name");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$headers = ['Item Code','Item Name','Category','Brand','Model','Unit','GST%','Sale Price','Min Stock','Purchased Qty','Available Qty','Freeze Qty','Sold Qty','Avg Purchase Price'];

if ($format === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="stock_report_' . date('Ymd_His') . '.csv"');
    $fp = fopen('php://output','w');
    fputcsv($fp, $headers);
    foreach ($rows as $r) {
        fputcsv($fp, [
            $r['item_code'], $r['item_name'], $r['category_name'] ?? '', $r['brand'], $r['model'],
            $r['unit'], $r['gst_percent'], $r['sale_price'], $r['min_stock_level'],
            $r['purchased_qty'], $r['available_qty'], $r['freeze_qty'], $r['sold_qty'], $r['avg_purchase_price']
        ]);
    }
    fclose($fp);
    exit;
}

if ($format === 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="stock_report_' . date('Ymd_His') . '.xls"');
    echo '<table border="1">';
    echo '<tr>' . implode('', array_map(fn($h) => "<th><b>$h</b></th>", $headers)) . '</tr>';
    foreach ($rows as $r) {
        echo '<tr>';
        $cols = [$r['item_code'],$r['item_name'],$r['category_name']??'',$r['brand'],$r['model'],
                 $r['unit'],$r['gst_percent'],$r['sale_price'],$r['min_stock_level'],
                 $r['purchased_qty'],$r['available_qty'],$r['freeze_qty'],$r['sold_qty'],$r['avg_purchase_price']];
        foreach ($cols as $c) echo '<td>' . htmlspecialchars($c ?? '') . '</td>';
        echo '</tr>';
    }
    echo '</table>';
    exit;
}

if ($format === 'pdf') {
    ob_start();
    ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stock Report</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;font-size:11px;margin:20px;}
h2{color:#1D4E4A;margin-bottom:4px;}
.meta{color:#75716A;font-size:10px;margin-bottom:12px;}
table{width:100%;border-collapse:collapse;font-size:10px;}
th{background:#1D4E4A;color:#fff;padding:5px 6px;text-align:left;}
td{padding:4px 6px;border-bottom:1px solid #E0DBCE;}
tr:nth-child(even) td{background:#F6F4EF;}
.num{text-align:right;}
.low{color:#A32D2D;font-weight:bold;}
</style>
</head>
<body>
<h2>Stock Overview Report</h2>
<div class="meta">Generated: <?= date('d-M-Y H:i A') ?> | Total Items: <?= count($rows) ?></div>
<table>
<thead><tr>
<?php foreach ($headers as $h): ?><th><?= $h ?></th><?php endforeach; ?>
</tr></thead>
<tbody>
<?php foreach ($rows as $r):
    $low = $r['available_qty'] <= $r['min_stock_level'];
?>
<tr>
    <td><?= htmlspecialchars($r['item_code']) ?></td>
    <td><?= htmlspecialchars($r['item_name']) ?></td>
    <td><?= htmlspecialchars($r['category_name'] ?? '') ?></td>
    <td><?= htmlspecialchars($r['brand']) ?></td>
    <td><?= htmlspecialchars($r['model']) ?></td>
    <td><?= htmlspecialchars($r['unit']) ?></td>
    <td class="num"><?= $r['gst_percent'] ?>%</td>
    <td class="num">Rs. <?= number_format($r['sale_price'],2) ?></td>
    <td class="num"><?= $r['min_stock_level'] ?></td>
    <td class="num"><?= $r['purchased_qty'] ?></td>
    <td class="num <?= $low?'low':'' ?>"><?= $r['available_qty'] ?></td>
    <td class="num"><?= $r['freeze_qty'] ?></td>
    <td class="num"><?= $r['sold_qty'] ?></td>
    <td class="num">Rs. <?= number_format($r['avg_purchase_price'],2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body></html>
<?php
    $html = ob_get_clean();
    PdfHelper::output($html, 'stock_report_' . date('Ymd_His') . '.pdf');
}
