// Get current location
if (currentLocation === 'stripe-products-prices') {
    listProductPriceDataToDatatable();
}

if (currentLocation === 'stripe-subscriptions') {
    listSubscriptionDataToDatatable();
}

if (currentLocation === 'stripe-invoices') {
    listInvoiceDataToDatatable();
}

if (currentLocation === 'stripe-customers') {
    listCustomersDataToDatatable();
}

if (currentLocation === 'billing') {
    getStripeCustomerSubscriptionData();
    // listStripeInvoiceDataToDatatable();
}

// Column selectors
const tbStripeProductPrice = $('.stripe-product-price-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    // order: [[0, "desc"]],
});

// Add New Product Price
$(document).on("click", ".btnAddProductPrice", function () {
    document.getElementById("frmAddProductPrice").reset();
    $('#product-price-modal').modal('show');
});

// Get data from API
async function getProductPriceDataFromAPI(props) {
    try {

        const url = 'stripe/stripe.controller.php?case=productPriceListing';
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.log(error);
        return false;
    }
}

// List All data function
async function listProductPriceDataToDatatable() {

    // ── Helper: capitalize first letter ───────────────────────────────────────
    const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

    try {
        const res = await getProductPriceDataFromAPI();

        if (res.status === 'success') {

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    const planInterval = capitalize(item.plan_interval);
                    const planName = `${item.plan_name} -> (${showCurrencyFormat('USD', '', item.plan_price)})`;
                    const planRecurring = item.plan_recurring.toLowerCase() === 'yes'
                        ? `Recurring -> (Each ${item.plan_interval_count} ${planInterval})`
                        : 'One-Time';

                    return [
                        item.plan_id,
                        item.plan_created_at_formatted,
                        item.plan_product_id,
                        item.plan_product_price_id,
                        planName,
                        planRecurring,
                        item.plan_description,
                        item.plan_features,
                    ];
                });

                tbStripeProductPrice.clear().rows.add(formattedData).draw();

            } else {
                tbStripeProductPrice.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbStripeProductPrice.clear().draw();

        } else {

            tbStripeProductPrice.clear().draw();
            console.error('listProductPriceDataToDatatable unexpected response:', res);
        }

    } catch (error) {
        tbStripeProductPrice.clear().draw();
        console.error('listProductPriceDataToDatatable error:', error);
    }
}

/*=============================================
VALIDATE INPUT FORM
=============================================*/
function validateInputFormData() {

    var plan_name = $("#plan_name").val();
    var plan_price = $("#plan_price").val();

    if ($.trim(plan_name) == "") {
        $("#plan_name").css("border", "1px solid red ");
        fnSweetToast("Enter plan name", "error", 3500);
        return false;
    } else {
        $("#plan_name").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($.trim(plan_price) == "" && Number(plan_price) <= 0) {
        $("#plan_price").css("border", "1px solid red ");
        fnSweetToast("Enter plan price", "error", 3500);
        return false;
    } else {
        $("#plan_price").css("border", `1px solid ${borderColorValidated}`);
    }
    return true;
}

$(".btnSave").click(function () {
    if (validateInputFormData() == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

// Prevent form submission on Enter key press
if (currentLocation === 'stripe-products-prices') {

    document.getElementById('plan_name').addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            event.preventDefault(); // Prevent the form from submitting
        }
    });

    document.getElementById('plan_description').addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            event.preventDefault(); // Prevent the form from submitting
        }
    });

    document.getElementById('plan_price').addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            event.preventDefault(); // Prevent the form from submitting
        }
    });
}

// ── Helper: set all action buttons to a given state ───────────────────────
function setButtonStatus(state) {
    if (state === 'loading') {
        $('.btnSave')
            .prop('disabled', true)
            .css('cursor', 'not-allowed')
            .html(translate.waiting_icon_text);
        return;
    }
    if (state === 'ready') {
        $('.btnSave')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-floppy-disk me-1"></i> ${translate.save}`);
    }
}

/*=============================================
FUNCTION TO SAVE OR UPDATE DATA
=============================================*/
async function fnSaveUpdate() {

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmAddProductPrice")[0]);
    const apiUrl = 'stripe/stripe.controller.php?case=createNewStripeProductPrice';

    // for (var pair of formPostData.entries()) {
    //     console.log(pair[0] + " - " + pair[1]);
    // }
    // return;

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            body: formPostData,
        });

        const data = await response.json();
        console.log(data);

        if (data.success == true) {

            setButtonStatus('ready');

            document.getElementById("frmAddProductPrice").reset();
            swalInit.fire(data.message, "", "success");
            $("#product-price-modal").modal("hide");
            listProductPriceDataToDatatable();

        } else {
            console.log(data);
            swalInit.fire(data.error, "", "error").then(function (result) {
                $("#product-price-modal").modal("hide");
                document.getElementById("frmAddProductPrice").reset();
                setButtonStatus('ready');
            });
        }

    } catch (error) {
        console.error('Error:', error);
        swalInit.fire(error.message, "", "error").then(function (result) {
            $("#product-price-modal").modal("hide");
            document.getElementById("frmAddProductPrice").reset();
            setButtonStatus('ready');
        });
    }
}

// Create DataTable instance for Subscriptions
const tbStripeSubscriptions = $('.stripe-subscriptions-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    order: [[0, "desc"]],
});

// Get data from API
async function getSubscriptionDataFromAPI(props) {
    try {

        const url = `stripe/stripe.controller.php?case=subscriptionListing&status=${props.status}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.log(error);
        return false;
    }
}

// List All data function
async function listSubscriptionDataToDatatable() {

    // ── Status badge map ──────────────────────────────────────────────────────
    const statusBadgeClass = {
        active: 'bg-success',
        canceled: 'bg-danger',
    };

    let subsTotalPaid = 0;

    const props = {
        status: ($(".searchStatus").val() || '').trim(),
    };

    // ── Validate required props ───────────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([, value]) => value === '' || value === undefined)
        .map(([key]) => key);

    if (missingProps.length > 0) {
        resetSearchButton();
        await swalInit.fire(translate.please_fill_in_all_required_fields, missingProps.join(', '), 'warning');
        return;
    }

    try {
        const res = await getSubscriptionDataFromAPI(props);

        if (res.status === 'success') {

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    const subsAmountTotal = Number(item.subs_amount_unit) * Number(item.subs_quantity);

                    subsTotalPaid += subsAmountTotal;

                    // ── Subscription status badge ─────────────────────────────
                    const badgeClass = statusBadgeClass[item.subscription_status] ?? 'bg-warning';
                    const subscriptionStatus = `<span class="badge ${badgeClass} fw-medium text-white">
                                                     ${item.subscription_status.toUpperCase()}
                                                 </span>`;

                    return [
                        item.subs_id,
                        item.subs_created_at_formatted,
                        item.subs_subscription_id,
                        item.subs_customer_id,
                        item.subs_customer_account_id,
                        item.ent_name,
                        item.customer_email,
                        item.customer_name,
                        showCurrencyFormat(item.subs_currency, '', subsAmountTotal),
                        subscriptionStatus,
                    ];
                });

                tbStripeSubscriptions.clear().rows.add(formattedData).draw();

            } else {
                tbStripeSubscriptions.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbStripeSubscriptions.clear().draw();

        } else {

            tbStripeSubscriptions.clear().draw();
            console.error('listSubscriptionDataToDatatable unexpected response:', res);
        }

    } catch (error) {
        tbStripeSubscriptions.clear().draw();
        console.error('listSubscriptionDataToDatatable error:', error);

    } finally {
        $('#subsTotalPaid').text(showCurrencyFormat('USD', '', subsTotalPaid));
    }
}


// Create DataTable for Invoices
const tbStripeInvoices = $('.stripe-invoices-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    order: [[0, "desc"]],
});


// Get data from API
async function getInvoiceDataFromAPI(props = "") {
    try {

        // You can dynamically build the URL using parameters
        const params = new URLSearchParams({
            case: 'invoiceListing',
            ...props,
        });

        const url = `stripe/stripe.controller.php?${params.toString()}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.log(error);
        return false;
    }
}


// List All data function
async function listInvoiceDataToDatatable() {

    // ── Helper: format currency for this module (currency from item) ──────────
    const fmtItem = (currency, val) => showCurrencyFormat(currency, '', val);
    const fmtUSD = val => showCurrencyFormat('USD', '', val);

    // ── Status badge map ──────────────────────────────────────────────────────
    const statusBadgeClass = {
        paid: 'bg-success',
        uncollectible: 'bg-danger',
        void: 'bg-danger',
    };

    // ── Amount colour map ─────────────────────────────────────────────────────
    const amountClass = {
        paid: 'text-success',
    };

    let invoiceTotalDue = 0;
    let invoiceTotalPaid = 0;

    // ── Collect filter parameters ─────────────────────────────────────────────
    const [fromDate, toDate] = $.trim($('.dateSelected').val()).split(' / ');

    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
        status: ($(".searchStatus").val() || '').trim(),
        fromDate,
        toDate,
    };

    // ── Validate required props ───────────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([, value]) => value === '' || value === undefined)
        .map(([key]) => key);

    if (missingProps.length > 0) {
        resetSearchButton();
        await swalInit.fire(translate.please_fill_in_all_required_fields, missingProps.join(', '), 'warning');
        return;
    }

    try {
        const res = await getInvoiceDataFromAPI(props);

        if (res.status === 'success') {

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    invoiceTotalDue += Number(item.inv_amount_due);
                    invoiceTotalPaid += Number(item.inv_amount_paid);

                    // ── Status badge ──────────────────────────────────────────
                    const badgeClass = statusBadgeClass[item.inv_status] ?? 'bg-warning';
                    const invoiceStatus = `<span class="badge ${badgeClass} fw-medium text-white">
                                               ${item.inv_status.toUpperCase()}
                                           </span>`;

                    // ── Amount colours — both reflect paid status ─────────────
                    const amtClass = amountClass[item.inv_status] ?? 'text-warning';
                    const invoiceAmountDue = `<span class="fw-medium ${amtClass}">${fmtItem(item.inv_currency, item.inv_amount_due)}</span>`;
                    const invoiceAmountPaid = `<span class="fw-medium ${amtClass}">${fmtItem(item.inv_currency, item.inv_amount_paid)}</span>`;

                    return [
                        item.inv_id,
                        item.inv_stripe_invoice_id,
                        item.inv_date_formatted,
                        item.enterprise_name,
                        item.inv_customer_email,
                        item.inv_customer_name,
                        invoiceAmountDue,
                        invoiceAmountPaid,
                        invoiceStatus,
                        `<a  href="${item.inv_hosted_url}"
                             target="_blank"
                             class="btn btn-sm btn-indigo fw-medium fs-md">
                             <i class="ph-eye me-1"></i> View Invoice
                         </a>`,
                    ];
                });

                tbStripeInvoices.clear().rows.add(formattedData).draw();

            } else {
                tbStripeInvoices.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbStripeInvoices.clear().draw();

        } else {

            tbStripeInvoices.clear().draw();
            console.error('listInvoiceDataToDatatable unexpected response:', res);
        }

    } catch (error) {
        tbStripeInvoices.clear().draw();
        console.error('listInvoiceDataToDatatable error:', error);

    } finally {
        $('#invoiceTotalDue').text(fmtUSD(invoiceTotalDue));
        $('#invoiceTotalPaid').text(fmtUSD(invoiceTotalPaid));
    }
}




// Create DataTable for Customers
const tbStripeCustomers = $('.stripe-customers-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    order: [[0, "desc"]],
});


// Get data from API
async function getCustomersDataFromAPI(props) {
    try {

        const url = 'stripe/stripe.controller.php?case=customerListing';
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.log(error);
        return false;
    }
}


// List All data function
async function listCustomersDataToDatatable() {

    let customerTotalBalance = 0;

    try {
        const res = await getCustomersDataFromAPI();

        if (res.status === 'success') {

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    customerTotalBalance += Number(item.customer_balance);

                    return [
                        item.cus_id,
                        item.customer_created_at_formatted,
                        item.customer_id,
                        item.customer_enterprise_id,
                        item.customer_email,
                        item.customer_name,
                        item.customer_phone,
                        `<button type="button" class="btn btn-sm btn-indigo"
                             onclick='jsViewCustomerDetail(${JSON.stringify(item)})'>
                         <i class="ph-eye me-1"></i> ${translate.view}
                        </button>`,
                    ];
                });

                tbStripeCustomers.clear().rows.add(formattedData).draw();

            } else {
                tbStripeCustomers.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbStripeCustomers.clear().draw();

        } else {

            tbStripeCustomers.clear().draw();
            console.error('listCustomersDataToDatatable unexpected response:', res);
        }

    } catch (error) {
        tbStripeCustomers.clear().draw();
        console.error('listCustomersDataToDatatable error:', error);

    } finally {
        $('#customerTotalBalance').text(fmt(customerTotalBalance));
    }
}


function jsViewCustomerDetail(data) {

    const fmt = val => showCurrencyFormat('USD', '', val);
    // Modal form
    $("#stripe_account_id").text(data.customer_account_id);
    $("#stripe_customer_city").text(data.customer_city);
    $("#stripe_customer_country").text(data.customer_country);
    $("#stripe_customer_line1").text(data.customer_line1);
    $("#stripe_customer_line2").text(data.customer_line2);
    $("#stripe_customer_postal_code").text(data.customer_postal_code);
    $("#stripe_customer_state").text(data.customer_state);
    $("#stripe_customer_balance").text(fmt(data.customer_balance));

    $("#stripe-customer-view-modal").modal("show");
}

// Get data from API
async function createCustomerPortalSession() {
    try {

        if (stripe_customer_id == "") {
            console.log(`stripe_customer_id is empty`);
            return false;
        }

        // You can dynamically build the URL using parameters
        const params = new URLSearchParams({
            case: 'createCustomerPortalSession',
            stripe_customer_id: stripe_customer_id,
        });

        const url = `stripe/stripe.controller.php?${params.toString()}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        // console.log(`CustomerPortalURL: ${data.url}`);
        window.open(data.url);

    } catch (error) {
        console.log(error);
        return false;
    }
}


// Create DataTable for Invoices
const tbStripeCustomerInvoices = $('.stripe-customer-invoice-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    // order: [[0, "desc"]],
    order: false,
});

$(".div-subscription-loading").show();
$(".div-subscription").hide();

// Get data from API
async function getStripeCustomerSubscriptionData() {

    // ── Helper: capitalize first letter ───────────────────────────────────────
    const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

    // ── Subscription status badge map ─────────────────────────────────────────
    const subStatusBadgeClass = {
        active: 'bg-success',
        past_due: 'bg-warning',
        paused: 'bg-warning',
        trialing: 'bg-warning',
        incomplete: 'bg-warning',
    };

    // ── Invoice status badge map ───────────────────────────────────────────────
    const invStatusBadgeClass = {
        paid: 'bg-success',
        uncollectible: 'bg-danger',
        void: 'bg-danger',
    };

    try {
        // ── Guard: both IDs must be present ───────────────────────────────────
        if (!stripe_customer_id || !stripe_subscription_id) {
            $('.div-subscription-loading, .div-subscription').remove();
            return;
        }

        const params = new URLSearchParams({
            case: 'getStripeCustomerSubscriptionData',
            stripe_customer_id: stripe_customer_id,
            stripe_subscription_id: stripe_subscription_id,
        });

        const response = await fetch(`stripe/stripe.controller.php?${params.toString()}`);

        if (!response.ok) {
            throw new Error(`HTTP error — status: ${response.status}`);
        }

        const data = await response.json();

        $('.div-subscription-loading').hide();
        $('.div-subscription').show();

        // ── Destructure subscription data ─────────────────────────────────────
        const { name: cusName, email: cusEmail } = data.customer;
        const {
            product_name, quantity, unit_amount,
            currency, interval_count, interval,
            next_billing, status: subStatus,
        } = data.subscription;

        // ── Subscription price line ───────────────────────────────────────────
        const subPrice = `${quantity} x ${showCurrencyFormat(currency, '', unit_amount)}`
            + ` -> (Each ${interval_count} ${capitalize(interval)})`;

        // ── Subscription status badge ─────────────────────────────────────────
        const subBadgeClass = subStatusBadgeClass[subStatus] ?? 'bg-danger';
        const subStatusBadge = `<span class="badge ${subBadgeClass} text-white">
                                    ${capitalize(subStatus)}
                                </span>`;

        // ── Render billing section — .text() for user-supplied strings ────────
        $('#subs_customer_name').text(cusName);
        $('#subs_customer_email').text(cusEmail);
        $('#sub_status').html(subStatusBadge);
        $('#sub_plan_name').text(product_name);
        $('#sub_unit_amount').html(subPrice);
        $('#sub_next_billing').text(next_billing);

        // ── Recent invoices ───────────────────────────────────────────────────
        if (data.invoices.length > 0) {

            const formattedData = data.invoices.map(item => {

                const isPaid = item.status === 'paid';
                const amountClass = isPaid ? 'fw-medium' : 'fw-medium text-warning';
                const invBadgeClass = invStatusBadgeClass[item.status] ?? 'bg-warning';

                return [
                    item.date,
                    `<span class="${amountClass}">${showCurrencyFormat(item.currency, '', item.amount)}</span>`,
                    `<span class="badge ${invBadgeClass} fw-medium text-white">${item.status.toUpperCase()}</span>`,
                    `<a  href="${item.hosted_invoice_url}"
                         target="_blank"
                         class="btn btn-sm btn-indigo fs-md">
                         <i class="ph-eye me-1"></i> ${translate.view_invoice}
                     </a>`,
                ];
            });

            tbStripeCustomerInvoices.clear().rows.add(formattedData).draw();

        } else {
            tbStripeCustomerInvoices.clear().draw();
        }

    } catch (error) {
        console.error('getStripeCustomerSubscriptionData error:', error);
    }
}

// List All data function
// async function listStripeInvoiceDataToDatatable() {

//     const res = await getInvoiceDataFromAPI(sess_ent_id);
//     // console.log(res);

//     let invoiceTotalDue = 0.00;
//     let invoiceTotalPaid = 0.00;

//     if (res.status == "success") {

//         if (res.data.length > 0) {
//             const formattedData = res.data.map(item => {

//                 // Payment Status
//                 let invoiceAmountDue = `<span class="fw-medium text-warning">${showCurrencyFormat(item.inv_currency, '', item.inv_amount_due)}</span>`;

//                 let btnViewInvoice = `<a href="${item.inv_hosted_url}" target="_blank" class="btn btn-sm btn-indigo fs-md"><i class="ph-eye me-1"></i> View Invoice</a>`;

//                 // Invoice Status
//                 let invoiceStatus = `<span class="badge bg-warning fw-medium text-white">${item.inv_status.toUpperCase()}</span>`;
//                 if (item.inv_status == "paid") invoiceStatus = `<span class="badge bg-success fw-medium text-white">${item.inv_status.toUpperCase()}</span>`;
//                 if (item.inv_status == "uncollectible" || item.inv_status == "void") invoiceStatus = `<span class="badge bg-danger fw-medium text-white">${item.inv_status.toUpperCase()}</span>`;

//                 invoiceTotalDue += parseFloat(item.inv_amount_due);
//                 invoiceTotalPaid += parseFloat(item.inv_amount_paid);

//                 return [
//                     // item.inv_id,
//                     // item.inv_stripe_invoice_id,
//                     item.inv_date_formatted,
//                     invoiceAmountDue,
//                     invoiceStatus,
//                     btnViewInvoice,
//                 ];
//             });

//             tbStripeCustomerInvoices.clear().rows.add(formattedData).draw();
//         } else {
//             tbStripeCustomerInvoices.clear().draw();
//         }

//     } else if (res.status == "warning") {
//         // swalInit.fire(res.message, ``, res.status);
//         tbStripeCustomerInvoices.clear().draw();

//     } else {
//         tbStripeCustomerInvoices.clear().draw();
//         console.log(res);
//     }

//     // Show total amount
//     // $("#invoiceTotalDue").text(showCurrencyFormat('USD', '', invoiceTotalDue));
//     // $("#invoiceTotalPaid").text(showCurrencyFormat('USD', '', invoiceTotalPaid));
// }

