<?php
// rifa_listado.php — Rifas (vigentes por defecto)
// GET opcionales: vigentes=1|0, activo=1|0, fecha_desde=YYYY-MM-DD, fecha_hasta=YYYY-MM-DD, _debug=1
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: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

$DEBUG = isset($_GET['_debug']) && $_GET['_debug']=='1';

require __DIR__ . '/conex.php';
$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) {
  if ($DEBUG) http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error de conexión.','data'=>[]]); exit;
}
if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); }
mysqli_set_charset($db,'utf8mb4');

function qp(string $k,$d=null){ return $_GET[$k] ?? $d; }
function out_ok($rows){ echo json_encode(['success'=>true,'total'=>count($rows),'data'=>$rows], JSON_UNESCAPED_UNICODE); exit; }
function out_fail($msg,$err=null,$debug=false){ if($debug) http_response_code(500); echo json_encode(['success'=>false,'message'=>$msg,'error'=>$debug?$err:null,'data'=>[]], JSON_UNESCAPED_UNICODE); exit; }

try {
  $db->query("SET time_zone='-05:00'");
  @ $db->query("SET lc_time_names='es_EC'");

  $vigentes    = qp('vigentes','1');
  $solo_activo = qp('activo');                // "1"|"0"|null
  $desde       = qp('fecha_desde');
  $hasta       = qp('fecha_hasta');

  $where  = ["l.condicion = 1"];
  $types  = "";
  $params = [];

  if ($solo_activo === "0" || $solo_activo === "1") {
    $where[] = "l.activar = ?";
    $params[] = (int)$solo_activo;
    $types   .= "i";
  }
  if ($desde) { $where[] = "l.fecha >= ?"; $params[]=$desde; $types.="s"; }
  if ($hasta) { $where[] = "l.fecha <= ?"; $params[]=$hasta; $types.="s"; }

  if ($vigentes !== '0') {
    $where[] = "(
      l.fecha > CURDATE() OR (
        l.fecha = CURDATE() AND
        COALESCE(
          CASE
            WHEN l.hora_fin    REGEXP '^[0-9]{2}:[0-9]{2}(:[0-9]{2})?$' THEN TIME(l.hora_fin)
            WHEN l.hora_fin    REGEXP '^[0-9]{4}$'                       THEN STR_TO_DATE(l.hora_fin,'%H%i')
            ELSE NULL
          END,
          '23:59:59'
        ) >= CURTIME()
      )
    )";
  }

  $whereSql = $where ? ("WHERE ".implode(" AND ",$where)) : "";

  $sql = "
    SELECT
      l.idloteria AS id,
      COALESCE(NULLIF(l.loteria,''), '-') AS loteria_nombre,
      DATE_FORMAT(l.fecha,'%Y-%m-%d') AS fecha,
      TRIM(IFNULL(l.dia, DATE_FORMAT(l.fecha, '%W'))) AS dia,
      DATE_FORMAT(
        CASE
          WHEN l.hora_inicio REGEXP '^[0-9]{2}:[0-9]{2}(:[0-9]{2})?$' THEN TIME(l.hora_inicio)
          WHEN l.hora_inicio REGEXP '^[0-9]{4}$'                       THEN STR_TO_DATE(l.hora_inicio,'%H%i')
          ELSE NULL
        END,'%H:%i'
      ) AS hora_inicio,
      DATE_FORMAT(
        CASE
          WHEN l.hora_fin REGEXP '^[0-9]{2}:[0-9]{2}(:[0-9]{2})?$' THEN TIME(l.hora_fin)
          WHEN l.hora_fin REGEXP '^[0-9]{4}$'                       THEN STR_TO_DATE(l.hora_fin,'%H%i')
          ELSE NULL
        END,'%H:%i'
      ) AS hora_fin,
      COALESCE(l.activar,0) AS activo
    FROM tbr_loteria l
    $whereSql
    ORDER BY
      l.fecha ASC,
      COALESCE(
        CASE
          WHEN l.hora_inicio REGEXP '^[0-9]{2}:[0-9]{2}(:[0-9]{2})?$' THEN TIME(l.hora_inicio)
          WHEN l.hora_inicio REGEXP '^[0-9]{4}$'                       THEN STR_TO_DATE(l.hora_inicio,'%H%i')
          ELSE NULL
        END,
        '00:00:00'
      ) ASC,
      l.idloteria ASC
  ";

  $stmt=$db->prepare($sql);
  if ($types!=="") { $stmt->bind_param($types, ...$params); }
  $stmt->execute();
  $res=$stmt->get_result();

  $rows=[];
  while($r=$res->fetch_assoc()){
    $rows[]=[
      'id'             => (int)$r['id'],
      'loteria_nombre' => $r['loteria_nombre'],
      'fecha'          => $r['fecha'],
      'dia'            => ucfirst($r['dia'] ?? ''),
      'hora_inicio'    => $r['hora_inicio'] ?? '',
      'hora_fin'       => $r['hora_fin'] ?? '',
      'activo'         => (int)$r['activo'],
    ];
  }
  $stmt->close();
  out_ok($rows);

} catch(Throwable $e){
  out_fail('No se pudo listar las rifas.',$e->getMessage(),$DEBUG);
}
