var cart_data = {
    "products": {
        // "PRODUCT-ID": {
        //     "product_id": null,
        //     "image": null,
        //     "name": null,
        //     "orders": {
        //         "COLORCODE-SIZE": {
        //             "color_code": null,
        //             "color_name": null,
        //             "stock": 1,
        //             "price": null,
        //             "size": null,
        //             "discount": null
        //         }
        //
        //     }
        //
        // },
    }
};
var selected_data = {
    "product_id": first_init.product_id,
    "color_code": first_init.color_code,
    "color_name": first_init.color_name,
    "size": first_init.size,
    "stock": 0,
    "stock_limit": first_init.stock
}
loadCartData();

const ORDERKEY = selected_data["color_code"] + selected_data["size"]
let temp_stock = getProductField(selected_data["product_id"], ORDERKEY, 'stock');
if (temp_stock !== null) {
    selected_data["stock"] = temp_stock
}
cart_btn_view();

// ذخیره سازی داده ها در localStorage
function saveCartData() {
    localStorage.setItem('cart_data', JSON.stringify(cart_data));
}

// بازیابی داده ها از localStorage
function loadCartData() {
    var savedCartData = localStorage.getItem('cart_data');
    if (savedCartData) {
        cart_data = JSON.parse(savedCartData);
    }
}

// فراخوانی تابع برای بازیابی داده ها
// loadCartData();
function openModal(index) {
    currentIndex = index;
    changeMedia(0);
    var myModal = new bootstrap.Modal(document.getElementById('myModal'));
    myModal.show();

}

modalImage.addEventListener('mousedown', function (e) {
    startPos = e.clientX;
    isDragging = true;
});

modalImage.addEventListener('mousemove', function (e) {
    if (isDragging) {
        if (startPos > e.clientX) {
            changeMedia(1);
        } else {
            changeMedia(-1);
        }
        isDragging = false;
    }
});

modalImage.addEventListener('mouseup', function (e) {
    isDragging = false;
});

modalImage.addEventListener('touchstart', function (e) {
    startPos = e.touches[0].clientX;
    isDragging = true;
});

modalImage.addEventListener('touchmove', function (e) {
    if (isDragging) {
        endPos = e.touches[0].clientX;
        if (startPos > endPos) {
            changeMedia(1);
        } else {
            changeMedia(-1);
        }
        isDragging = false;
    }
});

modalImage.addEventListener('touchend', function (e) {
    isDragging = false;
});

function select_color(self, color_name, color_code, product_id) {
    reset_counter();
    close_alert();
    reset_cart_button();
    selected_data["color_code"] = color_code;
    selected_data["color_name"] = color_name;
    selected_data["size"] = null;

    const color_data = variants["colors"];
    var buttons = document.getElementsByClassName('color-btn-active');
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].classList.remove('color-btn-active');
    }

    self.classList.add('color-btn-active')
    document.getElementById("selected-color-text").innerText = color_name;


    let size_content = "";
    if (variants.colors.hasOwnProperty(color_code)) {
        let color = variants.colors[color_code];
        for (let size in color.sizes) {
            size_content += `<button class="bg-white mx-2 mx-md-1 border-opacity-25 border-secondary rounded-0 px-3 py-2 size-btn persian-number ${first_initial.size == size ? 'selected' : ''}"
            onclick="select_size(this,'${size}','${variants.product_id}')">
            ${size}
        </button>`;
        }
    }
    document.getElementById("size-area").innerHTML = size_content;

}

function select_size(self, size, product_id) {
    reset_counter()
    close_alert();
    selected_data["size"] = size;

    selected_data["stock_limit"] = variants["colors"][selected_data["color_code"]]["sizes"][size]["stock"];

    const ORDERKEY = selected_data["color_code"] + selected_data["size"]
    let temp_stock = getProductField(selected_data["product_id"], ORDERKEY, "stock")
    selected_data["stock"] = temp_stock;
    if (temp_stock == null) {
        selected_data["stock"] = 0;
    }

    document.getElementById("selected-size-text").innerText = size;
    // document.getElementById("price").innerText = cart_data["price"];

    for (let size_btn of document.getElementsByClassName("size-btn")) {
        size_btn.classList.remove("selected");
    }
    self.classList.add("selected");

    let discount = variants["colors"][selected_data["color_code"]]["sizes"][size]["discount"];
    let price = variants["colors"][selected_data["color_code"]]["sizes"][size]["price"];

    if (discount !== 0) {
        document.getElementById("discount_area").classList.remove("d-none")
        document.getElementById("discount_percent").innerText = "٪" + formatNumber(discount);
        document.getElementById("price").innerText = formatNumber(price - (price * (discount / 100)));
        document.getElementById("old_price").innerText = formatNumber(price);
    } else {
        document.getElementById("price").innerText = formatNumber(price);

        document.getElementById("discount_area").classList.add("d-none")
    }

    cart_btn_view()
}


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


var is_initial = false

function first_initial(data, variants) {
    if (is_initial === false) {
        cart_data["products"]["product_id"] = variants[data["color_name"]]["product"];
        cart_data["size"] = data["size"];
        cart_data["color_name"] = data["color_name"];
        cart_data["color_code"] = data["color_code"];
        cart_data["price"] = data["price"];
        cart_data["stock_limit"] = data["stock"];
        cart_data["stock"] = counter_product;
        is_initial = true;
    }
}

function show_alert(text, mode = "alert-warning") {
    close_alert();
    var alert = document.getElementById("cart-alert")
    alert.classList.add(mode)
    alert.classList.remove("d-none")
    alert.innerText = text;
    document.getElementById("cart-alert").innerHTML += `<button type="button" class="btn-close"  onclick="close_alert()"></button>`
}

function close_alert() {
    var alert = document.getElementById("cart-alert")
    alert.classList.remove("alert-danger");
    alert.classList.remove("alert-warning");
    alert.classList.remove("alert-success");
    alert.classList.remove("alert-info");
    alert.classList.add("d-none")
    alert.innerText = "";
}


function add_cart(self, variants) {
    if (selected_data["size"] == null) {
        show_alert("لطفا سایز مناسب خود را انتخاب کنید.");
    } else {
        reset_counter()
        increaseCount();
    }
}

function increaseCount() {
    let is_limit = selected_data["stock"] < selected_data["stock_limit"];
    console.log(selected_data["stock"] + " - " + selected_data["stock_limit"])

    if (is_limit) {
        selected_data['stock']++;
    }

    save_cart();
    cart_btn_view();
}


function cart_btn_view() {
    // = selected_data["stock"];
    let is_limit = selected_data["stock"] >= selected_data["stock_limit"]
    const ORDERKEY = selected_data["color_code"] + selected_data["size"]

    let stock = getProductField(selected_data["product_id"], ORDERKEY, "stock")


    if (is_limit) {
        document.getElementById("increase-count").classList.add("disabled");
    } else {
        document.getElementById("increase-count").classList.remove("disabled");
    }

    if (stock === 0 || stock == null) {
        document.getElementById("cart-btn").classList.remove("d-none");
        document.getElementById("product-count-container").classList.add("d-none")

    } else if (stock === 1) {
        document.getElementById("cart-btn").classList.add("d-none");
        document.getElementById("product-count-container").classList.remove("d-none")
        document.getElementById("decrease-count-trash").classList.remove("d-none");
        document.getElementById("decrease-count-min").classList.add("d-none");

    } else {
        document.getElementById("cart-btn").classList.add("d-none");
        document.getElementById("product-count-container").classList.remove("d-none")
        document.getElementById("decrease-count-trash").classList.add("d-none");
        document.getElementById("decrease-count-min").classList.remove("d-none");

    }
    document.getElementById('product-count').innerText = stock;
    document.getElementById('selected-count-text').innerText = stock;
    if (selected_data["stock_limit"] === 0) {
        document.querySelector("#cart-btn span").innerHTML = "اتمام موجودی";
        document.querySelector("#cart-btn").classList.add("disabled");
        document.querySelector("#cart-btn").classList.remove("d-none");
        document.getElementById("product-count-container").classList.add("d-none");
    } else {
        // document.getElementById("product-count-container").classList.add("d-none");

        document.querySelector("#cart-btn span").innerHTML = "افزودن به سبد خرید";
        document.querySelector("#cart-btn").classList.remove("disabled");

    }
}

function decreaseCount() {
    const ORDERKEY = selected_data["color_code"] + selected_data["size"]
    var counter_product = getProductField(selected_data["product_id"], ORDERKEY, "stock")
    if (counter_product == null) {
        counter_product = 0;
    }
    if (counter_product >= 1) {
        counter_product--;
        selected_data["stock"] = counter_product;

    }


    cart_data["stock"] = counter_product;

    save_cart();

    if (counter_product < 1) {
        document.getElementById("decrease-count").classList.add("disabled");

        reset_counter();
        reset_cart_button();
    } else {
        document.getElementById("decrease-count").classList.remove("disabled");

    }
    cart_btn_view();
}

function reset_counter() {
    document.getElementById("increase-count").classList.remove("disabled");
    document.getElementById("decrease-count").classList.remove("disabled");
    counter_product = 0;
    document.getElementById('product-count').innerText = counter_product;
    document.getElementById('selected-count-text').innerText = counter_product;
}

function reset_cart_button() {
    document.getElementById("product-count-container").classList.add("d-none")
    document.getElementById("cart-btn").classList.remove("d-none")
}

function disable_call_button() {
    var call_btn = document.getElementsByClassName("call-btn")
    for (let btn of call_btn) {
        btn.classList.add("disabled")
    }
}

function active_call_button() {
    var call_btn = document.getElementsByClassName("call-btn")
    for (let btn of call_btn) {
        btn.classList.remove("disabled")
    }
}

function save_cart() {


    // disable_call_button();
    let product_data = {
        "color_code": selected_data["color_code"],
        "color_name": selected_data["color_name"],
        "stock": selected_data["stock"],
        "limit_stock": selected_data["stock_limit"],
        "size": selected_data["size"],
        "price": variants["colors"][selected_data["color_code"]]["sizes"][selected_data["size"]]["price"],
        "discount": variants["colors"][selected_data["color_code"]]["sizes"][selected_data["size"]]["discount"]
    }
    const ORDERKEY = selected_data["color_code"] + selected_data["size"]
    addOrUpdateProduct(selected_data["product_id"], ORDERKEY, product_data)
    removeZeroStockOrders(cart_data);
    saveCartData();

}


// تابع برای اضافه کردن یا به روز کردن محصول
// تعریف یک سفارش خالی با تمام فیلدها
var emptyOrder = {
    "color_code": null,
    "color_name": null,
    "stock": 1,
    "limit_stock": 10,
    "price": null,
    "size": null,
    "discount": null
};

// تابع برای اضافه کردن یا به روز کردن محصول
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(".main-title").innerText,
            "url": document.querySelector('link[rel="canonical"]').href,
            "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;

    saveCartData();
}

function getProductField(productId, orderKey, fieldName) {
    var product = cart_data.products[productId.toString()];
    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 removeOrder(cart_data, productId, orderKey) {
    if (cart_data.products[productId] && cart_data.products[productId].orders[orderKey]) {
        delete cart_data.products[productId].orders[orderKey];
        console.log('سفارش با موفقیت حذف شد.');
    } else {
        console.log('سفارش مورد نظر یافت نشد.');
    }
}

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) {
                delete cart_data.products[productId].orders[orderKey];
                console.log('سفارش با موفقیت حذف شد.');
            }
        }
    }
}
