<?php
require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

requireAuth();

$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

$business_id = $current_business['business_id'];
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

// Subquery for Purchase totals in range
$purchases = all_rows("
    SELECT pi.item_id, SUM(pi.qty) as total_bought
    FROM purchase_items pi
    JOIN purchases p ON pi.purchase_id = p.id
    WHERE p.business_id = ? AND p.purchase_date BETWEEN ? AND ?
    GROUP BY pi.item_id
", [$business_id, $from, $to]);

$purchase_map = [];
foreach ($purchases as $p) $purchase_map[$p['item_id']] = (float)$p['total_bought'];

// Subquery for Sales totals in range
$sales = all_rows("
    SELECT si.item_id, SUM(si.qty) as total_sold
    FROM sale_items si
    JOIN sales s ON si.sale_id = s.id
    WHERE s.business_id = ? AND s.sale_date BETWEEN ? AND ?
    GROUP BY si.item_id
", [$business_id, $from, $to]);

$sale_map = [];
foreach ($sales as $s) $sale_map[$s['item_id']] = (float)$s['total_sold'];

// Get all items to build the report
$items = all_rows("SELECT id, item_name, primary_unit, opening_qty_kg FROM new_items WHERE business_id = ? ORDER BY item_name", [$business_id]);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Stock Report</title>
    <style>
        body { 
            /* Merged background styles so image works */
            background-image: url("<?= BASE_URL ?>/public/grocery.png");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: center;
            background-color: #f4f6f9; /* Fallback */
            font-size: 14px;
        }
        .card { border-radius: 8px; padding: 15px; border:none; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .table th { background: #007cf8; color: white; font-weight: 500; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">
    <h4 class="mb-3">Stock Movement Report</h4>

    <form class="row g-2 align-items-end mb-3">
        <input type="hidden" name="r" value="reports/stock">
        <div class="col-auto">
            <label class="form-label">From</label>
            <input type="date" name="from" class="form-control" value="<?= e($from) ?>">
        </div>
        <div class="col-auto">
            <label class="form-label">To</label>
            <input type="date" name="to" class="form-control" value="<?= e($to) ?>">
        </div>
        <div class="col-auto">
            <button class="btn btn-primary">Filter</button>
        </div>
    </form>

    <div class="card p-0">
        <table class="table table-hover mb-0">
            <thead>
                <tr>
                    <th>Item Name</th>
                    <th>Unit</th>
                    <th class="text-end">Purchased (+)</th>
                    <th class="text-end">Sold (-)</th>
                    <th class="text-end">Current Stock</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $i): 
                    $bought = $purchase_map[$i['id']] ?? 0;
                    $sold = $sale_map[$i['id']] ?? 0;
                ?>
                <tr>
                    <td><?= e($i['item_name']) ?></td>
                    <td><?= e($i['primary_unit']) ?></td>
                    <td class="text-end text-success">+ <?= number_format($bought, 2) ?></td>
                    <td class="text-end text-danger">- <?= number_format($sold, 2) ?></td>
                    <td class="text-end fw-bold"><?= number_format($i['opening_qty_kg'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($items)): ?>
                    <tr><td colspan="5" class="text-center py-4">No items found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>
