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

header('Content-Type: application/json; charset=utf-8');

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

$fnsku = isset($_GET['fnsku']) ? trim($_GET['fnsku']) : '';
$month = isset($_GET['month']) ? trim($_GET['month']) : '';

if ($fnsku === '') {
  echo json_encode([
    'ok' => true,
    'total' => 0,
    'sellable' => 0,
    'rework' => 0,
    'disposed' => 0,
    'month_used' => null,
    'start_used' => null,
    'end_used' => null,
    'fallback' => 'empty_fnsku'
  ]);
  exit;
}

if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
  $month = date('Y-m');
  $fallback = 'fallback_current_month';
} else {
  $fallback = null;
}

// Build month range (year included automatically)
$start = $month . '-01 00:00:00';
$endExclusive = date('Y-m-01 00:00:00', strtotime($start . ' +1 month')); // next month start

$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 = 3 THEN 1 ELSE 0 END) AS disposed
  FROM process
  WHERE TRIM(fnsku) = :fnsku
    AND date_received >= :start
    AND date_received < :endExclusive
";

$stmt = $conn->prepare($sql);
$stmt->execute([
  ':fnsku' => $fnsku,
  ':start' => $start,
  ':endExclusive' => $endExclusive
]);

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

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

  // Echo back what the endpoint used so you can verify in the modal
  'month_used' => $month,
  'start_used' => $start,
  'end_used' => date('Y-m-d H:i:s', strtotime($endExclusive . ' -1 second')),
  'fallback' => $fallback
]);