<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../db/conexion.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$tienda = trim($_POST['tienda'] ?? '');

if (empty($tienda)) {
    echo json_encode(['success' => false, 'message' => 'Tienda no especificada']);
    exit;
}

$dias = ['lunes','martes','miercoles','jueves','viernes','sabado','domingo'];
$valores = [];

foreach ($dias as $dia) {
    $campo_apertura = $_POST[$dia] ?? null;
    $campo_cierre = $_POST[$dia . 'C'] ?? null;
    $nolabora = isset($_POST[$dia . '_nolabora']);

    if ($nolabora) {
        $valores[$dia] = 'No se labora';
        $valores[$dia . 'C'] = 'No se labora';
    } else {
        if ($campo_apertura === null || $campo_cierre === null) {
            echo json_encode(['success' => false, 'message' => "Faltan datos para $dia"]);
            exit;
        }
        $valores[$dia] = $campo_apertura;
        $valores[$dia . 'C'] = $campo_cierre;
    }
}

// Leer horario preferente de recepción de equipos
$recepcion_dia = $_POST['recepcion_dia'] ?? null;
$recepcion_horaini = $_POST['recepcion_horaini'] ?? null;
$recepcion_horafin = $_POST['recepcion_horafin'] ?? null;

// Verificar si ya existe la tienda
$sqlCheck = "SELECT COUNT(*) as total FROM PDVXRegion WHERE Tienda = ?";
$stmt = $conn->prepare($sqlCheck);
$stmt->bind_param("s", $tienda);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$existe = $result['total'] > 0;
$stmt->close();

if ($existe) {
    // Update
    $sql = "UPDATE PDVXRegion SET 
        Lunes = ?, LunesC = ?, 
        Martes = ?, MartesC = ?, 
        Miercoles = ?, MiercolesC = ?, 
        Jueves = ?, JuevesC = ?, 
        Viernes = ?, ViernesC = ?, 
        Sabado = ?, SabadoC = ?, 
        Domingo = ?, DomingoC = ?,
        Dia = ?, HoraIni = ?, HoraFin = ?
        WHERE Tienda = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        "ssssssssssssssssss",
        $valores['lunes'], $valores['lunesC'],
        $valores['martes'], $valores['martesC'],
        $valores['miercoles'], $valores['miercolesC'],
        $valores['jueves'], $valores['juevesC'],
        $valores['viernes'], $valores['viernesC'],
        $valores['sabado'], $valores['sabadoC'],
        $valores['domingo'], $valores['domingoC'],
        $recepcion_dia, $recepcion_horaini, $recepcion_horafin,
        $tienda
    );
} else {
    // Insert
    $sql = "INSERT INTO PDVXRegion (
        Tienda,
        Lunes, LunesC, 
        Martes, MartesC, 
        Miercoles, MiercolesC, 
        Jueves, JuevesC, 
        Viernes, ViernesC, 
        Sabado, SabadoC, 
        Domingo, DomingoC,
        Dia, HoraIni, HoraFin
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        "ssssssssssssssssss",
        $tienda,
        $valores['lunes'], $valores['lunesC'],
        $valores['martes'], $valores['martesC'],
        $valores['miercoles'], $valores['miercolesC'],
        $valores['jueves'], $valores['juevesC'],
        $valores['viernes'], $valores['viernesC'],
        $valores['sabado'], $valores['sabadoC'],
        $valores['domingo'], $valores['domingoC'],
        $recepcion_dia, $recepcion_horaini, $recepcion_horafin
    );
}

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Error al guardar']);
}

$stmt->close();
$conn->close();
