<?php
// views/pages/raspadita/api/coordinador_resumen.php
declare(strict_types=1);

session_start();
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'Use POST'], JSON_UNESCAPED_UNICODE);
  exit;
}

function jexit(array $p, int $c=200): void {
  http_response_code($c);
  echo json_encode($p, JSON_UNESCAPED_UNICODE);
  exit;
}

if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES' || (int)($_SESSION['id_rol'] ?? 0) !== 7) {
  jexit(['success'=>false,'message'=>'No autorizado'], 401);
}

$id_coordinador = (int)($_SESSION['id_coordinador'] ?? 0);
if ($id_coordinador <= 0) jexit(['success'=>false,'message'=>'Sesión sin coordinador'], 401);

require_once __DIR__ . '/../../conex.php';
$db = $conn ?? null;
if (!$db instanceof mysqli) jexit(['success'=>false,'message'=>'Sin conexión BD'], 500);

mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone='-05:00'");

/* ===== SALDO ===== */
$saldo = 0.0;
$stmt = mysqli_prepare($db, "SELECT COALESCE(saldo,0) FROM tbr_coordinador WHERE id=? LIMIT 1");
if ($stmt) {
  mysqli_stmt_bind_param($stmt, "i", $id_coordinador);
  mysqli_stmt_execute($stmt);
  mysqli_stmt_bind_result($stmt, $s);
  mysqli_stmt_fetch($stmt);
  mysqli_stmt_close($stmt);
  $saldo = (float)$s;
}

/* ===== TOTAL (1-3) (ignora anulado=1 sin borrar NULL) ===== */
$total_123 = 0;
$stmt2 = mysqli_prepare($db, "
  SELECT COUNT(*)
  FROM tbr_raspadita
  WHERE id_coordinador=?
    AND COALESCE(anulado,0) <> 1
    AND estado IN (1,2,3)
");
if ($stmt2) {
  mysqli_stmt_bind_param($stmt2, "i", $id_coordinador);
  mysqli_stmt_execute($stmt2);
  mysqli_stmt_bind_result($stmt2, $c);
  mysqli_stmt_fetch($stmt2);
  mysqli_stmt_close($stmt2);
  $total_123 = (int)$c;
}

/* ===== VENDIDAS HOY: estado IN (3,8) ===== */
$hoy = date('Y-m-d');
$vendidas_hoy = 0;
$stmt3 = mysqli_prepare($db, "
  SELECT COUNT(*)
  FROM tbr_raspadita
  WHERE id_coordinador=?
    AND COALESCE(anulado,0) <> 1
    AND estado IN (3,8)
    AND LEFT(fecha_hora,10)=?
");
if ($stmt3) {
  mysqli_stmt_bind_param($stmt3, "is", $id_coordinador, $hoy);
  mysqli_stmt_execute($stmt3);
  mysqli_stmt_bind_result($stmt3, $c2);
  mysqli_stmt_fetch($stmt3);
  mysqli_stmt_close($stmt3);
  $vendidas_hoy = (int)$c2;
}

jexit([
  'success'=>true,
  'saldo'=>$saldo,
  'total_123'=>$total_123,
  'hoy_vendidas'=>$vendidas_hoy
]);