var cart_data = {
    "products": {},
};
var w = window.innerWidth;
var h = window.innerHeight;

function loadCartData() {
    var savedCartData = localStorage.getItem('cart_data');
    if (savedCartData) {
        cart_data = JSON.parse(savedCartData);
    }
}

loadCartData();

function saveCartData() {
    removeZeroStockOrders(cart_data);
    localStorage.setItem('cart_data', JSON.stringify(cart_data));
}

// تابع برای اضافه کردن یا به روز کردن محصول
function addOrUpdateProduct(productId, orderKey, orderData) {
    var product = cart_data.products[productId.toString()];
    if (!product) {
        // اگر محصول موجود نیست، یک محصول جدید با تمام فیلدها ایجاد کنید
        product = {
            "product_id": productId,
            "image": document.getElementById("expandedImg").src,
            "name": document.querySelector("h1").innerText,
            "orders": {}
        };
        cart_data.products[productId.toString()] = product;
    }

    // اگر سفارش موجود است، فیلدهای آن را به روز کنید
    // اگر سفارش موجود نیست، یک سفارش جدید با تمام فیلدها ایجاد کنید
    var order = product.orders[orderKey] || {...emptyOrder};
    for (var field in orderData) {
        order[field] = orderData[field];
    }
    product.orders[orderKey] = order;
    removeZeroStockOrders(cart_data);
    saveCartData();
}

function getProductField(productId, orderKey, fieldName) {
    var product = cart_data.products[productId.toString()];
    console.log(productId + "-" + orderKey + "-" + fieldName)
    console.log(product)
    if (product) {
        var order = product.orders[orderKey];
        if (order && order.hasOwnProperty(fieldName)) {
            return order[fieldName];
        } else {
            console.log("سفارشی با این کلید در محصول وجود ندارد یا فیلد مورد نظر در سفارش وجود ندارد: " + orderKey + ", " + fieldName);
            return null;
        }
    } else {
        console.log("محصولی با این شناسه وجود ندارد: " + productId);
        return null;
    }
}

function save_cart(product_id, ORDERKEY, product_data) {


    addOrUpdateProduct(product_id, ORDERKEY, product_data)

}

function createCardMobile(product, order) {
    let discount = order.price * (order.discount / 100);
    let price = order.price - discount;
    const ORDERID = `${product.product_id}-${order.color_code}-${order.size}`;
    return `<div class="col col-12 mb-2" id="${ORDERID}">
                        <div class="row justify-content-center">

                            <div class="col col-12 col-md-10 row justify-content-between p-0 pe-2">
                                <div class="col col-5 col-md-3 cart-img-container">

                                    <img src="${product.image}" class="cart-img">
                                </div>
                                <div class="col col-7">
                                   <h5 class="main-title"><a href="${product.url}">${product.name}</a></h5>
                                    <div class="col col-12 px-0">
                                        <button class=" text-white opacity-75 mt-2 size-btn persian-number border-0 p-0 rounded-0 info-btn"
                                                style="background-color:#${order.color_code};">
                                            <span class="info-text ` + (order.color_name === "سفید" ? "text-dark" : "") + `">${order.color_name}</span>
                                        </button>

                                        <span class="text-muted p-1 info-text">رنگ</span>
                                        <br>
                                        <button class="bg-dark bg-opacity-75 text-white mt-2 size-btn persian-number border-0 p-0  rounded-0 info-btn">
                                            <span class="info-text">${order.size}</span>

                                        </button>
                                        <span class="text-muted p-1 info-text">سایز</span>
                                        <br>
                                        <button class="bg-light shadow-sm text-white mt-2 size-btn persian-number border-0 p-0 rounded-0 info-btn">
                                            <img src="https://cdn.viraoriginal.ir/static/icon/shield.svg" width="20">
                                        </button>
                                        <span class="text-muted p-1 info-text">گارانتی سلامت فیزیکی کالا</span>
                                    </div>
                                </div>


                            </div>

                            <div class="col col-12 row justify-content-around mt-2">
                                <div class="col text-end">
                                    <button onclick="decreaseCount('${product.product_id}','${order.color_code}','${order.size}')"
                                            class="btn btn-danger bg-gradient py-md-3 px-md-3 p-2 call-btn decrease-count` + (order.stock === 0 ? "disabled" : "") + `">
                                        <span class="decrease-count-trash  ` + (order.stock <= 1 ? "" : "d-none") + `"><img
                                                src="https://cdn.viraoriginal.ir/static/icon/trash.svg" width="20"></span>
                                        <span class="mx-1 decrease-count-min ` + (order.stock <= 1 ? "d-none" : "") + `">-</span>

                                    </button>
                                    <span class="mx-3 persian-number product-count">${order.stock}</span>
                                    <button onclick="increaseCount('${product.product_id}','${order.color_code}','${order.size}')"
                                            class="btn btn-danger bg-gradient py-md-3 px-md-3 p-2 call-btn increase-count ` + (order.stock === order.limit_stock ? "disabled" : "") + `">
                                        <span class="h4">+</span>
                                    </button>
                                </div>
                                <div class="col text-start">
                                    <span id="price" class="persian-number price fw-bold h2">${formatNumber(price)}</span>
                                    <span class="text-muted">تومان</span>
                                ` + (order.discount !== 0 ? `
                                <div class="opacity-75 text-danger small">
                                    <span  class="persian-number price fw-bold h6 small">${formatNumber(discount)}</span>
                                    <span class="small">تومان تخفیف</span>
                                </div></div>` : "") + `
                            </div>
                        </div>
<hr class="text-muted mt-2 mt-md-0">
                    </div>`
}

// تابعی برای ایجاد یک کارت HTML
function createCard(product, order) {
    let discount = order.price * (order.discount / 100);
    let price = order.price - discount;
    let ORDERID = `${product.product_id}-${order.color_code}-${order.size}`
    return ` <div class="col col-12" id="${ORDERID}">
                        <div class="row justify-content-center">
                            <div class="col col-3 px-0 pe-3">
                                <img src="${product.image}" class="img-fluid" alt="..." width="">
                            </div>
                            <div class="col col-9 col-md-6">
                                <div>
                                    <h5 class="main-title"><a href="${product.url}">${product.name}</a></h5>
                                </div>
                                <div class="">
                                    <button class=" text-white opacity-75 mt-2 size-btn persian-number border-1 border-opacity-100 border-light px-3 rounded-0"
                                            style="background-color:#${order.color_code};width: 80px">
                                            
                                        <span class="` + (order.color_name === "سفید" ? "text-dark" : "") + `">${order.color_name}</span>
                                    </button>
    
                                    <span class="text-muted p-1">رنگ</span>
                                    <br>
                                    <button class="bg-dark bg-opacity-75 text-white mt-2 size-btn persian-number border-0 px-4 rounded-0"
                                            style="width: 80px">
                                        ${order.size}
                                    </button>
                                    <span class="text-muted p-1">سایز</span>
                                    <br>
                                    <button class="bg-light shadow-sm text-white mt-2 size-btn persian-number border-0 px-4 rounded-0"
                                            style="width: 80px">
                                       <img src="https://cdn.viraoriginal.ir/static/icon/shield.svg" width="20">
                                    </button>
                                    <span class="text-muted p-1">گارانتی اصالت و سلامت فیزیکی کالا</span>
                                </div>
                                <div class="mt-5">
                                ` + (order.discount !== 0 ? `
                                <div class="opacity-75 text-danger small">
                                    <span  class="persian-number price fw-bold h6">${formatNumber(discount)}</span>
                                    <span class="small">تومان تخفیف</span>
                                </div>` : "") + `
                                    <span  class="persian-number price fw-bold h2">${formatNumber(price)}</span>
                                    <span>تومان</span>
                                </div>
                            </div>

                            <div class="col col-2  col-md-3 d-flex align-items-center justify-content-center ">
                                <div class="
                                text-center">
                                    <button onclick="decreaseCount('${product.product_id}','${order.color_code}','${order.size}')"
                                            class="btn btn-danger bg-gradient py-2 px-2 call-btn decrease-count ` + (order.stock === 0 ? "disabled" : "") + `">
                                        <span class="decrease-count-trash ` + (order.stock <= 1 ? "" : "d-none") + `"><img
                                                src="https://cdn.viraoriginal.ir/static/icon/trash.svg" width="20"></span>
                                        <span  class="mx-1 decrease-count-min ` + (order.stock <= 1 ? "d-none" : "") + `">-</span>

                                    </button>
                                    <span class="mx-3 persian-number product-count">${order.stock}</span>
                                    <button  onclick="increaseCount('${product.product_id}','${order.color_code}','${order.size}')"
                                            class="btn btn-danger bg-gradient py-2 px-2 call-btn increase-count ` + (order.stock === order.limit_stock ? "disabled" : "") + `">
                                        <span class="h4">+</span>
                                    </button>
                                </div>

                            </div>
                        </div>
<hr class="text-muted mt-3 p-0">
                    </div>
`;
}

// پیمایش دیکشنری و ایجاد کارت‌ها
function show_cart() {
    document.getElementById("cart_area").innerHTML = "";
    for (let productId in cart_data.products) {
        var product = cart_data.products[productId];
        for (var orderKey in product.orders) {
            var order = product.orders[orderKey];

            if (order.stock !== 0) {
                var card;
                if (w >= 991) {
                    card = createCard(product, order);

                } else {
                    card = createCardMobile(product, order);
                }
                document.getElementById("cart_area").innerHTML += card;
                show_sum();
            }
        }
    }
}

show_cart();
if (w >= 991) {


} else {
    document.getElementById("mobile-btn-area").appendChild(document.getElementById("order_btn"));
}

function show_sum() {
    let sum_prices = 0;
    let sum_discount = 0;
    let product_count = 0;
    for (var productId in cart_data.products) {
        var product = cart_data.products[productId];

        for (var orderKey in product.orders) {
            var order = product.orders[orderKey];

            if (order.stock !== 0) {
                let discount = order.price * (order.discount / 100);
                let price = order.price - discount;
                sum_prices += (price) * order.stock;
                sum_discount += discount * order.stock;
                product_count += order.stock;
            }
        }

    }
    document.getElementById("sum_price").innerText = formatNumber(sum_prices);
    document.getElementById("sum_price_mobile").innerText = formatNumber(sum_prices);
    document.getElementById("sum_products").innerText = formatNumber(product_count);
    document.getElementById("sum_discounts").innerText = formatNumber(sum_discount);
    if (sum_prices > 0) {
        document.getElementById("order_btn").classList.remove("disabled")
    } else {
        document.getElementById("order_btn").classList.add("disabled")

    }
}

function decreaseCount(product_id, color_code, size) {

    const ORDERKEY = color_code + size;

    var counter_product = getProductField(product_id, ORDERKEY, "stock")

    if (counter_product == null) {
        counter_product = 0;
    }
    if (counter_product >= 1) {
        counter_product--;
        var product_data = {
            "stock": counter_product,
        }

    }
    save_cart(product_id, ORDERKEY, product_data);
    console.log(cart_data);

    const ORDERID = `${product_id}-${color_code}-${size}`;
    let card = document.getElementById(ORDERID);
    card.querySelector(".product-count").innerHTML = counter_product;
    if (counter_product < 1) {
        card.querySelector(".decrease-count").classList.add("disabled");

    } else {
        card.querySelector(".decrease-count").classList.remove("disabled");
    }
    if (counter_product <= 1) {
        card.querySelector(".decrease-count-trash").classList.remove("d-none");
        card.querySelector(".decrease-count-min").classList.add("d-none");
    }
    card.querySelector(".increase-count").classList.remove("disabled");
    if (counter_product === 0) {
        card.classList.add("d-none");
    }
    show_sum();
}

function increaseCount(product_id, color_code, size) {
    const ORDERKEY = color_code + size;
    const ORDERID = `${product_id}-${color_code}-${size}`;
    let stock = getProductField(product_id, ORDERKEY, "stock");
    let stock_limit = getProductField(product_id, ORDERKEY, "limit_stock");

    let card = document.getElementById(ORDERID);

    if (stock < stock_limit) {
        stock++;

    }
    if (stock === stock_limit) {

        card.querySelector(".increase-count").classList.add("disabled");
    }
    if (stock > 1) {
        card.querySelector(".decrease-count-trash").classList.add("d-none");
        card.querySelector(".decrease-count-min").classList.remove("d-none");
    }
    card.querySelector(".decrease-count").classList.remove("disabled");


    var product_data = {
        "stock": stock,
    };
    save_cart(product_id, ORDERKEY, product_data);
    console.log(cart_data);
    card.querySelector(".product-count").innerHTML = stock;
    show_sum();
}

function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

function removeZeroStockOrders(cart_data) {
    for (let productId in cart_data.products) {
        for (let orderKey in cart_data.products[productId].orders) {
            if (cart_data.products[productId].orders[orderKey].stock === 0 || cart_data.products[productId].orders[orderKey].limit_stock === 0) {
                delete cart_data.products[productId].orders[orderKey];
                console.log('سفارش با موفقیت حذف شد.');
            }
        }
    }
}

async function cart_btn(self) {
    console.log(cart_data);
    self.innerText = "منتظر انتخاب آدرس";
    let res = await sendCart_api();
    if (res.status === "success") {
        self.innerText = "نهایی کردن سفارش";

        clearDatabase(cart_data);
        saveCartData();
        show_cart();
        window.location.href = res.cart_url;

    }

}

function clearDatabase(cart_data) {
    for (let productId in cart_data.products) {
        delete cart_data.products[productId];
    }
    console.log('دیتابیس با موفقیت پاک شد.');
}

async function sendCart_api() {

    let csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    let _data = "initial";
    try {
        const response = await fetch('/buy/api/save-cart', {
            method: 'POST', headers: {
                'Content-Type': 'application/json', 'X-CSRFToken': csrfToken
                // Include other headers as needed
            }, body: JSON.stringify(cart_data),
        });
        // تبدیل پاسخ به JSON
        _data = await response.json();
    } catch (error) {
        let alert_text = "خطای مهلکی در ارتباط با مرکز رخ داده است، اینترنت خود را بررسی یا با توسعه دهنده تماس بگیرید.";
        // show_alert(alert_text, "alert-danger");
        console.log(alert_text);
        _data = "fail";
    }
    return _data;
}

function updateDatabase(current_cart_data, new_cart_data) {

    for (let productId in new_cart_data.products) {
        if (!current_cart_data.products[productId]) {
            current_cart_data.products[productId] = new_cart_data.products[productId];
        } else {
            for (let orderKey in new_cart_data.products[productId].orders) {
                if (!current_cart_data.products[productId].orders[orderKey]) {
                    current_cart_data.products[productId].orders[orderKey] = new_cart_data.products[productId].orders[orderKey];
                    console.log('سفارش با موفقیت به دیتابیس اضافه شد.');
                } else {
                    console.log('سفارش در حال حاضر در دیتابیس وجود دارد.');
                }
            }
        }
    }
    saveCartData();
    show_cart();
    var url = window.location.href.split('?')[0];
    window.history.pushState({}, document.title, url);
}


