<?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; }

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

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    echo json_encode(['success' => false, 'message' => 'JSON inválido']);
    exit;
}

$slug_tienda = trim($input['slug_tienda'] ?? '');
$iva         = floatval($input['iva'] ?? 0);
$domicilio   = floatval($input['domicilio'] ?? 0);

if ($slug_tienda === '') {
    echo json_encode(['success' => false, 'message' => 'Falta slug_tienda']);
    exit;
}

// ✅ Revisar si ya existe
$stmt = $mysqli->prepare("SELECT id FROM pos_config WHERE slug_tienda = ?");
$stmt->bind_param("s", $slug_tienda);
$stmt->execute();
$stmt->store_result();
$existe = $stmt->num_rows > 0;
$stmt->close();

if ($existe) {
    // 🔄 UPDATE
    $sql = "UPDATE pos_config SET iva = ?, domicilio = ? WHERE slug_tienda = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("dds", $iva, $domicilio, $slug_tienda);
    $ok = $stmt->execute();
    $stmt->close();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Configuración actualizada' : 'Error al actualizar: ' . $mysqli->error
    ]);
} else {
    // ➕ INSERT
    $sql = "INSERT INTO pos_config (slug_tienda, iva, domicilio) VALUES (?,?,?)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("sdd", $slug_tienda, $iva, $domicilio);
    $ok = $stmt->execute();
    $stmt->close();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Configuración guardada' : 'Error al guardar: ' . $mysqli->error
    ]);
}

$mysqli->close();
