<?php
// views/pages/raspadita/api/coordinador_cobros_list.php
// Historial de cobros (tbr_raspadita_cobro)

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 = json_decode($raw ?: '[]', true);
  return is_array($j) ? $j : [];
}

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

$in = read_json();
$desde = trim((string)($in['desde'] ?? ''));
$hasta = trim((string)($in['hasta'] ?? ''));

// defaults: hoy
if ($desde === '') $desde = date('Y-m-d');
if ($hasta === '') $hasta = date('Y-m-d');

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 c.id, c.fecha_hora,
         c.id_punto_venta, c.id_canillita,
         c.saldo_anterior, c.abono, c.saldo_nuevo,
         c.observacion, c.ip, c.created_at,

         COALESCE(u.usuario,'') AS pv_nombre,
         COALESCE(can.canillita,'') AS can_nombre
  FROM tbr_raspadita_cobro c
  LEFT JOIN tbr_usuario u ON u.idusuario = c.id_punto_venta
  LEFT JOIN tbr_canillita can ON can.id = c.id_canillita
  WHERE c.id_coordinador = ?
    AND DATE(c.fecha_hora) BETWEEN ? AND ?
  ORDER BY c.fecha_hora DESC, c.id DESC
  LIMIT 5000
";

$stmt = mysqli_prepare($db, $sql);
if (!$stmt) jexit(['success'=>false,'message'=>'SQL error'], 500);

mysqli_stmt_bind_param($stmt, "iss", $id_coordinador, $desde, $hasta);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);

$items = [];
while ($r = mysqli_fetch_assoc($res)) {
  $tipo = ((int)$r['id_canillita'] > 0) ? 'CAN' : 'PV';
  $destino = ($tipo === 'CAN')
    ? (trim((string)$r['can_nombre']) !== '' ? (string)$r['can_nombre'] : ('CAN #' . (int)$r['id_canillita']))
    : (trim((string)$r['pv_nombre']) !== '' ? (string)$r['pv_nombre'] : ('PV #' . (int)$r['id_punto_venta']));

  $items[] = [
    'id' => (int)$r['id'],
    'fecha_hora' => (string)$r['fecha_hora'],
    'tipo' => $tipo,
    'destino' => $destino,
    'saldo_anterior' => (float)$r['saldo_anterior'],
    'abono' => (float)$r['abono'],
    'saldo_nuevo' => (float)$r['saldo_nuevo'],
    'observacion' => (string)($r['observacion'] ?? ''),
    'ip' => (string)($r['ip'] ?? ''),
  ];
}
mysqli_stmt_close($stmt);

jexit(['success'=>true,'items'=>$items]);