<?php
require_once '../../db/Config.php';

$db = new Config();
$conn = $db->getConnection();

$fnsku = $_GET['fnsku'] ?? '';
$currentmonth = date('Y-m');

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

if ($fnsku === '') {
  echo json_encode([
    'total' => 0,
    'sellable' => 0,
    'rework' => 0,
    'liquidation' => 0,
    'disposed' => 0
  ]);
  exit;
}

$sql = "
  SELECT
    COUNT(*) AS total,
    SUM(CASE WHEN sellable = 1 THEN 1 ELSE 0 END) AS sellable,
    SUM(CASE WHEN sellable = 2 THEN 1 ELSE 0 END) AS rework,
    SUM(CASE WHEN sellable IN (3,4) THEN 1 ELSE 0 END) AS liquidation,
    SUM(CASE WHEN sellable = 5 THEN 1 ELSE 0 END) AS disposed
  FROM process
  WHERE fnsku = :fnsku
    AND date_received LIKE :month
";

$stmt = $conn->prepare($sql);
$stmt->execute([
  ':fnsku' => $fnsku,
  ':month' => "%$currentmonth%"
]);

$row = $stmt->fetch(PDO::FETCH_ASSOC);

echo json_encode([
  'total' => (int)($row['total'] ?? 0),
  'sellable' => (int)($row['sellable'] ?? 0),
  'rework' => (int)($row['rework'] ?? 0),
  'liquidation' => (int)($row['liquidation'] ?? 0),
  'disposed' => (int)($row['disposed'] ?? 0),
]);
