<?php
// views/pages/raspadita/api/raspadita_canillita_list.php
// ✅ Lista raspaditas asignadas a canillitas por usuario y rango de fechas
// POST JSON: { "desde":"2026-02-01", "hasta":"2026-02-04" }
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;
}
function read_json(): array {
  $raw = file_get_contents('php://input');
  $j = $raw ? json_decode($raw, true) : [];
  return is_array($j) ? $j : [];
}

if (!isset($_SESSION['idusuario'])) jexit(['success'=>false,'message'=>'Sesión no iniciada'], 401);
$id_usuario = (int)$_SESSION['idusuario'];

$in = read_json();
$desde = trim((string)($in['desde'] ?? date('Y-m-01')));
$hasta = trim((string)($in['hasta'] ?? date('Y-m-d')));

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $desde)) jexit(['success'=>false,'message'=>'Desde inválido'], 400);
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $hasta)) jexit(['success'=>false,'message'=>'Hasta inválido'], 400);

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'");

$sql = "SELECT r.id, r.codigo, r.estado, r.id_canillita, c.canillita,
               r.id_usuario
        FROM tbr_raspadita r
        LEFT JOIN tbr_canillita c ON c.id = r.id_canillita
        WHERE r.id_usuario = ?
          AND r.anulado = 0
          AND DATE(r.fecha_hora) BETWEEN ? AND ?
          AND r.id_canillita IS NOT NULL
        ORDER BY r.id DESC";

$st = $db->prepare($sql);
if (!$st) jexit(['success'=>false,'message'=>'Error prepare','detail'=>$db->error], 500);

$st->bind_param('iss', $id_usuario, $desde, $hasta);
$st->execute();
$res = $st->get_result();

$data = [];
while ($row = $res->fetch_assoc()) $data[] = $row;
$st->close();

jexit(['success'=>true,'data'=>$data,'count'=>count($data)], 200);
