<?php
// includes/stock_helper.php

if (!function_exists('current_outlet_id')) {
    function current_outlet_id() {
        if (session_status() === PHP_SESSION_NONE) session_start();
        return (int)($_SESSION['outlet_id'] ?? 1);
    }
}

if (!function_exists('update_stock')) {
    function update_stock($item_id, $qty, $outlet_id = null) {
        if ($outlet_id === null) {
            $outlet_id = current_outlet_id();
        }
        $db = db();
        
        // 1. Update/Insert into outlet_stock (Per-Outlet Source of Truth)
        $check = $db->prepare("SELECT id FROM outlet_stock WHERE outlet_id = ? AND item_id = ?");
        $check->execute([$outlet_id, $item_id]);
        if (!$check->fetchColumn()) {
            $db->prepare("INSERT INTO outlet_stock (outlet_id, item_id, quantity) VALUES (?, ?, 0)")->execute([$outlet_id, $item_id]);
        }
        
        $stmt = $db->prepare("UPDATE outlet_stock SET quantity = quantity + ? WHERE outlet_id = ? AND item_id = ?");
        $stmt->execute([$qty, $outlet_id, $item_id]);
        
        // 2. Update global stock_items (Legacy/Aggregate Cache)
        $stmtGlobal = $db->prepare("UPDATE stock_items SET stock_quantity = stock_quantity + ? WHERE id = ?");
        $stmtGlobal->execute([$qty, $item_id]);
    }
}