/**
 * Handles all API interactions for shops, products, and orders.
 */
class ShopService {
    constructor(notifier) {
        this.notifier = notifier;
    }

    async _fetch(url, options = {}) {
        try {
            const response = await fetch(url, options);
            const data = await response.json();
            if (!response.ok || !data.success) {
                throw new Error(data.message || `Request failed with status ${response.status}`);
            }
            return data;
        } catch (error) {
            this.notifier.show(error.message, 'error');
            console.error('API Error:', error);
            throw error; // Re-throw to allow caller to handle it
        }
    }

    getShop(shopId) {
        return this._fetch(`api/shops/get.php?id=${shopId}`);
    }

    getShopProducts(shopId) {
        return this._fetch(`api/shops/products.php?shop_id=${shopId}`);
    }

    getProduct(productId) {
        return this._fetch(`api/shops/get_product.php?id=${productId}`);
    }

    getShopOrders(shopId) {
        return this._fetch(`api/shops/orders.php?shop_id=${shopId}`);
    }

    createShop(data) {
        return this._fetch('api/shops/create.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
    }

    updateShop(data) {
        return this._fetch('api/shops/update.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
    }

    saveProduct(data) {
        const url = data.product_id ? 'api/shops/update_product.php' : 'api/shops/add_product.php';
        return this._fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
    }

    deleteProduct(productId, shopId) {
        return this._fetch('api/shops/delete_product.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ product_id: productId, shop_id: shopId })
        });
    }

    toggleProductAvailability(productId, shopId, isAvailable) {
        return this._fetch('api/shops/toggle_product.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                product_id: productId,
                shop_id: shopId,
                is_available: isAvailable
            })
        });
    }

    updateOrderStatus(orderId, shopId, status) {
        return this._fetch('api/shops/update_order_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                order_id: orderId,
                status: status,
                shop_id: shopId
            })
        });
    }
}