<?php
// views/pages/raspadita/api/coordinador_saldos_list.php
// Lista saldos pendientes de PV y CAN para el coordinador (ROL 7)
// - CAN: tbr_canillita.saldo
// - PV : tbr_usuario.saldo (solo si existe columna saldo)

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

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

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

// ¿tbr_usuario tiene saldo?
$pv_has_saldo = false;
$chk = mysqli_prepare($db, "
  SELECT 1
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'tbr_usuario'
    AND COLUMN_NAME = 'saldo'
  LIMIT 1
");
if ($chk) {
  mysqli_stmt_execute($chk);
  mysqli_stmt_store_result($chk);
  $pv_has_saldo = (mysqli_stmt_num_rows($chk) > 0);
  mysqli_stmt_close($chk);
}

$pv = [];
$pv_warning = null;

if ($pv_has_saldo) {
  // PV que tengan raspaditas asignadas por ESTE coordinador (estado 2 entregada)
  // y mostramos saldo actual del usuario
  $sqlPv = "
    SELECT u.idusuario AS id,
           COALESCE(NULLIF(u.nombre,''), u.usuario, CONCAT('PV #',u.idusuario)) AS text,
           COALESCE(u.saldo,0) AS saldo
    FROM tbr_usuario u
    WHERE u.activo=1 AND u.condicion=1
    ORDER BY u.idusuario DESC
    LIMIT 2000
  ";
  $rs = mysqli_query($db, $sqlPv);
  if ($rs) {
    while ($row = mysqli_fetch_assoc($rs)) {
      $pv[] = [
        'id' => (int)$row['id'],
        'text' => (string)$row['text'],
        'saldo' => (float)$row['saldo'],
      ];
    }
    mysqli_free_result($rs);
  }
} else {
  $pv_warning = "PV sin saldo: tu tabla tbr_usuario no tiene columna 'saldo'.";
}

$can = [];
$sqlCan = "
  SELECT c.id AS id,
         c.canillita AS text,
         COALESCE(c.saldo,0) AS saldo
  FROM tbr_canillita c
  WHERE c.activo=1
  ORDER BY c.id DESC
  LIMIT 2000
";
$rs2 = mysqli_query($db, $sqlCan);
if ($rs2) {
  while ($row = mysqli_fetch_assoc($rs2)) {
    $can[] = [
      'id' => (int)$row['id'],
      'text' => (string)$row['text'],
      'saldo' => (float)$row['saldo'],
    ];
  }
  mysqli_free_result($rs2);
}

jexit([
  'success' => true,
  'pv_enabled' => $pv_has_saldo,
  'pv_warning' => $pv_warning,
  'pv' => $pv,
  'can' => $can,
]);