<?php
$json = file_get_contents('php://input');   
$obj = json_decode($json);
$id = $obj->flag;

header('Content-Type: application/json');

$conn = new mysqli("directoriofitness.com.mx", "direct18", "L4LL4v3M@3str@", $obj->bd);
$conn->set_charset("utf8");

// Obtener zona horaria buscando por nombre de BD
$queryZona = "SELECT r.zona_horaria 
              FROM direct18_ProGymCloud.gimnasios g
              JOIN direct18_ProGymCloud.redes_sociales_gym r ON g.idGimnasio = r.gimnasio_idGym
              WHERE g.BaseDatos = ? 
              LIMIT 1";
$stmtZona = $conn->prepare($queryZona);
$stmtZona->bind_param("s", $obj->bd);
$stmtZona->execute();
$resultZona = $stmtZona->get_result();
$timezone = 'America/Mexico_City';

if($resultZona && $resultZona->num_rows > 0){
    $rowZona = $resultZona->fetch_assoc();
    if(!empty($rowZona['zona_horaria'])){
        $timezone = $rowZona['zona_horaria'];
    }
}
$stmtZona->close();

date_default_timezone_set($timezone);
$conn->query("SET time_zone = '$timezone'");

switch($id){
    
    case '0': // get mis accesos
        switch($obj->filter){
            case '1':
                $dayFilter = 15;
                break;
            case '2':
                $dayFilter = 30;
                break;
            case '3':
                $dayFilter = 60;
                break;
            case '4':
                $dayFilter = 180;
                break;
            default:
                $dayFilter = 30;
        }
        
        $query = "SELECT a.idSocio, 
                         CONCAT(s.Nombre, ' ', s.Apellidos) AS nombre, 
                         DATE_FORMAT(a.FechaHora, '%d/%m/%Y %H:%i:%s') AS fecha, 
                         su.NombreSucursal, 
                         a.Puerta 
                  FROM sucursal su 
                  JOIN asistenciaservicio2 a ON su.idSucursal = a.idSucursal 
                  JOIN socios s ON a.idSocio = s.idSocio 
                  WHERE a.idSocio = ? 
                    AND a.FechaHora >= DATE_SUB(NOW(), INTERVAL ? DAY) 
                    AND a.FechaHora <= NOW()
                  ORDER BY a.FechaHora DESC";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $obj->id_cliente, $dayFilter);
        $stmt->execute();
        $resultado = $stmt->get_result();
        
        if($resultado->num_rows > 0){
            $array = [];
            while($row = $resultado->fetch_assoc()){
                $array[] = $row;
            }
            echo json_encode($array);
        } else {
            echo json_encode('vacio');
        }
        
        $stmt->close();
        break;
}

$conn->close();
?>