/*==========================
# Create order Query
============================*/
$(document).ready(function(){
    $('#o-submit').click(function (e){
        e.preventDefault();
        var form = $('#createUserForm')[0];
        var item = $('#o-item').val();
        var unit = $('#o-unit').val();
        var location = $('#o-location').val();

        var formData = new FormData();
        formData.append('item', item);
        formData.append('unit', unit);
        formData.append('location', location);
        formData.append('action', 'create_orders');
        
        $('#o-submit').prop('disabled', true).text('Processing...');
        $.ajax({
            type: "POST",
            url: "inc/code_query.php",
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                if(response == 1) {
                    Swal.fire({
                        title: "Success",
                        text: "Your Order has been successfully created.",
                        icon: "success"
                    }).then(() => {
                        $('#o-submit').prop('disabled', false).text('Submit');
                        window.location.reload();
                    });
                } else {
                    Swal.fire({
                        title: "Error",
                        text: response,
                        icon: "error"
                    })
                }
            }
        });
    });
});
/*==========================
# Create order Query
============================*/
$(document).ready(function(){
    $('[id^=confirmDelivery_]').click(function (e){
        e.preventDefault();
        var buttonId = $(this).attr('id');
        var index = buttonId.split('_').pop();

        $.ajax({
            type: "POST",
            url: "inc/code_query.php",
            data: {order_id: index, action: 'confirmDelivery'},
            success: function(response) {
                if(response == 1) {
                    Swal.fire({
                        title: "Success",
                        text: "Your Order has been successfully Delivery.",
                        icon: "success"
                    }).then(() => {
                        $('#o-submit').prop('disabled', false).text('Submit');
                        window.location.reload();
                    });
                } else {
                    Swal.fire({
                        title: "Error",
                        text: response,
                        icon: "error"
                    })
                }
            }
        });
    });
});





$(document).ready(function() {
    $('#Topup_submit').click(function (e) {
        e.preventDefault();
        
        // 1. Correct Selectors (Added # for IDs)
        const formData = new FormData();
        const amount = $('#t-amount').val();

        // 2. Validation Fix
        if (!amount || amount <= 0) {
            Swal.fire("Error", "Please enter a valid amount.", "warning");
            return;
        }

        formData.append('action', 'processTopup');
        formData.append('amount', $('#t-amount').val());
        formData.append('bank', $('#t-bank').val());
        formData.append('reference', $('#t-ref').val());
        formData.append('description', $('#t-desc').val());
        
        // 3. File Input Fix (jQuery objects don't have .files, use [0])
        const receiptFileInput = $('#t-receipt')[0]; 
        if (receiptFileInput && receiptFileInput.files[0]) {
            formData.append('receipt', receiptFileInput.files[0]);
        }

        $.ajax({
            method: 'POST',
            url: 'inc/code_query.php',
            data: formData,
            contentType: false, // Required for FormData
            processData: false, // Required for FormData
            beforeSend: function() {
                // Disable button and show loading state
                $('#Topup_submit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Sending...');
            },
            success: function(response) {
                // Trim response to handle accidental whitespace from PHP
                if (response.trim() == "1") {
                    Swal.fire({
                        title: "Success",
                        text: "Top-up request submitted! Admin will verify your payment shortly.",
                        icon: "success"
                    }).then(() => {
                        window.location.reload(); // Reload to show pending transaction
                    });
                } else {
                    Swal.fire({
                        title: "Error",
                        text: response,
                        icon: "error"
                    });
                    $('#Topup_submit').prop('disabled', false).text('Confirm Deposit');
                }
            },
            error: function() {
                Swal.fire("Error", "Could not connect to server.", "error");
                $('#Topup_submit').prop('disabled', false).text('Confirm Deposit');
            }
        });
    });
});







function generatePreview() {
    const from = $('#state-from').val();
    const to = $('#state-to').val();

    if (!from || !to) {
        Swal.fire("Wait", "Please select a date range", "info");
        return;
    }

    $.ajax({
        url: 'inc/code_query.php',
        method: 'POST',
        data: { action: 'getStatement', from: from, to: to },
        // If it's still not displaying, remove 'json' temporarily to see errors
        dataType: 'json', 
        success: function(response) {
            if (response.status === "success") {
                // Update the Top Cards
                $('#sum-inflow').text('₦' + response.totals.inflow);
                $('#sum-outflow').text('₦' + response.totals.outflow);
                $('#sum-net').text('₦' + response.totals.net);

                // Inject the Table Rows
                $('#statement-table-body').html(response.html);

                // IMPORTANT: Remove the d-none class to make it visible
                $('#statement-preview').removeClass('d-none').hide().fadeIn();
            } else {
                Swal.fire("No Data", "No transactions found for these dates.", "warning");
            }
        },
        error: function(xhr, status, error) {
            // This will tell you exactly why it's not displaying in the console
            console.error("AJAX Error: " + error);
            console.log(xhr.responseText); 
            Swal.fire("Error", "Server returned an invalid response. Check console.", "error");
        }
    });
}


/*==========================
# Log Out Query
===========================*/
$(document).ready(function(){
    $('#authorize_sign_out').click(function (e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "inc/code_query.php",
            data: { action: 'authorize_sign_out' },
            success: function(response) {
                Swal.fire({
                title: "Logout",
                icon: "success"
                }).then(() => {
                    window.location.href = '../auth-login.html';
                });         
            }
        });
    });
});


function saveProfile() {

    const profileImg = $('#profile_img')[0].files[0];
    const btn = $('#updateBtn');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Updating...');

    // 3. Create FormData for versatile handling (Text + Files)
    const formData = new FormData();
    formData.append('action', 'update_user_profile');
    formData.append('full_name', $('input[name="full-name"]').val());
    formData.append('phone', $('input[name="phone-no"]').val());
    formData.append('email', $('input[name="email"]').val());
    formData.append('address', $('textarea[name="address"]').val());
    formData.append('kin_name', $('input[name="kin-name"]').val());
    formData.append('kin_relation', $('select[name="kin-relation"]').val());
    formData.append('kin_phone', $('input[name="kin-phone"]').val());
    formData.append('kin_email', $('input[name="kin-email"]').val());
    formData.append('kin_address', $('input[name="kin-address"]').val());
    formData.append('pre_profile_img', $('input[name="pre_profile_img"]').val());
    
    if (profileImg) {
        formData.append('profile_img', profileImg);
    }

    // 4. AJAX Call
    $.ajax({
        url: 'inc/code_query.php',
        type: 'POST',
        data: formData,
        processData: false, 
        contentType: false, 
        success: function(res) {
            if (res.trim() == "1") {
                Swal.fire('Success', 'Profile Updated Successfully', 'success')
                    .then(() => location.reload());
            } else {
                Swal.fire('Error', res, 'error');
            }
        },
        error: function() {
            Swal.fire('Error', 'Connection failed', 'error');
        },
        complete: function() {
            btn.prop('disabled', false).text('Update Profile');
        }
    });
}



function updatePassword() {
    // Select the values
    const currPass = $('#curr-pass').val();
    const newPass = $('#new-pass').val();
    const confirmPass = $('#confirm-pass').val();
    const btn = $('#passBtn');

    // INSPECTION: Check if variables are defined and not null
    if (!newPass || !confirmPass) {
        return Swal.fire('Error', 'Please fill in all password fields', 'error');
    }

    if (newPass !== confirmPass) {
        return Swal.fire('Error', 'New passwords do not match!', 'error');
    }

    // Now it is safe to check .length
    if (newPass.length < 8 || !/[A-Z]/.test(newPass) || !/[0-9]/.test(newPass)) {
        return Swal.fire('Weak Password', 'Password must be 8+ chars with 1 Uppercase and 1 Number.', 'warning');
    }

    // 2. UI Feedback
    btn.prop('disabled', true).text('Verifying...');

    // 3. AJAX Update
    $.ajax({
        url: 'inc/code_query.php',
        type: 'POST',
        data: {
            action: 'change_user_password',
            curr_pass: currPass,
            new_pass: newPass
        },
        success: function(res) {
            if (res.trim() == "1") {
                Swal.fire('Success', 'Password changed successfully!', 'success');
                $('#passwordForm')[0].reset(); // Clear form
            } else {
                Swal.fire('Error', res, 'error');
            }
        },
        error: function() {
            Swal.fire('Error', 'Server connection failed', 'error');
        },
        complete: function() {
            btn.prop('disabled', false).text('Update Password');
        }
    });
}
