var ADDRESS = null;
var DELIVERY = null;

async function pay_button(self, order_id) {
    self.innerText = "صبر کنید..."
    self.classList.add("disabled");
    let res = await pay_request_api(order_id, ADDRESS, DELIVERY)
    if (res.status === "pay") {
        setTimeout(function () {
            window.location.href = "/payment/request/";
        }, 1);
    } else if (res.status === "no-address") {
        self.innerText = "پرداخت امن"
        self.classList.remove("disabled");
        console.log(res.addresses)
        address_area = `<div class=""><h5 class="mb-2">آدرس‌ها</h5>
`;
        let aindex = 0;
        res.addresses.forEach(address => {
            address_area += `
            <div class="bg-secondary rounded-2 bg-opacity-10 p-2 row mt-2" onclick="selectAddress(this,'${address.id}','${address.province}','${address.city}','${address.post_code}')">
                <div class="col col-auto">
                    <input class="form-check-input h3" type="radio" name="flexRadioDefault" id="flexRadioDefault${address.id}" ` + (aindex === 0 ? "checked0" : "") + `>
                </div>
                <div class="col col-auto">
                  <span > ${address.province}</span>
                  <span class="text-muted">.</span>
                  <span > ${address.city}</span>
                  <span class="text-muted d-block persian-number">${address.post_code}</span>
              </div>
            </div>
            `;
            aindex++;
        });
        address_area += `</div>
        <a class="col col-12 btn btn-light rounded-0 mt-3" href="/profile/address/?next=${res.url}">افزودن آدرس جدید</a>`
        delivery_area = `<hr><div class=""><h5 class="mb-2">شیوه ارسال</h5>`
        let dindex = 0;
        res.deliveries.forEach(delivery => {

            delivery_area += `
            <div class="bg-secondary rounded-2 bg-opacity-10 p-2 row mt-2" onclick="selectDelivery(this,'${delivery.id}','${delivery.price}')">
                <div class="col col-2">
                    <input class="form-check-input h3" type="radio" name="flexRadioDefaultd" id="flexRadioDefaultd${delivery.id}" ` + (dindex === 0 ? "checked0" : "") + `>
                </div>
                <div class="col col-10">
                  <span class="persian-number d-block">${delivery.name}<span class="text-muted small mx-2">${delivery.detail}</span></span>
                  
                  <span class="persian-number text-muted small">هزینه ارسال: ${formatNumber(delivery.price)} تومان</span>
              </div>
        </div>
            `;
            dindex++;
        });
        delivery_area += `</div>`


        show_modal(address_area + delivery_area, "انتخاب آدرس");
    }else {
        self.innerText = "تلاش دوباره"
        self.classList.remove("disabled");
    }
}

async function pay_request_api(order_id, address = null, delivery = null) {
    PAY_DATA = {
        "order_id": order_id,
        "address": address,
        "delivery": delivery
    }
    let csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    let _data = "initial";
    try {
        const response = await fetch('/buy/api/payment', {
            method: 'POST', headers: {
                'Content-Type': 'application/json', 'X-CSRFToken': csrfToken
                // Include other headers as needed
            }, body: JSON.stringify(PAY_DATA),
        });
        // تبدیل پاسخ به JSON

        _data = await response.json();
        console.log(_data)
    } catch (error) {
        let alert_text = "خطای مهلکی در ارتباط با مرکز رخ داده است، اینترنت خود را بررسی یا با توسعه دهنده تماس بگیرید.";
        console.log(alert_text)
        _data = "fail";
    }
    return _data;
}

function selectAddress(self, address_id, province, city, post_code) {
    self.querySelector("input").checked = true;
    ADDRESS = address_id;
    document.getElementById("address_area").innerHTML = `
    <p class="text-wrap overflow-scroll p-0 m-1 small">${province} . ${city}</p>
    <p class=" persian-number p-0 m-1 small">${post_code}</p>`;

    if (ADDRESS && DELIVERY) {
        close_modal();
    }
}

function selectDelivery(self, delivery_id, price) {
    self.querySelector("input").checked = true;
    let total_price = formatNumber(parseInt(product_price) + parseInt(price));
    document.getElementById("sum_price_mobile").innerText = total_price;
    document.getElementById("total_price").innerText = total_price;
    document.getElementById("delivery_price").innerText = formatNumber(price);
    DELIVERY = delivery_id;

    if (ADDRESS && DELIVERY) {
        close_modal();
    }
}