<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
header("Access-Control-Max-Age: 86400");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

require_once(__DIR__ . '/../../config.php');

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!$data || !isset($data['slug_tienda'])) {
        throw new Exception('Slug de tienda requerido');
    }

    $slug_tienda = $data['slug_tienda'];

    $sql = "SELECT modo_pos, activo FROM pos_configuracion WHERE slug_tienda = ? AND activo = 1";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s", $slug_tienda);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        echo json_encode([
            'success' => true,
            'modo_pos' => $row['modo_pos'],
            'activo' => $row['activo']
        ]);
    } else {
        // Si no hay configuración, devolver valor por defecto
        echo json_encode([
            'success' => true,
            'modo_pos' => 'tienda', // Valor por defecto
            'activo' => 1
        ]);
    }

    $stmt->close();
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>