<?php
// views/pages/raspadita/api/coordinador_saldos_pendientes.php
// Lista PV y CAN con saldo > 0 para la pestaña "Cobrar saldos"

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

try {
  // Detectar si PV tiene columna 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);
  }

  $pvs = [];
  if ($pv_has_saldo) {
    $q1 = mysqli_prepare($db, "
      SELECT idusuario, usuario, COALESCE(saldo,0) saldo
      FROM tbr_usuario
      WHERE activo=1 AND condicion=1 AND COALESCE(saldo,0) > 0
      ORDER BY usuario ASC
      LIMIT 2000
    ");
    if ($q1) {
      mysqli_stmt_execute($q1);
      mysqli_stmt_store_result($q1);
      mysqli_stmt_bind_result($q1, $id, $user, $saldo);
      while (mysqli_stmt_fetch($q1)) {
        $pvs[] = ['id'=>(int)$id, 'text'=>(string)$user, 'saldo'=>(float)$saldo];
      }
      mysqli_stmt_close($q1);
    }
  }

  $cans = [];
  $q2 = mysqli_prepare($db, "
    SELECT id, canillita, COALESCE(saldo,0) saldo
    FROM tbr_canillita
    WHERE activo=1 AND COALESCE(saldo,0) > 0
    ORDER BY canillita ASC
    LIMIT 2000
  ");
  if ($q2) {
    mysqli_stmt_execute($q2);
    mysqli_stmt_store_result($q2);
    mysqli_stmt_bind_result($q2, $idc, $can, $saldo2);
    while (mysqli_stmt_fetch($q2)) {
      $cans[] = ['id'=>(int)$idc, 'text'=>(string)$can, 'saldo'=>(float)$saldo2];
    }
    mysqli_stmt_close($q2);
  }

  jexit([
    'success'=>true,
    'pv_has_saldo'=>$pv_has_saldo,
    'puntos_venta'=>$pvs,
    'canillitas'=>$cans
  ]);

} catch (Throwable $e) {
  jexit(['success'=>false,'message'=>'Error', 'detail'=>$e->getMessage()], 500);
}