<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}

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

$clientId = (int)($_REQUEST['client_id'] ?? 0);
$locationId = (int)($_REQUEST['location_id'] ?? 0);

if ($clientId <= 0) {
    echo json_encode([
        'ui_units' => 0,
        'estimated_minutes' => 0,
        'missing_ui' => 0,
        'due_overdue_items' => 0
    ]);
    exit;
}

$todayEnd = strtotime('tomorrow midnight') - 1;
$where = "i.clientnumber = ? AND i.statuslive = 1 AND i.duedate IS NOT NULL AND i.duedate > 0 AND i.duedate <= ?";

if ($locationId > 0) {
    $where .= " AND i.locnumber = ?";
}

$sql = "
    SELECT
        COUNT(i.itemnumber) AS due_overdue_items,
        SUM(COALESCE(dp.units, 0)) AS ui_units,
        SUM(CASE WHEN dp.units IS NULL THEN 1 ELSE 0 END) AS missing_ui
    FROM itemdetails i
    LEFT JOIN dd_plant dp ON i.code = dp.code
    WHERE $where
";

$stmt = $con->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['error' => $con->error]);
    exit;
}

if ($locationId > 0) {
    $stmt->bind_param('iii', $clientId, $todayEnd, $locationId);
} else {
    $stmt->bind_param('ii', $clientId, $todayEnd);
}
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc() ?: [];
$units = (float)($row['ui_units'] ?? 0);

echo json_encode([
    'ui_units' => $units,
    'estimated_minutes' => $units * 15,
    'missing_ui' => (int)($row['missing_ui'] ?? 0),
    'due_overdue_items' => (int)($row['due_overdue_items'] ?? 0)
]);

$stmt->close();
$con->close();
?>
