<?php
// views/pages/raspadita/api/coordinador_stock.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'");

$stmt = mysqli_prepare($db, "
  SELECT COUNT(*)
  FROM tbr_raspadita
  WHERE id_coordinador=?
    AND estado=1
    AND COALESCE(id_usuario,0)=0
    AND COALESCE(id_canillita,0)=0
");
if (!$stmt) jexit(['success'=>false,'message'=>'Error SQL stock'], 500);

mysqli_stmt_bind_param($stmt, "i", $id_coordinador);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $c);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);

jexit(['success'=>true, 'stock_disponible'=>(int)($c ?? 0)]);