/**
 * ============================================================
 * SAFA MODEST HOUSE - Main Application JavaScript
 * ============================================================
 * Handles all frontend interactions with AJAX
 */

(function($) {
    'use strict';
    
    // Site base URL
    window.siteUrl = window.location.origin + '/safa-modest-house';
    const ajaxUrl = siteUrl + '/public/ajax';
    
    // ============================================================
    // Add to Cart
    // ============================================================
    $(document).on('click', '.btn-add-cart', function(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const productId = $btn.data('product-id');
        const qty = parseInt($btn.closest('.product-actions-form').find('.qty-input').val()) || 1;
        
        setButtonLoading($btn, true);
        
        $.ajax({
            url: ajaxUrl + '/cart/add.php',
            type: 'POST',
            data: {
                product_id: productId,
                qty: qty
            },
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    updateCartCount(response.data.cart_count);
                } else {
                    showToast(response.message, 'error');
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // ============================================================
    // Update Cart Quantity
    // ============================================================
    $(document).on('click', '.btn-qty-update', function(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const $input = $btn.siblings('.qty-input');
        const productId = $input.data('product-id');
        const action = $btn.data('action');
        let qty = parseInt($input.val()) || 1;
        
        if (action === 'increase') {
            qty++;
        } else if (action === 'decrease' && qty > 1) {
            qty--;
        } else if (action === 'decrease' && qty <= 1) {
            // Remove item
            removeFromCart(productId);
            return;
        }
        
        $input.val(qty);
        updateCartItem(productId, qty);
    });
    
    // Direct quantity input change
    $(document).on('change', '.cart-qty-input', function() {
        const $input = $(this);
        const productId = $input.data('product-id');
        const qty = parseInt($input.val()) || 1;
        
        if (qty < 1) {
            removeFromCart(productId);
        } else {
            updateCartItem(productId, qty);
        }
    });
    
    function updateCartItem(productId, qty) {
        $.ajax({
            url: ajaxUrl + '/cart/update_qty.php',
            type: 'POST',
            data: {
                product_id: productId,
                qty: qty
            },
            success: function(response) {
                if (response.success) {
                    updateCartCount(response.data.cart_count);
                    updateCartSummary(response.data.totals);
                    
                    // Update line total
                    const $row = $('[data-product-id="' + productId + '"]').closest('.cart-item');
                    const unitPrice = parseFloat($row.data('unit-price'));
                    $row.find('.line-total').text(formatPrice(unitPrice * qty));
                } else {
                    showToast(response.message, 'error');
                }
            }
        });
    }
    
    // ============================================================
    // Remove from Cart
    // ============================================================
    $(document).on('click', '.btn-remove-cart', function(e) {
        e.preventDefault();
        
        const productId = $(this).data('product-id');
        
        confirmAction({
            title: 'পণ্য সরাতে চান?',
            text: 'এই পণ্যটি কার্ট থেকে সরানো হবে।',
            confirmButtonText: 'হ্যাঁ, সরান'
        }).then((result) => {
            if (result.isConfirmed) {
                removeFromCart(productId);
            }
        });
    });
    
    function removeFromCart(productId) {
        $.ajax({
            url: ajaxUrl + '/cart/remove.php',
            type: 'POST',
            data: { product_id: productId },
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    updateCartCount(response.data.cart_count);
                    
                    // Remove item from DOM
                    $('[data-product-id="' + productId + '"]').closest('.cart-item').fadeOut(300, function() {
                        $(this).remove();
                        
                        // Check if cart is empty
                        if ($('.cart-item').length === 0) {
                            location.reload();
                        } else {
                            updateCartSummary(response.data.totals);
                        }
                    });
                } else {
                    showToast(response.message, 'error');
                }
            }
        });
    }
    
    function updateCartSummary(totals) {
        if (!totals) return;
        
        $('#cart-subtotal').text(formatPrice(totals.subtotal));
        $('#cart-vat').text(formatPrice(totals.vat_amount));
        $('#cart-tax').text(formatPrice(totals.tax_amount));
        $('#cart-discount').text(formatPrice(totals.discount_amount));
        $('#cart-grand-total').text(formatPrice(totals.grand_total));
    }
    
    // ============================================================
    // Apply Promo Code
    // ============================================================
    $(document).on('click', '#applyPromoBtn', function(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const code = $('#promoCodeInput').val().trim();
        
        if (!code) {
            showToast('প্রোমো কোড দিন', 'warning');
            return;
        }
        
        setButtonLoading($btn, true);
        
        $.ajax({
            url: ajaxUrl + '/promo/apply.php',
            type: 'POST',
            data: { code: code },
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    
                    // Update summary
                    $('#cart-discount').text(formatPrice(response.data.discount_amount));
                    $('#cart-grand-total').text(formatPrice(response.data.grand_total));
                    
                    // Store promo data
                    $('#applied-promo-id').val(response.data.promo.id);
                    $('#applied-promo-code').val(response.data.promo.code);
                    
                    // Show applied message
                    $('#promoAppliedMsg').html(
                        '<span class="text-success"><i class="bi bi-check-circle me-1"></i>' +
                        response.data.promo.code + ' প্রয়োগ হয়েছে - ছাড়: ' + 
                        formatPrice(response.data.discount_amount) + '</span>'
                    ).show();
                    
                    // Disable input
                    $('#promoCodeInput').prop('disabled', true);
                    $btn.text('প্রয়োগ হয়েছে').prop('disabled', true);
                } else {
                    showToast(response.message, 'error');
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // ============================================================
    // Wishlist Toggle
    // ============================================================
    $(document).on('click', '.btn-wishlist', function(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const productId = $btn.data('product-id');
        
        $.ajax({
            url: ajaxUrl + '/wishlist/toggle.php',
            type: 'POST',
            data: { product_id: productId },
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    
                    // Toggle icon
                    const $icon = $btn.find('i');
                    if (response.data.in_wishlist) {
                        $icon.removeClass('bi-heart').addClass('bi-heart-fill text-danger');
                    } else {
                        $icon.removeClass('bi-heart-fill text-danger').addClass('bi-heart');
                    }
                } else {
                    showToast(response.message, 'error');
                }
            }
        });
    });
    
    // ============================================================
    // Payment Method Selection
    // ============================================================
    $(document).on('click', '.payment-method-card', function() {
        const $card = $(this);
        const method = $card.data('method');
        
        // Update selection
        $('.payment-method-card').removeClass('selected');
        $card.addClass('selected');
        
        // Update hidden input
        $('#payment-method').val(method);
        
        // Update merchant number display
        const merchantNumber = $card.data('merchant');
        $('#merchant-number').text(merchantNumber);
        $('#payment-instructions').show();
    });
    
    // ============================================================
    // Submit Payment Details
    // ============================================================
    $(document).on('submit', '#paymentForm', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        
        // Validate
        const senderMobile = $('#sender_mobile').val().trim();
        const trxId = $('#trx_id').val().trim();
        const method = $('#payment-method').val();
        
        if (!method) {
            showToast('পেমেন্ট মেথড সিলেক্ট করুন', 'warning');
            return;
        }
        
        if (!senderMobile) {
            showToast('আপনার মোবাইল নম্বর দিন', 'warning');
            $('#sender_mobile').focus();
            return;
        }
        
        if (!trxId) {
            showToast('Transaction ID দিন', 'warning');
            $('#trx_id').focus();
            return;
        }
        
        setButtonLoading($btn, true);
        clearFormErrors($form);
        
        $.ajax({
            url: ajaxUrl + '/orders/submit_payment.php',
            type: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    
                    // Redirect to success page
                    setTimeout(function() {
                        window.location.href = siteUrl + '/public/?page=order-success&order=' + response.data.order_no;
                    }, 1500);
                } else {
                    showToast(response.message, 'error');
                    if (response.errors) {
                        showFormErrors($form, response.errors);
                    }
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // ============================================================
    // Place Order (Checkout)
    // ============================================================
    $(document).on('submit', '#checkoutForm', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        
        // Validate payment method
        if (!$('#payment-method').val()) {
            showToast('পেমেন্ট মেথড সিলেক্ট করুন', 'warning');
            return;
        }
        
        setButtonLoading($btn, true);
        clearFormErrors($form);
        
        $.ajax({
            url: ajaxUrl + '/orders/place_order.php',
            type: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    
                    // Redirect to payment page or success
                    setTimeout(function() {
                        window.location.href = siteUrl + '/public/?page=order-success&order=' + response.data.order_no;
                    }, 1500);
                } else {
                    showToast(response.message, 'error');
                    if (response.errors) {
                        showFormErrors($form, response.errors);
                    }
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // ============================================================
    // Submit Review
    // ============================================================
    $(document).on('submit', '#reviewForm', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        
        // Validate rating
        const rating = $form.find('input[name="rating"]:checked').val();
        if (!rating) {
            showToast('রেটিং দিন', 'warning');
            return;
        }
        
        setButtonLoading($btn, true);
        
        $.ajax({
            url: ajaxUrl + '/reviews/submit.php',
            type: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    $form[0].reset();
                    
                    // Hide form, show thank you message
                    $form.slideUp();
                    $('#reviewThankYou').slideDown();
                } else {
                    showToast(response.message, 'error');
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // ============================================================
    // User Authentication
    // ============================================================
    
    // Login Form
    $(document).on('submit', '#loginForm', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        
        setButtonLoading($btn, true);
        clearFormErrors($form);
        
        $.ajax({
            url: ajaxUrl + '/auth/login.php',
            type: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    
                    // Redirect
                    setTimeout(function() {
                        window.location.href = response.data.redirect || siteUrl + '/public/';
                    }, 1000);
                } else {
                    showToast(response.message, 'error');
                    if (response.errors) {
                        showFormErrors($form, response.errors);
                    }
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // Register Form
    $(document).on('submit', '#registerForm', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        
        setButtonLoading($btn, true);
        clearFormErrors($form);
        
        $.ajax({
            url: ajaxUrl + '/auth/register.php',
            type: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    
                    setTimeout(function() {
                        window.location.href = siteUrl + '/public/?page=login';
                    }, 1500);
                } else {
                    showToast(response.message, 'error');
                    if (response.errors) {
                        showFormErrors($form, response.errors);
                    }
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // Logout
    $(document).on('click', '#logoutBtn', function(e) {
        e.preventDefault();
        
        $.ajax({
            url: ajaxUrl + '/auth/logout.php',
            type: 'POST',
            success: function(response) {
                showToast('সফলভাবে লগআউট হয়েছে', 'success');
                setTimeout(function() {
                    window.location.href = siteUrl + '/public/';
                }, 1000);
            }
        });
    });
    
    // ============================================================
    // Quantity Input Buttons (Product Page)
    // ============================================================
    $(document).on('click', '.qty-btn', function() {
        const $input = $(this).siblings('.qty-input');
        const action = $(this).data('action');
        let value = parseInt($input.val()) || 1;
        
        if (action === 'increase') {
            value++;
        } else if (action === 'decrease' && value > 1) {
            value--;
        }
        
        $input.val(value);
    });
    
    // ============================================================
    // Image Gallery (Product Page)
    // ============================================================
    $(document).on('click', '.product-thumb', function() {
        const src = $(this).data('src');
        $('#mainProductImage').attr('src', src);
        
        $('.product-thumb').removeClass('active');
        $(this).addClass('active');
    });
    
})(jQuery);
