<?php
require_once 'config.php';
require_login();
require_permission('stock');

require_once __DIR__ . '/dompdf/autoload.inc.php';
use Dompdf\Dompdf;

$group_id     = (int)($_GET['group_id'] ?? 0);
$only_nonzero = isset($_GET['only_nonzero']) && $_GET['only_nonzero'] === '1';
$search       = trim($_GET['q'] ?? '');

$where = [];
if ($group_id > 0) {
    $where[] = 'i.item_group_id = ' . $group_id;
}
if ($search !== '') {
    $esc = $mysqli->real_escape_string($search);
    $where[] = "(i.name LIKE '%{$esc}%' OR i.code LIKE '%{$esc}%')";
}
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
SELECT
    i.code,
    i.name,
    i.unit,
    g.name AS group_name,
    COALESCE(rin.total_in, 0)  AS qty_in,
    COALESCE(rout.total_out, 0) AS qty_out,
    COALESCE(rin.total_in, 0) - COALESCE(rout.total_out, 0) AS qty_stock
FROM items i
LEFT JOIN item_groups g ON g.id = i.item_group_id
LEFT JOIN (
    SELECT ri.item_id, SUM(ri.quantity) AS total_in
    FROM receipt_items ri
    JOIN receipts r ON r.id = ri.receipt_id
    GROUP BY ri.item_id
) AS rin ON rin.item_id = i.id
LEFT JOIN (
    SELECT ci.item_id, SUM(ci.quantity) AS total_out
    FROM consumption_items ci
    JOIN consumption_orders o ON o.id = ci.order_id
    GROUP BY ci.item_id
) AS rout ON rout.item_id = i.id
{$where_sql}
";

if ($only_nonzero) {
    $sql .= " HAVING qty_stock <> 0";
}
$sql .= " ORDER BY i.name";

$res = $mysqli->query($sql);
$rows = [];
while ($r = $res->fetch_assoc()) {
    $rows[] = $r;
}

$today = date('d.m.Y');

ob_start();
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body { font-family: DejaVu Sans, sans-serif; font-size: 11px; }
        h1 { font-size: 16px; margin-bottom: 4px; }
        p { margin: 2px 0; }
        table { border-collapse: collapse; width: 100%; margin-top: 8px; }
        th, td { border: 1px solid #000; padding: 3px; }
        th { background: #eee; font-size: 10px; }
        td { font-size: 10px; }
        .right { text-align: right; }
    </style>
</head>
<body>
<h1>Stanje skladišta</h1>
<p>Datum izvještaja: <?php echo $today; ?></p>

<?php if (empty($rows)): ?>
    <p>Nema artikala za zadane kriterije.</p>
<?php else: ?>
<table>
    <thead>
    <tr>
        <th>Šifra</th>
        <th>Naziv artikla</th>
        <th>Grupa</th>
        <th>Ulaz</th>
        <th>Izlaz</th>
        <th>Stanje</th>
        <th>JM</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($rows as $row):
        $in    = (float)$row['qty_in'];
        $out   = (float)$row['qty_out'];
        $stock = (float)$row['qty_stock'];
    ?>
        <tr>
            <td><?php echo htmlspecialchars($row['code']); ?></td>
            <td><?php echo htmlspecialchars($row['name']); ?></td>
            <td><?php echo htmlspecialchars($row['group_name']); ?></td>
            <td class="right"><?php echo number_format($in, 3, ',', '.'); ?></td>
            <td class="right"><?php echo number_format($out, 3, ',', '.'); ?></td>
            <td class="right"><?php echo number_format($stock, 3, ',', '.'); ?></td>
            <td><?php echo htmlspecialchars($row['unit']); ?></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?php endif; ?>

<p style="margin-top:10px;font-size:9px;">Generirano iz aplikacije za evidenciju materijala.</p>
</body>
</html>
<?php
$html = ob_get_clean();

$dompdf = new Dompdf();
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$filename = 'stanje_skladista_' . date('Ymd_His') . '.pdf';
$dompdf->stream($filename, ['Attachment' => 0]);
exit;
