<?php
declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

require __DIR__ . '/conex.php'; // <-- ajusta ruta
$db = $conn ?? ($conex ?? null);

if (!$db instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Sin conexión BD']);
  exit;
}
mysqli_set_charset($db, 'utf8mb4');

$action = $_GET['action'] ?? '';

/**
 * Topes por id_cifras:
 * 3 cifras => >= 5
 * 4 cifras => >= 1
 */
function topePorCifras(int $idCifras): float {
  return match($idCifras) {
    3 >= 5.0,
    4 >= 1.0,
    default => 999999.0
  };
}

if ($action === 'reporte') {
  $fecha   = $_GET['fecha'] ?? date('Y-m-d');
  $idCifras = (int)($_GET['id_cifras'] ?? 0);

  if (!in_array($idCifras, [3,4], true)) {
    echo json_encode(['success'=>false,'message'=>'id_cifras inválido']);
    exit;
  }

  $tope = topePorCifras($idCifras);

  $sql = "
    SELECT
      l.loteria,
      t.numero,
      COUNT(*) AS cant_ventas,
      SUM(CAST(t.valor AS DECIMAL(10,2))) AS total_valor
    FROM tbr_ticket t
    INNER JOIN tbr_loteria l ON l.idloteria = t.id_loteria
    WHERE t.condicion = 1
      AND t.estado IN (1,2)
      AND t.fecha_impreso = ?
      AND t.id_cifras = ?
    GROUP BY t.id_loteria, t.numero
    HAVING SUM(CAST(t.valor AS DECIMAL(10,2))) >= ?
    ORDER BY l.loteria ASC, total_valor DESC, t.numero ASC
  ";

  $stmt = $db->prepare($sql);
  if (!$stmt) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Error prepare','detail'=>$db->error], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $types  = "sid";              // fecha(string), id_cifras(int), tope(double)
  $params = [$fecha, $idCifras, $tope];

  $stmt->bind_param($types, ...$params);
  $stmt->execute();
  $rs = $stmt->get_result();

  $data = [];
  while ($row = $rs->fetch_assoc()) {
    $data[] = $row;
  }

  echo json_encode(['success'=>true,'data'=>$data], JSON_UNESCAPED_UNICODE);
  exit;
}

echo json_encode(['success'=>false,'message'=>'Acción no válida']);
