<?php
// /core/modules/inventory/_logic.php

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../config/database.php';

/**
 * True if user is SUPER_ADMIN (can view all companies).
 */
function isSuperAdmin(): bool
{
    return !empty($_SESSION['is_super_admin'])
        || (isset($_SESSION['role_name']) && $_SESSION['role_name'] === 'SUPER_ADMIN');
}

/**
 * Returns the company_id scope for inventory queries.
 * - SUPER_ADMIN: null (means ALL companies)
 * - Everyone else: their session company_id (must exist)
 */
function inventoryCompanyScope(): ?int
{
    if (isSuperAdmin()) return null;

    $cid = (int)($_SESSION['company_id'] ?? 0);
    if ($cid <= 0) {
        die("Company not identified for this user.");
    }
    return $cid;
}

/**
 * Normalize statuses to ONE lifecycle.
 */
function invStatusLabel(string $status): string
{
    $s = strtoupper(trim($status));
    $allowed = ['IN_STOCK','WITH_DISTRIBUTOR','INSTALLED','FAULTY'];

    return in_array($s, $allowed, true) ? $s : 'IN_STOCK';
}

/**
 * Safely build a LIKE parameter.
 */
function likeParam(string $value): string
{
    return '%' . str_replace(['%', '_'], ['\%', '\_'], $value) . '%';
}