<?php
date_default_timezone_set('Asia/Colombo');
require_once '../config.php';
require_once '../auth.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

header('Content-Type: application/json');

try {
    $sql = "SELECT name, stock, min_stock FROM products WHERE stock <= min_stock ORDER BY stock ASC, name ASC";
    $result = $conn->query($sql);
    $rows = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    echo json_encode($rows);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to fetch low stock items']);
    error_log('Low stock API error: ' . $e->getMessage());
}
