<?php
session_start(); // Importante para usar $_SESSION
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';

try {
    $database = new Database();
    $conn = $database->connect();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "Error al conectar a la base de datos: " . $e->getMessage()]);
    exit;
}

$pdvUsuario = $_SESSION['pdv_usuario'] ?? null;
if (empty($pdvUsuario)) {
    http_response_code(401);
    echo json_encode(["error" => "No hay PDV definido en la sesión"]);
    exit;
}

try {
    $sql = "SELECT Tienda, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, LunesC, MartesC, MiercolesC, JuevesC, ViernesC, SabadoC, DomingoC, Dia, HoraIni, HoraFin FROM PDVXRegion WHERE Tienda = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$pdvUsuario]);
    $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $datos = [];
    foreach ($res as $row) {
        $datos[] = [
            "tienda" => $row['Tienda'],
            "lunes" => $row['Lunes'] ?? null,
            "martes" => $row['Martes'] ?? null,
            "miercoles" => $row['Miercoles'] ?? null,
            "jueves" => $row['Jueves'] ?? null,
            "viernes" => $row['Viernes'] ?? null,
            "sabado" => $row['Sabado'] ?? null,
            "domingo" => $row['Domingo'] ?? null,
            "lunesC" => $row['LunesC'] ?? null,
            "martesC" => $row['MartesC'] ?? null,
            "miercolesC" => $row['MiercolesC'] ?? null,
            "juevesC" => $row['JuevesC'] ?? null,
            "viernesC" => $row['ViernesC'] ?? null,
            "sabadoC" => $row['SabadoC'] ?? null,
            "domingoC" => $row['DomingoC'] ?? null,
            "dia" => $row['Dia'] ?? null,
            "horaini" => $row['HoraIni'] ?? null,
            "horafin" => $row['HoraFin'] ?? null
        ];
    }
    echo json_encode(["success" => true, "data" => $datos], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "Error en la consulta de horarios: " . $e->getMessage()]);
    exit;
}
