<?php
/**
 * Purchase Manager Dashboard API
 */

session_start();
include 'config.php';

if (!isset($_SESSION['purchase_manager_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$pm_id = (int)$_SESSION['purchase_manager_id'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

if ($action !== 'get_stats' && $action !== 'get_dashboard_stats') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

$stats = [
    'success' => true,
    'suppliers' => 0,
    'requisitions_pending' => 0,
    'requisitions_approved' => 0,
    'orders_open' => 0,
    'orders_in_transit' => 0,
    'comparisons' => 0,
    'low_stock_ingredients' => 0,
    'low_stock_count' => 0
];

$result = $conn->query("SELECT COUNT(*) AS c FROM suppliers WHERE purchase_manager_id = $pm_id AND status = 'active'");
if ($result) $stats['suppliers'] = (int)$result->fetch_assoc()['c'];

$result = $conn->query("SELECT COUNT(*) AS c FROM purchase_requisitions WHERE purchase_manager_id = $pm_id AND status = 'pending'");
if ($result) $stats['requisitions_pending'] = (int)$result->fetch_assoc()['c'];

$result = $conn->query("SELECT COUNT(*) AS c FROM purchase_requisitions WHERE purchase_manager_id = $pm_id AND status = 'approved'");
if ($result) $stats['requisitions_approved'] = (int)$result->fetch_assoc()['c'];

$result = $conn->query("SELECT COUNT(*) AS c FROM purchase_orders WHERE purchase_manager_id = $pm_id AND status NOT IN ('delivered', 'cancelled')");
if ($result) $stats['orders_open'] = (int)$result->fetch_assoc()['c'];

$result = $conn->query("SELECT COUNT(*) AS c FROM purchase_orders WHERE purchase_manager_id = $pm_id AND status IN ('confirmed', 'shipped', 'partially_received')");
if ($result) $stats['orders_in_transit'] = (int)$result->fetch_assoc()['c'];

$result = $conn->query("SELECT COUNT(*) AS c FROM cost_comparisons WHERE purchase_manager_id = $pm_id");
if ($result) $stats['comparisons'] = (int)$result->fetch_assoc()['c'];

$result = $conn->query("SELECT COUNT(*) AS c FROM ingredients WHERE status = 'active' AND current_stock < minimum_stock");
if ($result) {
    $low_stock = (int)$result->fetch_assoc()['c'];
    $stats['low_stock_ingredients'] = $low_stock;
    $stats['low_stock_count'] = $low_stock;
}

header('Content-Type: application/json');
echo json_encode($stats);
