<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");


require("./connect.php");


include('../../vendor/funciones.php');



include('../../vendor/DBA.php');


include('../../vendor/EncryptClass.php');



include('../../vendor/Security.php');



$tokenID = getCode();
$myencrypt = new EncryptClass();


$input = file_get_contents('php://input');
$datapost = json_decode($input, true);
$type = $datapost['tipo'];
$return = isset($datapost['return']);
function generateSecureToken($length = 32) {
    $bytes = openssl_random_pseudo_bytes($length);
    if ($bytes === false) {
        // Si openssl falla, usar alternativa menos segura
        $bytes = '';
        for ($i = 0; $i < $length; $i++) {
            $bytes .= chr(mt_rand(0, 255));
        }
    }
    return bin2hex($bytes);
}
$queries = [

    // Queries para apartados
    'all_apartados' => " SELECT a.*,
           c.nombre as cliente_nombre,
           u.nombre as usuario_nombre
    FROM apartados a
    JOIN clientes c ON a.cliente_id = c.id
    JOIN usuarios u ON a.usuario_id = u.id
    ORDER BY fecha_apartado DESC",

    'get_apartado_details' => "  SELECT ad.*,
           p.nombre as producto_nombre,
           c.name as color_nombre,
           c.hex as color_hex,
           t.nombre as tela_nombre
    FROM apartados_detalles ad
    JOIN productos p ON ad.producto_id = p.id
    JOIN colors c ON ad.color_id = c.id
    JOIN telas t ON ad.tela_id = t.id
    WHERE ad.apartado_id = ?",

    'get_apartado_payments' => "  SELECT ap.*,
           u.nombre as usuario_nombre
    FROM apartados_pagos ap
    JOIN usuarios u ON ap.usuario_id = u.id
    WHERE ap.apartado_id = ?",

    'add_apartado' => " INSERT INTO apartados (
        cliente_id, usuario_id, total_venta, 
        meses_plazo, observaciones, saldo_pendiente
    ) VALUES (?, ?, ?, ?, ?, ?)",

    'add_payment' => "
        INSERT INTO apartados_pagos (
            apartado_id, usuario_id, monto, 
            tipo_pago, referencia
        ) VALUES (?, ?, ?, ?, ?)",

    'update_apartado_status' => "
        UPDATE apartados 
        SET estado_entrega = ?
        WHERE id = ?",






    //trasferencias
    'get_transfers' => "SELECT t.*, 
            so.nombre as sucursal_origen,
            sd.nombre as sucursal_destino,
            u.nombre as usuario
            FROM transferencias_inventario t
            JOIN sucursales so ON t.sucursal_origen_id = so.id
            JOIN sucursales sd ON t.sucursal_destino_id = sd.id
            JOIN usuarios u ON t.usuario_id = u.id
            ORDER BY t.fecha_transferencia DESC",

    'add_transfer' => "INSERT INTO transferencias_inventario 
        (sucursal_origen_id, sucursal_destino_id, usuario_id, 
            observaciones, detalles, estado, fecha_transferencia) 
        VALUES (?, ?, ?, ?, ?, 'completada', NOW())",
    //ventas
    'add_sale' => "INSERT INTO ventas (
                    usuario_id, 
                    sucursal_id,
                    total_costo, 
                    total_venta, 
                    descuento_total, 
                    fecha_venta,
                    detalles
                ) VALUES (?, ?, ?, ?, ?, NOW(), ?)",

    'get_sales' => "SELECT v.*, 
        u.nombre as vendedor, 
        s.nombre as sucursal 
        FROM ventas v 
        JOIN usuarios u ON v.usuario_id = u.id 
        JOIN sucursales s ON v.sucursal_id = s.id 
        ORDER BY v.fecha_venta DESC",

    //clientes
    'edit_client' => "UPDATE clientes SET nombre=?, telefono=?, direccion=? WHERE id=?",
    'delete_client' => "DELETE FROM clientes WHERE id=?",
    'all_clients' => "SELECT * FROM clientes",
    'add_client' => "INSERT INTO clientes (nombre, telefono, direccion) VALUES (?, ?, ?)",
    //login
    'login' => "SELECT u.password,u.id, u.nombre, u.usuario, u.perfil_id, u.sucursal_id, p.permisos 
                     FROM usuarios u 
                     JOIN perfiles p ON u.perfil_id = p.id 
                     WHERE u.usuario = ? AND u.activo = 1",

    //inventario
    'all_inventory' => "SELECT * FROM inventario ORDER BY ultima_actualizacion DESC",
    'add_inventory' => "INSERT INTO inventario (sucursal_id, producto_id, combinaciones) 
                    VALUES (?, ?, ?)
                    ON DUPLICATE KEY UPDATE combinaciones = VALUES(combinaciones)",

    'get_product_combinations' => "SELECT c.id as color_id, c.name as color_nombre, 
           t.id as tela_id, t.nombre as tela_nombre
    FROM productos_colores pc
    JOIN colors c ON pc.color_id = c.id
    CROSS JOIN productos_telas pt
    JOIN telas t ON pt.tela_id = t.id
    WHERE pc.producto_id = ? AND pt.producto_id = ?",

    'add_inventory' => "INSERT INTO inventario (sucursal_id, producto_id, combinaciones) 
                    VALUES (?, ?, ?)
                    ON DUPLICATE KEY UPDATE combinaciones = VALUES(combinaciones)",
    //usuario
    'all_users' => "SELECT * FROM usuarios",
    'add_user' => "INSERT INTO usuarios (nombre, usuario, password, sucursal_id, perfil_id) VALUES (?, ?, ?, ?, ?)",
    'edit_user' => "UPDATE usuarios SET nombre=?, usuario=?, sucursal_id=?, perfil_id=? WHERE id=?",
    'edit_user_with_password' => "UPDATE usuarios SET nombre=?, usuario=?, password=?, sucursal_id=?, perfil_id=? WHERE id=?",
    'deactivate_user' => "UPDATE usuarios SET activo = FALSE WHERE id=?",
    //perfiles
    'all_profiles' => "SELECT * FROM perfiles",
    'all_modules' => "SELECT * FROM modulos",
    'add_profile' => "INSERT INTO perfiles (nombre, descripcion, permisos) VALUES (?, ?, ?)",
    'edit_profile' => "UPDATE perfiles SET nombre=?, descripcion=?, permisos=? WHERE id=?",
    'delete_profile' => "DELETE FROM perfiles WHERE id=?",
    //sucursales
    'all_branches' => "SELECT * FROM sucursales",
    'add_branch' => "INSERT INTO sucursales (nombre, direccion, horarios) VALUES (?, ?, ?)",
    'edit_branch' => "UPDATE sucursales SET nombre=?, direccion=?, horarios=? WHERE id=?",
    'delete_branch' => "DELETE FROM sucursales WHERE id=?",
    // Productos
    'all_products' => "SELECT p.*, 
                       GROUP_CONCAT(DISTINCT pc.color_id) as colores,
                       GROUP_CONCAT(DISTINCT pt.tela_id) as telas
                       FROM productos p 
                       LEFT JOIN productos_colores pc ON p.id = pc.producto_id 
                       LEFT JOIN productos_telas pt ON p.id = pt.producto_id 
                       GROUP BY p.id",
    'add_product' => "INSERT INTO productos (nombre, tamaño_id, piezas_id, costo, precio, 
                      fotografia, max_descuento1, max_descuento2) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
    'edit_product' => "UPDATE productos SET nombre=?, tamaño_id=?, piezas_id=?, 
                       costo=?, precio=?, fotografia=?, max_descuento1=?, max_descuento2=? 
                       WHERE id=?",
    'delete_product' => "DELETE FROM productos WHERE id=?",
    'add_product_color' => "INSERT INTO productos_colores (producto_id, color_id) VALUES (?, ?)",
    'add_product_tela' => "INSERT INTO productos_telas (producto_id, tela_id) VALUES (?, ?)",
    'delete_product_colors' => "DELETE FROM productos_colores WHERE producto_id=?",
    'delete_product_telas' => "DELETE FROM productos_telas WHERE producto_id=?",

    // Piezas
    'all_pieces' => "SELECT * FROM piezas",
    'edit_pieces' => "UPDATE piezas SET piezas=? WHERE id=?",
    'add_pieces' => "INSERT INTO piezas (piezas) VALUES (?)",
    'delete_pieces' => "DELETE FROM piezas WHERE id=?",

    // Tamaños
    'all_furniture_sizes' => "SELECT * FROM tamano",
    'edit_furniture_size' => "UPDATE tamano SET nombre=? WHERE id=?",
    'add_furniture_size' => "INSERT INTO tamano (nombre) VALUES (?)",
    'delete_furniture_size' => "DELETE FROM tamano WHERE id=?",

    // Tipos
    'all_furniture_types' => "SELECT * FROM tipo",
    'edit_furniture_type' => "UPDATE tipo SET nombre=? WHERE id=?",
    'add_furniture_type' => "INSERT INTO tipo (nombre) VALUES (?)",
    'delete_furniture_type' => "DELETE FROM tipo WHERE id=?",

    // Telas
    'all_fabrics' => "SELECT * FROM telas",
    'edit_fabric' => "UPDATE telas SET nombre=?, descripcion=? WHERE id=?",
    'add_fabric' => "INSERT INTO telas (nombre, descripcion) VALUES (?, ?)",
    'delete_fabric' => "DELETE FROM telas WHERE id=?",

    // Colores
    'all_colors' => "SELECT id, name as nombre, hex as color FROM colors",
    'one_color' => "SELECT name as nombre, hex as color FROM colors WHERE id=?",
    'add_color' => "INSERT INTO colors (name, hex) VALUES (?, ?)",
    'edit_color' => "UPDATE colors SET name=?, hex=? WHERE id=?",
    'delete_color' => "DELETE FROM colors WHERE id=?"
];

if (!array_key_exists($type, $queries)) {
    echo json_encode(["message" => "Invalid request type"]);
    exit;
}

if ($conn->connect_error) {
    echo json_encode(["message" => "Database connection error: " . $conn->connect_error]);
    exit;
}


try {
    $query = $queries[$type];
    $stmt = $conn->prepare($query);

    if (!$stmt) {
        throw new Exception("Error en la preparación: " . $conn->error);
    }
  

    switch ($type) {
        case 'add_apartado':
            // Insertar apartado principal
            $stmt = $conn->prepare($queries['add_apartado']);
            $total_venta = $datapost['total_venta'];
            $stmt->bind_param(
                "iidiss",
                $datapost['cliente_id'],
                $datapost['usuario_id'],
                $total_venta,
                $datapost['meses_plazo'],
                $datapost['observaciones'],
                $total_venta  // saldo_pendiente inicial igual al total
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al crear apartado: " . $stmt->error);
            }

            $apartado_id = $conn->insert_id;

            // Insertar detalles
            $stmt = $conn->prepare("
                INSERT INTO apartados_detalles (
                    apartado_id, producto_id, color_id, 
                    tela_id, cantidad, precio_unitario, subtotal
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            ");

            foreach ($datapost['detalles'] as $detalle) {
                $subtotal = $detalle['cantidad'] * $detalle['precio_unitario'];
                $stmt->bind_param(
                    "iiiiidd",
                    $apartado_id,
                    $detalle['producto_id'],
                    $detalle['color_id'],
                    $detalle['tela_id'],
                    $detalle['cantidad'],
                    $detalle['precio_unitario'],
                    $subtotal
                );

                if (!$stmt->execute()) {
                    throw new Exception("Error al agregar detalle: " . $stmt->error);
                }
            }

            $conn->commit();
            echo json_encode(["success" => true, "id" => $apartado_id]);
            break;

        case 'add_payment':
            $stmt = $conn->prepare("
                INSERT INTO apartados_pagos (
                    apartado_id, usuario_id, monto, 
                    tipo_pago, referencia
                ) VALUES (?, ?, ?, ?, ?)
            ");

            $stmt->bind_param(
                "iidss",
                $datapost['apartado_id'],
                $datapost['usuario_id'],
                $datapost['monto'],
                $datapost['tipo_pago'],
                $datapost['referencia']
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al registrar pago: " . $stmt->error);
            }

            // Actualizar total_pagado y saldo_pendiente
            $stmt = $conn->prepare("
                UPDATE apartados 
                SET total_pagado = (
                    SELECT COALESCE(SUM(monto), 0)
                    FROM apartados_pagos
                    WHERE apartado_id = ?
                ),
                saldo_pendiente = total_venta - (
                    SELECT COALESCE(SUM(monto), 0)
                    FROM apartados_pagos
                    WHERE apartado_id = ?
                ),
                estado_pago = CASE
                    WHEN (
                        SELECT COALESCE(SUM(monto), 0)
                        FROM apartados_pagos
                        WHERE apartado_id = ?
                    ) >= total_venta THEN 'liquidado'
                    WHEN (
                        SELECT COALESCE(SUM(monto), 0)
                        FROM apartados_pagos
                        WHERE apartado_id = ?
                    ) > 0 THEN 'parcial'
                    ELSE 'pendiente'
                END
                WHERE id = ?
            ");

            $stmt->bind_param(
                "iiiii",
                $datapost['apartado_id'],
                $datapost['apartado_id'],
                $datapost['apartado_id'],
                $datapost['apartado_id'],
                $datapost['apartado_id']
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al actualizar estado: " . $stmt->error);
            }

            $conn->commit();
            echo json_encode(["success" => true]);
            break;

        case 'update_apartado_status':
            $stmt = $conn->prepare("
                UPDATE apartados 
                SET estado_entrega = ?
                WHERE id = ?
            ");

            $stmt->bind_param(
                "si",
                $datapost['estado_entrega'],
                $datapost['id']
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al actualizar estado: " . $stmt->error);
            }

            $conn->commit();
            echo json_encode(["success" => true]);
            break;
        case 'add_transfer':
            $conn->begin_transaction();
            try {
                // Insertar la transferencia
                $stmt = $conn->prepare($queries['add_transfer']);
                $stmt->bind_param(
                    "iiiss",
                    $datapost['sucursal_origen_id'],
                    $datapost['sucursal_destino_id'],
                    $datapost['usuario_id'],
                    $datapost['observaciones'],
                    $datapost['detalles']
                );

                if (!$stmt->execute()) {
                    throw new Exception("Error al registrar la transferencia: " . $stmt->error);
                }

                $conn->commit();
                echo json_encode(["message" => "Success", "id" => $conn->insert_id]);
            } catch (Exception $e) {
                $conn->rollback();
                echo json_encode(["message" => "Error: " . $e->getMessage()]);
            }
            break;
        case 'add_sale':
            // Validar y limpiar el JSON
            $detallesArray = json_decode($datapost['detalles'], true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception("Error en formato JSON: " . json_last_error_msg());
            }

            // Limpiar y validar cada detalle
            foreach ($detallesArray as &$detalle) {
                $detalle = array_map(function ($valor) {
                    if (is_string($valor)) {
                        return strip_tags(trim($valor));
                    }
                    return $valor;
                }, $detalle);
            }

            // Codificar el JSON limpio
            $detallesLimpios = json_encode($detallesArray, JSON_UNESCAPED_SLASHES);

            $stmt->bind_param(
                "iiddds", // 6 parámetros: integer, integer, double, double, double, string
                $datapost['usuario_id'],
                $datapost['sucursal_id'],
                $datapost['total_costo'],
                $datapost['total_venta'],
                $datapost['descuento_total'],
                $detallesLimpios
            );
            break;
        case 'edit_client':
            $stmt->bind_param(
                "sssi",
                $datapost['nombre'],
                $datapost['telefono'],
                $datapost['direccion'],
                $datapost['id']
            );
            break;
        case 'delete_client':
            $stmt->bind_param("i", $datapost['id']);
            break;
        case 'add_client':
            $stmt->bind_param(
                "sss",
                $datapost['nombre'],
                $datapost['telefono'],
                $datapost['direccion']
            );
            break;
        case 'login':
             
            $stmt = $conn->prepare($queries['login']);
            $stmt->bind_param("s", $datapost['usuario']);
try{
            if ($stmt->execute()) {
         
                $result = $stmt->get_result();
                if ($result->num_rows > 0) {
                    $user = $result->fetch_assoc();
                         
                    if (password_verify($datapost['password'], $user['password'])) {
                        // unset($user['password']);
                         
                        $token = generateSecureToken();
                        
                        echo json_encode([
                            "success" => true,
                            "user" => $user,
                            "token" => $token
                        ]);
                    } else {
                        echo json_encode([
                            "success" => false,
                            "message" => "Credenciales inválidas"
                        ]);
                    }
                } else {
                    echo json_encode([
                        "success" => false,
                        "message" => "Usuario no encontrado"
                    ]);
                }
            }}
            catch (Exception $e) {
                
                echo $e;
            }
            break;
        case 'get_product_combinations':
            $producto_id = $datapost['producto_id'];
            $stmt->bind_param("ii", $producto_id, $producto_id);
            if ($stmt->execute()) {
                $result = $stmt->get_result();
                $data = [];
                while ($row = $result->fetch_assoc()) {
                    $data[] = $row;
                }
                echo json_encode($data);
            } else {
                echo json_encode(["message" => "Error: " . $stmt->error]);
            }
            break;

        case 'add_inventory':
            $stmt->bind_param(
                "iis",
                $datapost['sucursal_id'],
                $datapost['producto_id'],
                $datapost['combinaciones']
            );
            break;
        case 'add_user':
            $hashedPassword = password_hash($datapost['password'], PASSWORD_DEFAULT);
            $stmt->bind_param(
                "sssii",
                $datapost['nombre'],
                $datapost['usuario'],
                $hashedPassword,
                $datapost['sucursal_id'],
                $datapost['perfil_id']
            );
            break;

        case 'edit_user':
            if (isset($datapost['password']) && !empty($datapost['password'])) {
                $hashedPassword = password_hash($datapost['password'], PASSWORD_DEFAULT);
                $stmt = $conn->prepare($queries['edit_user_with_password']);
                $stmt->bind_param(
                    "sssiii",
                    $datapost['nombre'],
                    $datapost['usuario'],
                    $hashedPassword,
                    $datapost['sucursal_id'],
                    $datapost['perfil_id'],
                    $datapost['id']
                );
            } else {
                $stmt->bind_param(
                    "ssiii",
                    $datapost['nombre'],
                    $datapost['usuario'],
                    $datapost['sucursal_id'],
                    $datapost['perfil_id'],
                    $datapost['id']
                );
            }
            break;

        case 'deactivate_user':
            $stmt->bind_param("i", $datapost['id']);
            break;
        case 'add_profile':
            $stmt->bind_param("sss", $datapost['nombre'], $datapost['descripcion'], $datapost['permisos']);
            break;

        case 'edit_profile':
            $stmt->bind_param("sssi", $datapost['nombre'], $datapost['descripcion'], $datapost['permisos'], $datapost['id']);
            break;

        case 'delete_profile':
            $stmt->bind_param("i", $datapost['id']);
            break;


        case 'add_branch':
            $stmt->bind_param("sss", $datapost['nombre'], $datapost['direccion'], $datapost['horarios']);
            break;

        case 'edit_branch':
            $stmt->bind_param("sssi", $datapost['nombre'], $datapost['direccion'], $datapost['horarios'], $datapost['id']);
            break;

        case 'delete_branch':
            $stmt->bind_param("i", $datapost['id']);
            break;
        case 'add_product':
            $conn->begin_transaction();

            $stmt->bind_param(
                "siiddsdd",
                $datapost['nombre'],
                $datapost['tamaño'],
                $datapost['piezas'],
                $datapost['costo'],
                $datapost['precio'],
                $datapost['fotografia'],
                $datapost['maxDescuento1'],
                $datapost['maxDescuento2']
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al insertar producto: " . $stmt->error);
            }

            $producto_id = $conn->insert_id;

            // Insertar colores
            $stmt_color = $conn->prepare($queries['add_product_color']);
            foreach ($datapost['colores'] as $color_id) {
                $stmt_color->bind_param("ii", $producto_id, $color_id);
                if (!$stmt_color->execute()) {
                    throw new Exception("Error al insertar color");
                }
            }

            // Insertar telas
            $stmt_tela = $conn->prepare($queries['add_product_tela']);
            foreach ($datapost['telas'] as $tela_id) {
                $stmt_tela->bind_param("ii", $producto_id, $tela_id);
                if (!$stmt_tela->execute()) {
                    throw new Exception("Error al insertar tela");
                }
            }

            $conn->commit();
            echo json_encode(["message" => "Success", "id" => $producto_id]);
            break;

        case 'edit_product':
            $conn->begin_transaction();

            // Primero actualizar el producto
            $stmt = $conn->prepare($queries['edit_product']);
            $stmt->bind_param(
                "siiddsdds",  // Corregido los tipos de parámetros
                $datapost['nombre'],
                $datapost['tamaño'],
                $datapost['piezas'],
                $datapost['costo'],
                $datapost['precio'],
                $datapost['fotografia'],
                $datapost['maxDescuento1'],
                $datapost['maxDescuento2'],
                $datapost['id']  // Agregado el ID para la cláusula WHERE
            );

            if (!$stmt->execute()) {
                throw new Exception("Error al actualizar producto");
            }

            // Actualizar colores
            $stmt_delete_colors = $conn->prepare($queries['delete_product_colors']);
            $stmt_delete_colors->bind_param("i", $datapost['id']);
            $stmt_delete_colors->execute();

            if (!empty($datapost['colores'])) {
                $stmt_color = $conn->prepare($queries['add_product_color']);
                foreach ($datapost['colores'] as $color_id) {
                    $stmt_color->bind_param("ii", $datapost['id'], $color_id);
                    if (!$stmt_color->execute()) {
                        throw new Exception("Error al actualizar colores");
                    }
                }
            }

            // Actualizar telas
            $stmt_delete_telas = $conn->prepare($queries['delete_product_telas']);
            $stmt_delete_telas->bind_param("i", $datapost['id']);
            $stmt_delete_telas->execute();

            if (!empty($datapost['telas'])) {
                $stmt_tela = $conn->prepare($queries['add_product_tela']);
                foreach ($datapost['telas'] as $tela_id) {
                    $stmt_tela->bind_param("ii", $datapost['id'], $tela_id);
                    if (!$stmt_tela->execute()) {
                        throw new Exception("Error al actualizar telas");
                    }
                }
            }

            $conn->commit();
            echo json_encode(["message" => "Success"]);
            break;

        case 'delete_product':
            $conn->begin_transaction();

            // Eliminar relaciones primero
            $stmt = $conn->prepare($queries['delete_product_colors']);
            $stmt->bind_param("i", $datapost['id']);
            $stmt->execute();

            $stmt = $conn->prepare($queries['delete_product_telas']);
            $stmt->bind_param("i", $datapost['id']);
            $stmt->execute();

            // Eliminar producto
            $stmt = $conn->prepare($queries['delete_product']);
            $stmt->bind_param("i", $datapost['id']);
            $stmt->execute();

            $conn->commit();
            echo json_encode(["message" => "Success"]);
            break;

            // Casos para otras operaciones CRUD
        case 'add_pieces':
            $stmt->bind_param("i", $datapost['piezas']);
            break;

        case 'edit_pieces':
            $stmt->bind_param("ii", $datapost['piezas'], $datapost['id']);
            break;

        case 'delete_pieces':
        case 'delete_furniture_size':
        case 'delete_fabric':
        case 'delete_furniture_type':
        case 'delete_color':
            $stmt->bind_param("i", $datapost['id']);
            break;

        case 'add_furniture_size':
        case 'add_furniture_type':
            $stmt->bind_param("s", $datapost['nombre']);
            break;

        case 'edit_furniture_size':
        case 'edit_furniture_type':
            $stmt->bind_param("si", $datapost['nombre'], $datapost['id']);
            break;

        case 'edit_fabric':
            $stmt->bind_param("ssi", $datapost['nombre'], $datapost['descripcion'], $datapost['id']);
            break;

        case 'add_fabric':
            $stmt->bind_param("ss", $datapost['nombre'], $datapost['descripcion']);
            break;

        case 'add_color':
            $stmt->bind_param("ss", $datapost['nombre'], $datapost['color']);
            break;

        case 'edit_color':
            $stmt->bind_param("ssi", $datapost['nombre'], $datapost['color'], $datapost['id']);
            break;

        default:
            // Para queries de SELECT

            $stmt->execute();
            $result = $stmt->get_result();
            $data = [];
            while ($row = $result->fetch_assoc()) {
                if ($type === 'all_apartados') {
                    // Obtener detalles y pagos para cada apartado
                    $detalles_stmt = $conn->prepare($queries['get_apartado_details']);
                    $detalles_stmt->bind_param("i", $row['id']);
                    $detalles_stmt->execute();
                    $row['detalles'] = $detalles_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

                    $pagos_stmt = $conn->prepare($queries['get_apartado_payments']);
                    $pagos_stmt->bind_param("i", $row['id']);
                    $pagos_stmt->execute();
                    $row['pagos'] = $pagos_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                }
                $data[] = $row;
            }

            echo json_encode($data);
            exit;
    }

    // Ejecutar la consulta si no es un SELECT
    if (!in_array($type, ['add_product', 'edit_product', 'delete_product', 'get_product_combinations', 'login', 'add_apartado'])) {
        if ($stmt->execute()) {
            echo json_encode(["message" => "Success", "id" => $conn->insert_id]);
        } else {
            throw new Exception("Error en la ejecución: " . $stmt->error);
        }
    }
} catch (Exception $e) {
    
    if (isset($conn) && $conn->connect_error === false) {
        $conn->rollback();
    }
    echo json_encode(["message" => "Error: " . $e->getMessage()]);
}
