/**
 * ============================================================
 * ADMIN PANEL - JavaScript
 * ============================================================
 */

(function($) {
    'use strict';
    
    const adminUrl = window.location.origin + '/safa-modest-house/admin';
    const ajaxUrl = adminUrl + '/ajax';
    
    // CSRF Token
    const csrfToken = $('meta[name="csrf-token"]').attr('content');
    
    // Setup AJAX defaults
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrfToken,
            'X-Requested-With': 'XMLHttpRequest'
        }
    });
    
    // ============================================================
    // Sidebar Toggle (Mobile)
    // ============================================================
    $('#sidebarToggle').on('click', function() {
        $('#adminSidebar').toggleClass('show');
        $('.sidebar-overlay').toggleClass('show');
    });
    
    $('.sidebar-overlay').on('click', function() {
        $('#adminSidebar').removeClass('show');
        $(this).removeClass('show');
    });
    
    // ============================================================
    // Toast Notification
    // ============================================================
    window.showToast = function(message, type = 'success') {
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: type,
            title: message,
            showConfirmButton: false,
            timer: 3000
        });
    };
    
    // ============================================================
    // Confirm Dialog
    // ============================================================
    window.confirmAction = function(options = {}) {
        return Swal.fire({
            title: options.title || 'Are you sure?',
            text: options.text || 'This action cannot be undone.',
            icon: options.icon || 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            cancelButtonColor: '#858796',
            confirmButtonText: options.confirmText || 'Yes, proceed',
            cancelButtonText: options.cancelText || 'Cancel'
        });
    };
    
    // ============================================================
    // Button Loading State
    // ============================================================
    window.setButtonLoading = function($btn, loading = true) {
        if (loading) {
            $btn.data('original-text', $btn.html());
            $btn.html('<span class="spinner-border spinner-border-sm me-1"></span>Loading...');
            $btn.prop('disabled', true);
        } else {
            $btn.html($btn.data('original-text'));
            $btn.prop('disabled', false);
        }
    };
    
    // ============================================================
    // Order Status Change
    // ============================================================
    $(document).on('click', '.btn-change-status', function() {
        const $btn = $(this);
        const orderId = $btn.data('order-id');
        const currentStatus = $btn.data('current-status');
        
        Swal.fire({
            title: 'Change Order Status',
            html: `
                <select id="statusSelect" class="form-select mb-3">
                    <option value="Pending" ${currentStatus === 'Pending' ? 'selected' : ''}>Pending</option>
                    <option value="Processing" ${currentStatus === 'Processing' ? 'selected' : ''}>Processing</option>
                    <option value="Shipped" ${currentStatus === 'Shipped' ? 'selected' : ''}>Shipped</option>
                    <option value="Delivered" ${currentStatus === 'Delivered' ? 'selected' : ''}>Delivered</option>
                    <option value="Cancelled" ${currentStatus === 'Cancelled' ? 'selected' : ''}>Cancelled</option>
                </select>
                <input type="text" id="statusNote" class="form-control" placeholder="Note (optional)">
            `,
            showCancelButton: true,
            confirmButtonText: 'Update Status',
            preConfirm: () => {
                return {
                    status: $('#statusSelect').val(),
                    note: $('#statusNote').val()
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: ajaxUrl + '/orders/change_status.php',
                    type: 'POST',
                    data: {
                        order_id: orderId,
                        status: result.value.status,
                        note: result.value.note
                    },
                    success: function(response) {
                        if (response.success) {
                            showToast(response.message, 'success');
                            location.reload();
                        } else {
                            showToast(response.message, 'error');
                        }
                    }
                });
            }
        });
    });
    
    // ============================================================
    // Payment Verification
    // ============================================================
    $(document).on('click', '.btn-verify-payment', function() {
        const $btn = $(this);
        const paymentId = $btn.data('payment-id');
        const action = $btn.data('action'); // 'verify' or 'reject'
        
        const title = action === 'verify' ? 'Verify Payment' : 'Reject Payment';
        const confirmText = action === 'verify' ? 'Yes, Verify' : 'Yes, Reject';
        
        Swal.fire({
            title: title,
            html: '<input type="text" id="paymentNote" class="form-control" placeholder="Note (optional)">',
            icon: action === 'verify' ? 'question' : 'warning',
            showCancelButton: true,
            confirmButtonText: confirmText,
            confirmButtonColor: action === 'verify' ? '#1cc88a' : '#e74a3b'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: ajaxUrl + '/orders/verify_payment.php',
                    type: 'POST',
                    data: {
                        payment_id: paymentId,
                        action: action,
                        note: $('#paymentNote').val()
                    },
                    success: function(response) {
                        if (response.success) {
                            showToast(response.message, 'success');
                            location.reload();
                        } else {
                            showToast(response.message, 'error');
                        }
                    }
                });
            }
        });
    });
    
    // ============================================================
    // Delete Confirmation
    // ============================================================
    $(document).on('click', '.btn-delete', function(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const url = $btn.data('url');
        const itemType = $btn.data('type') || 'item';
        
        confirmAction({
            title: 'Delete ' + itemType + '?',
            text: 'This action cannot be undone.'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: $btn.data(),
                    success: function(response) {
                        if (response.success) {
                            showToast(response.message, 'success');
                            $btn.closest('tr').fadeOut(300, function() {
                                $(this).remove();
                            });
                        } else if (response.has_orders) {
                            // Product has orders - ask for force delete
                            Swal.fire({
                                title: 'পণ্যের অর্ডার আছে!',
                                text: 'এই পণ্যের ' + response.order_count + ' টি অর্ডার আছে। জোর করে মুছতে চান?',
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: '#e74a3b',
                                confirmButtonText: 'হ্যাঁ, মুছে ফেলুন',
                                cancelButtonText: 'বাতিল'
                            }).then((forceResult) => {
                                if (forceResult.isConfirmed) {
                                    var postData = $btn.data();
                                    postData.forceDelete = true;
                                    $.ajax({
                                        url: url,
                                        type: 'POST',
                                        data: postData,
                                        success: function(res) {
                                            if (res.success) {
                                                showToast(res.message, 'success');
                                                $btn.closest('tr').fadeOut(300, function() {
                                                    $(this).remove();
                                                });
                                            } else {
                                                showToast(res.message, 'error');
                                            }
                                        }
                                    });
                                }
                            });
                        } else {
                            showToast(response.message, 'error');
                        }
                    }
                });
            }
        });
    });
    
    // ============================================================
    // User Block/Unblock
    // ============================================================
    $(document).on('click', '.btn-toggle-block', function() {
        const $btn = $(this);
        const userId = $btn.data('user-id');
        const action = $btn.data('action');
        
        const title = action === 'block' ? 'Block User?' : 'Unblock User?';
        
        confirmAction({ title: title }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: ajaxUrl + '/users/block.php',
                    type: 'POST',
                    data: {
                        user_id: userId,
                        action: action
                    },
                    success: function(response) {
                        if (response.success) {
                            showToast(response.message, 'success');
                            location.reload();
                        } else {
                            showToast(response.message, 'error');
                        }
                    }
                });
            }
        });
    });
    
    // ============================================================
    // Review Approve/Reject
    // ============================================================
    $(document).on('click', '.btn-review-action', function() {
        const $btn = $(this);
        const reviewId = $btn.data('review-id');
        const action = $btn.data('action');
        
        $.ajax({
            url: ajaxUrl + '/reviews/approve.php',
            type: 'POST',
            data: {
                review_id: reviewId,
                action: action
            },
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    $btn.closest('tr').fadeOut();
                } else {
                    showToast(response.message, 'error');
                }
            }
        });
    });
    
    // ============================================================
    // Image Upload Preview
    // ============================================================
    const $uploadZone = $('.image-upload-zone');
    const $imageInput = $('#productImages');
    const $previewGrid = $('.image-preview-grid');
    
    // Click to upload
    $uploadZone.on('click', function() {
        $imageInput.click();
    });
    
    // Drag and drop
    $uploadZone.on('dragover', function(e) {
        e.preventDefault();
        $(this).addClass('dragover');
    });
    
    $uploadZone.on('dragleave', function() {
        $(this).removeClass('dragover');
    });
    
    $uploadZone.on('drop', function(e) {
        e.preventDefault();
        $(this).removeClass('dragover');
        
        const files = e.originalEvent.dataTransfer.files;
        $imageInput[0].files = files;
        previewImages(files);
    });
    
    // File input change
    $imageInput.on('change', function() {
        previewImages(this.files);
    });
    
    function previewImages(files) {
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (!file.type.startsWith('image/')) continue;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                const html = `
                    <div class="image-preview-item">
                        <img src="${e.target.result}" alt="Preview">
                        <div class="image-actions">
                            <button type="button" class="btn btn-danger btn-sm btn-remove-preview">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>
                `;
                $previewGrid.append(html);
            };
            reader.readAsDataURL(file);
        }
    }
    
    // Remove preview
    $(document).on('click', '.btn-remove-preview', function() {
        $(this).closest('.image-preview-item').remove();
    });
    
    // ============================================================
    // Form Submission with File Upload
    // ============================================================
    $('#productForm').on('submit', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        const formData = new FormData(this);
        
        setButtonLoading($btn, true);
        
        $.ajax({
            url: $form.attr('action'),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(function() {
                        window.location.href = adminUrl + '/?page=products';
                    }, 1000);
                } else {
                    showToast(response.message, 'error');
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
    // ============================================================
    // Promo Code Form
    // ============================================================
    $('#promoForm').on('submit', function(e) {
        e.preventDefault();
        
        const $form = $(this);
        const $btn = $form.find('button[type="submit"]');
        
        setButtonLoading($btn, true);
        
        $.ajax({
            url: $form.attr('action'),
            type: 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(function() {
                        window.location.href = adminUrl + '/?page=promo-codes';
                    }, 1000);
                } else {
                    showToast(response.message, 'error');
                }
            },
            complete: function() {
                setButtonLoading($btn, false);
            }
        });
    });
    
})(jQuery);
