// Noahvelle POS - Frontend to Backend API Integration Guide

/**
 * API Configuration
 * Update this in your React app's configuration or use environment variables
 */

const API_CONFIG = {
    BASE_URL: window.location.origin + window.location.pathname.replace(/\/[^\/]*$/, '') + '/backend/api/',
    TIMEOUT: 30000, // 30 seconds — Namecheap shared hosting can be slow
    HEADERS: {
        'Content-Type': 'application/json',
    }
};

/**
 * API Service Class
 * Use this to communicate with the backend
 */

class POSApiService {
    /**
     * Authentication Methods
     */
    static async login(userId, pin) {
        return this.post('auth.php?action=login', {
            id: userId,
            pin: pin
        });
    }

    /**
     * Product Methods
     */
    static async getAllProducts(categoryId = null) {
        const url = categoryId 
            ? `products.php?action=get_all&category_id=${categoryId}`
            : 'products.php?action=get_all';
        return this.get(url);
    }

    static async getProduct(productId) {
        return this.get(`products.php?action=get&id=${productId}`);
    }

    static async getProductByBarcode(barcode) {
        return this.get(`products.php?action=by_barcode&barcode=${barcode}`);
    }

    static async getLowStockProducts() {
        return this.get('products.php?action=low_stock');
    }

    static async createProduct(productData) {
        return this.post('products.php?action=create', productData);
    }

    static async updateProduct(productId, productData) {
        return this.put(`products.php?action=update&id=${productId}`, productData);
    }

    /**
     * Customer Methods
     */
    static async getAllCustomers() {
        return this.get('customers.php?action=get_all');
    }

    static async getCustomer(customerId) {
        return this.get(`customers.php?action=get&id=${customerId}`);
    }

    static async searchCustomers(term) {
        return this.get(`customers.php?action=search&term=${encodeURIComponent(term)}`);
    }

    static async getCustomerStats(customerId) {
        return this.get(`customers.php?action=stats&id=${customerId}`);
    }

    static async getUpcomingBirthdays(days = 3) {
        return this.get(`customers.php?action=upcoming_birthdays&days=${days}`);
    }

    static async createCustomer(customerData) {
        return this.post('customers.php?action=create', customerData);
    }

    static async updateCustomer(customerId, customerData) {
        return this.put(`customers.php?action=update&id=${customerId}`, customerData);
    }

    /**
     * Transaction Methods
     */
    static async createTransaction(transactionData) {
        return this.post('transactions.php?action=create', transactionData);
    }

    static async getTransaction(transactionId) {
        return this.get(`transactions.php?action=get&id=${transactionId}`);
    }

    static async getAllTransactions(filters = {}) {
        let url = 'transactions.php?action=get_all';
        if (filters.start_date) url += `&start_date=${filters.start_date}`;
        if (filters.end_date) url += `&end_date=${filters.end_date}`;
        if (filters.status) url += `&status=${filters.status}`;
        if (filters.customer_id) url += `&customer_id=${filters.customer_id}`;
        return this.get(url);
    }

    static async getSalesStats(startDate = null, endDate = null) {
        let url = 'transactions.php?action=sales_stats';
        if (startDate) url += `&start_date=${startDate}`;
        if (endDate) url += `&end_date=${endDate}`;
        return this.get(url);
    }

    /**
     * Supplier Methods
     */
    static async getAllSuppliers() {
        return this.get('suppliers.php?action=get_all');
    }

    static async getSupplier(supplierId) {
        return this.get(`suppliers.php?action=get&id=${supplierId}`);
    }

    static async createSupplier(supplierData) {
        return this.post('suppliers.php?action=create', supplierData);
    }

    static async createSupplierPayment(paymentData) {
        return this.post('suppliers.php?action=create_payment', paymentData);
    }

    static async getSupplierPayments(supplierId) {
        return this.get(`suppliers.php?action=payments&supplier_id=${supplierId}`);
    }

    static async getSupplierBalance(supplierId) {
        return this.get(`suppliers.php?action=balance&supplier_id=${supplierId}`);
    }

    /**
     * Expense Methods
     */
    static async getAllExpenses(filters = {}) {
        let url = 'expenses.php?action=get_all';
        if (filters.start_date) url += `&start_date=${filters.start_date}`;
        if (filters.end_date) url += `&end_date=${filters.end_date}`;
        if (filters.category) url += `&category=${filters.category}`;
        return this.get(url);
    }

    static async createExpense(expenseData) {
        return this.post('expenses.php?action=create', expenseData);
    }

    static async updateExpense(expenseId, expenseData) {
        return this.put(`expenses.php?action=update&id=${expenseId}`, expenseData);
    }

    static async getExpenseStats(startDate = null, endDate = null) {
        let url = 'expenses.php?action=stats';
        if (startDate) url += `&start_date=${startDate}`;
        if (endDate) url += `&end_date=${endDate}`;
        return this.get(url);
    }

    static async getTotalExpenses(startDate = null, endDate = null) {
        let url = 'expenses.php?action=total';
        if (startDate) url += `&start_date=${startDate}`;
        if (endDate) url += `&end_date=${endDate}`;
        return this.get(url);
    }

    /**
     * Promotion Methods
     */
    static async getAllPromotions() {
        return this.get('promotions.php?action=get_all');
    }

    static async getActivePromotions() {
        return this.get('promotions.php?action=active');
    }

    static async getPromotion(promotionId) {
        return this.get(`promotions.php?action=get&id=${promotionId}`);
    }

    static async createPromotion(promotionData) {
        return this.post('promotions.php?action=create', promotionData);
    }

    static async getAppliedDiscount(productId, quantity = 1, totalAmount = 0) {
        return this.get(
            `promotions.php?action=get_discount&product_id=${productId}&quantity=${quantity}&total_amount=${totalAmount}`
        );
    }

    /**
     * HTTP Methods
     */
    static async get(endpoint) {
        return this._request(endpoint, 'GET');
    }

    static async post(endpoint, data) {
        return this._request(endpoint, 'POST', data);
    }

    static async put(endpoint, data) {
        return this._request(endpoint, 'PUT', data);
    }

    static async _request(endpoint, method = 'GET', data = null) {
        const url = API_CONFIG.BASE_URL + endpoint;
        const options = {
            method: method,
            headers: API_CONFIG.HEADERS,
            signal: AbortSignal.timeout(API_CONFIG.TIMEOUT),
        };

        if (data && (method === 'POST' || method === 'PUT')) {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            return await response.json();
        } catch (error) {
            console.error(`API Error [${method} ${endpoint}]:`, error);
            return {
                success: false,
                error: error.message || 'An error occurred'
            };
        }
    }
}

/**
 * Usage Examples in Your React Components
 */

// Example 1: Login Component
async function handleLogin(userId, pin) {
    const result = await POSApiService.login(userId, pin);
    if (result.success) {
        console.log('Logged in as:', result.user);
        // Store user in state
        // localStorage.setItem('user', JSON.stringify(result.user));
    } else {
        console.error('Login failed:', result.error);
    }
}

// Example 2: Load Products
async function loadProducts() {
    const products = await POSApiService.getAllProducts();
    console.log('Products:', products);
    // Update component state with products
}

// Example 3: Search Customer
async function searchCustomer(term) {
    const results = await POSApiService.searchCustomers(term);
    console.log('Search results:', results);
}

// Example 4: Create Transaction
async function processSale(cartItems, customerId) {
    const transactionData = {
        date: new Date().toISOString().slice(0, 19).replace('T', ' '),
        customer_id: customerId || null,
        cashier_id: 'admin', // Get from logged-in user
        total_amount: cartItems.reduce((sum, item) => sum + item.line_total, 0),
        discount_amount: 0,
        final_amount: cartItems.reduce((sum, item) => sum + item.line_total, 0),
        payment_method: 'cash',
        status: 'completed',
        items: cartItems.map(item => ({
            product_id: item.product_id,
            variation_id: item.variation_id,
            quantity: item.quantity,
            unit_price: item.unit_price,
            discount_amount: 0,
            line_total: item.line_total
        }))
    };

    const result = await POSApiService.createTransaction(transactionData);
    if (result.success) {
        console.log('Transaction created:', result.transaction_id);
        // Handle success - print receipt, clear cart, etc.
    } else {
        console.error('Transaction failed:', result.error);
    }
}

// Example 5: Get Dashboard Stats
async function loadDashboardStats() {
    const today = new Date().toISOString().slice(0, 10);
    const sales = await POSApiService.getSalesStats(today, today);
    const expenses = await POSApiService.getTotalExpenses(today, today);
    const lowStock = await POSApiService.getLowStockProducts();
    
    console.log('Sales:', sales);
    console.log('Expenses:', expenses);
    console.log('Low Stock Items:', lowStock);
}

// Export for use in your React components
if (typeof module !== 'undefined' && module.exports) {
    module.exports = POSApiService;
}

// Make available globally for browser usage
window.POSApiService = POSApiService;
