﻿﻿﻿var HataDurum = false
var isStarted
var logs = ['Loglar']
var log = ''

var kontrol

var isRefreshed = false
var SekmeKapatildi = false
var PcName = ''

var AmazonUrl = ''
var AbeUrl = ''
var UrunID = ''
var MagazaAdi = ''
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.Link) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.UygulamaBaslatildi) {
        SekmeBilgileriGonder()
    }
    if (message.PageReload) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.SekmeBulunamadi) {
        var text = "Extension'un çalıştığı sekme açık sekmeler arasında bulunamadı!"
        HataKontrolYap(1, text)
        console.log('Hata var:' + text)
    }
})

var linkKontrolCount = 0
var urunKontrolCount = 0

chrome.storage.onChanged.addListener(function (changes, namespace) {
    var storageChange

    for (key in changes) {
        if (key == 'KontrolUrl1' || key == 'KontrolUrl2') {
            storageChange = changes[key]
            if (storageChange.newValue.length > 0) {
                linkKontrolCount++
                //alert(linkKontrolCount);
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        //SiparisTamamla()
                    }, 2000)
                }
            }
        } else if (key == 'AmzUrunList' || key == 'AbeUrunList') {
            storageChange = changes[key]
            if (storageChange.newValue != undefined && storageChange.newValue != null) {
                urunKontrolCount++
                if (urunKontrolCount == 2) {
                    setTimeout(function () {
                        console.log(' UrunListeleriniGonder(); onchanged çağrıldı')
                        UrunListeleriniGonder()
                    }, 2000)
                }
            }
        } else {
        }
    }
})

$(document).ready(function () {
    var host = window.location.host
    var href = window.location.href
    chrome.storage.sync.get(
            [
                'isStarted',
                'UrunGetirildi',
                'Durum',
                'KontrolUrl1',
                'KontrolUrl1Hata',
                'KontrolUrl2Hata',
                'KontrolUrl2',
                'UrunFiyat',
                'AmzPageCount',
                'AbePageCount',
                'AmazonUrl',
                'AbeUrl',
                'UrunFiyat',
                'MagazaAdi',
                'RequestTime',
            ],
            function (item) {
                setTimeout(async function () {
                    if (item.isStarted == true) {
                        MagazaAdi = item.MagazaAdi
                        AmazonUrl = item.AmazonUrl
                        console.log(item.Durum)
                        AbeUrl = item.AbeUrl
                        if (item.UrunGetirildi == false) {
                            chrome.storage.sync.set(
                                    {
                                        UrunGetirildi: true,
                                        Durum: 'TypeKontrol',
                                        KontrolUrl1: '',
                                        KontrolUrl2: '',
                                    },
                                    function () {
                                        console.log('TypeKontrol1')
                                        BirinciLinkKontrol()
                                    }
                            )
                            SekmeBilgileriGonder()
                        } else {
                            console.log(item.Durum + 'TypeKontrol2')
                            //HataKontrolYap(250);
                            if (item.Durum == 'TypeKontrol') {
                                console.log('TypeKontrol3')
                                BirinciLinkKontrol()
                            }
                        }
                    }
                }, parseInt(item.RequestTime) * 1000)
            }
    )
})

function dialogModal(message, background = 'limegreen') {
    let loader = document.createElement('div')
    $(loader).addClass('extDialog')
    $(loader).css('position', 'fixed')
    $(loader).css('min-height', '200px')
    $(loader).css('height', 'auto')
    $(loader).css('width', '200px')
    $(loader).css('background', background)
    $(loader).css('color', '#fff')
    $(loader).css('overflow-wrap', 'anywhere')
    $(loader).css('border-radius', '50%')
    $(loader).css('font-weight', 'bold')
    $(loader).css('bottom', '10px')
    $(loader).css('right', '0')
    $(loader).css('z-index', '9999')
    $(loader).css('display', 'flex')
    $(loader).css('justify-content', 'center')
    $(loader).css('align-items', 'center')

    $(loader).html(message)
    document.body.append(loader)
    return loader
}
let loader2 = ''
function asinDialogModal(message, background = 'limegreen') {
    let loader = document.createElement('div')
    $(loader).addClass('extDialog2')
    $(loader).css('position', 'fixed')
    $(loader).css('min-height', '200px')
    $(loader).css('max-height', '1000px')
    $(loader).css('height', 'auto')
    $(loader).css('width', '250px')
    $(loader).css('background', background)
    $(loader).css('color', '#fff')
    $(loader).css('overflow-wrap', 'anywhere')
    $(loader).css('font-weight', 'bold')
    $(loader).css('top', '0px')
    $(loader).css('right', '250px')
    $(loader).css('z-index', '999999999')
    $(loader).css('display', 'flex')
    $(loader).css('justify-content', 'center')
    $(loader).css('overflow-y', 'scroll')

    $(loader).html(message)
    document.body.append(loader)
    return loader
}

async function SiparisTamamla(dataArray, lastIndex) {
    if (dataArray.length > 0) {
        chrome.storage.sync.get(
                ["MagazaAdi", "UrunID", "tracking", "kargoFirma", "ApiUrl", "LastIndex"],
                function (item) {
                    // MTip: Mağaza Tip (Amazon (0), Abe (1))
                    if (item.LastIndex == 1) {
                        localStorage.clear();
                        localStorage.removeItem("AsinList");
                    }

                    // ✅ ASIN ve Fiyat arraylerini ayır
                    const AsinArray = dataArray.map((x) => x.asin);
                    const FiyatArray = dataArray.map((x) => x.price);
                    const ConditionArray = dataArray.map((x) => x.condition);
                    var datam = {
                        AsinArray: AsinArray, // ✅ ["0999867180", "1649377150"]
                        FiyatArray: FiyatArray, // ✅ [6.41, 9.99]
                        ConditionArray: ConditionArray,
                        magazaDeger: item.MagazaAdi,
                        tip: "newAsinEnd",
                    };
                    $.ajax({
                        type: "post",
                        url: item.ApiUrl + "ExtensionWebServis/ajaxCall",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                        },
                        cache: false,
                        dataType: "json",
                        data: datam,
                        success: function (cevap) {
                            if (cevap.hata == 0 || cevap.hata === "0") {
                                console.log(cevap.hatatext);
                                chrome.storage.sync.set({LastIndex: lastIndex + 1}, function () {});
                            } else {
                                if (cevap.result) {
                                    console.log(cevap.result);
                                    console.log("Asin bilgileri gönderildi");
                                    // localStorage'dan eski kayıtları al
                                    let existingAsins = JSON.parse(localStorage.getItem("AsinList") || "[]");
                                    // Yeni gelen asin'leri al
                                    let newAsins = cevap.result.map((item) => item.asin);
                                    // Eski + yeni asin'leri birleştir (tekrarları kaldır)
                                    let combinedAsins = [...new Set([...existingAsins, ...newAsins])];
                                    // Yeni veriyi localStorage'a kaydet
                                    localStorage.setItem("AsinList", JSON.stringify(combinedAsins));
                                    // 🔽 loader'a TÜM ASIN’leri yazdır
                                    let html = `<div style="font-family: Arial, sans-serif; font-size: 20px; line-height: 1.6;">`;
                                    html += `<b>Toplam ${combinedAsins.length} ASIN Kaydedildi:</b><br>`;
                                    combinedAsins.forEach((asin, index) => {
                                        html += `<div style="padding: 4px 0; border-bottom: 1px solid #ddd;">
                    <a target="_blank" href="https://www.ebay.com/sch/i.html?_nkw=${asin}&_sacat=267&_from=R40&rt=nc&LH_ItemCondition=2750">
                      ${index + 1}. 📦 ${asin}
                    </a>
                  </div>`;
                                    });
                                    html += `</div>`;
                                    $(loader2).html(html);
                                    // LastIndex güncelle
                                    chrome.storage.sync.set({LastIndex: lastIndex + 1}, function () {});
                                } else {
                                    console.log("else girdi");
                                    $(loader).html("Hata oluştu.");
                                }
                            }
                        },
                        error: function (req, textStatus, errorThrown) {
                            console.log("textStatus:", textStatus);
                            console.log("errorThrown:", errorThrown);
                            console.log("responseText:", req.responseText);
                        },
                    });
                }
        );
    } else {
        console.log("Bot engellendi. 15 dk bekleniyor...");
        const loader = dialogModal("Bot engellendi. 15 dk bekleniyor...", "red");
        await new Promise((resolve) => setTimeout(resolve, 15 * 60 * 1000));
        console.log("Devam ediliyor...");
        $(loader).remove();
    }
}

function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms))
}

var RunCount = 0
const getInfoTab = async (shipID) => {
    return await axios
            .get(
                    'https://sellercentral.amazon.com/fba/inbound-shipment/summary/shipment-info/' + shipID,
                    {},
                    {
                        headers: {
                            cookie: document.cookie,
                        },
                    }
            )
            .then((response) => {
                if (response.data && response.data.carrierShipmentInfo.totalCostEstimate) {
                    return response.data.carrierShipmentInfo.totalCostEstimate.amount ?? undefined
                }
            })
            .catch((e) => {
            })
}

let shipingData = []
var count = 0
async function BirinciLinkKontrol() {
    chrome.storage.sync.get(['LastIndex'], async function (item) {
        const href = window.location.href
        const loader = dialogModal(`Loading...`)
        loader2 = asinDialogModal(`Yükleniyor...`)
        let pagenation = 1

        const paginationNext = document.querySelector('a.pagination__next')
        if (paginationNext) {
            const lastPageLink = paginationNext.previousElementSibling
            if (lastPageLink && !isNaN(parseInt(lastPageLink.textContent))) {
                pagenation = parseInt(lastPageLink.textContent)
            }
        }

        const isbnList = []
        let totalFetched = 0

        // 📘 ISBN alma fonksiyonu
        function extractAsinAndPriceFromPageHTML(html) {
            const parser = new DOMParser()
            const doc = parser.parseFromString(html, 'text/html')

            const subtitle = doc.querySelector('.x-item-title__subTitle')
            const description = doc.querySelector('.x-item-description-child')
            const isbnBlocks = doc.querySelectorAll('[data-testid="ux-labels-values"]')

            // ✅ PRICE (x-price-primary -> ux-textspans)
            let price = null
            const priceText = doc.querySelector('.x-price-primary .ux-textspans')?.textContent?.trim()
            if (priceText) {
                price = priceText.replace('US', '').trim()
                price = price.replace('$', '').trim()

                // ✅ burada ekle (string -> number)
                const n = Number(price.replace(/,/g, ''))
                price = Number.isNaN(n) ? null : n
            }

            let condition = null
            const conditionText =
                    doc.querySelector('.x-item-condition-text .ux-textspans')?.textContent?.trim()
            if (conditionText) {
                condition = conditionText
            }

            const textSources = [
                subtitle?.textContent || '',
                description?.textContent || '',
                doc.body.textContent || '',
            ]

            for (const text of textSources) {
                const parts = text.split('|').map((p) => p.trim())
                for (const part of parts) {
                    const isbn10Match = part.match(/(?:ISBN-10)[:\s]*([0-9]{9}[0-9Xx])/i)
                    if (isbn10Match)
                        return {asin: isbn10Match[1], price, condition}
                    const isbn13Match = part.match(/(?:ISBN-13)[:\s]*([0-9]{13})\b/i)
                    if (isbn13Match)
                        return {asin: isbn13Match[1], price, condition}
                    const isbnMatch = part.match(/(?:ISBN)[:\s]*([A-Z0-9]{8,10})/i)
                    if (isbnMatch)
                        return {asin: isbnMatch[1], price, condition}
                    const asinMatch = part.match(/(?:ASIN)[:\s]*([A-Z0-9]{8,10})/i)
                    if (asinMatch)
                        return {asin: asinMatch[1], price, condition}
                }
            }

            for (const block of isbnBlocks) {
                const label = block.querySelector('.ux-labels-values__labels .ux-textspans')?.textContent?.trim()
                const value = block.querySelector('.ux-labels-values__values .ux-textspans')?.textContent?.trim()
                if (label && value) {
                    if (/ISBN-10/i.test(label) && /^\d{9}[\dXx]$/.test(value))
                        return {asin: value, price, condition}
                    if (/ISBN/i.test(label) && /^[A-Z0-9]{8,10}$/i.test(value))
                        return {asin: value, price, condition}
                    if (/ASIN/i.test(label) && /^[A-Z0-9]{8,10}$/i.test(value))
                        return {asin: value, price, condition}
                }
            }
            return null
        }

        let lIndex = 1

        if (item.LastIndex > 1) {
            lIndex = item.LastIndex
        }

        for (let index = lIndex; index <= pagenation; index++) {
            $(loader).html(`Sayfa ${index} / ${pagenation} taranıyor...`)
            const url = `${href}&_pgn=${index}`
            console.log(url)

            await axios.get(url).then(async (response) => {
                const html = $.parseHTML(response.data)
                let itemLinks = $('a.su-link', html)
                        .map((i, el) => el.href)
                        .get()

                if (itemLinks.length == 0) {
                    itemLinks = $('div.su-card-container__header a.s-card__link', html)
                            .map((i, el) => el.href)
                            .get()
                }

                if (itemLinks.length === 0) {
                    itemLinks = $('article.str-item-card.StoreFrontItemCard a[href]', html)
                            .map((i, el) => el.href)
                            .get();
                }
                console.log("Sayfadaki Url Sayısı:", itemLinks.length)
                let pageIsbnList = []

                for (let i = 0; i < itemLinks.length; i++) {
                    const link = itemLinks[i]
                    try {
                        const response = await axios.get(link)
                        const pageHTML = response.data
                        const item = extractAsinAndPriceFromPageHTML(pageHTML)

                        console.log(`Sayfa ${index} - Ürün ${i + 1}: asin+price+condition:`, item)

                        if (item)
                            pageIsbnList.push(item)

                        await new Promise((r) => setTimeout(r, 5000))
                    } catch (err) {
                        console.error('Detay sayfa hatası:', link, err)
                    }
                }

                // ✅ sadece bu sayfaya ait ISBN'ler gönderilir
                await SiparisTamamla(pageIsbnList, index)
            })
        }
    })
}

function getSayfa(adres) {
    var strText = null
    $.ajax({
        url: adres,
        async: false,
        dataType: 'text',
        success: function (text) {
            strText = text
        },
        error: function (http, message, exc) {
            strText = null
        },
    })

    return strText
}

function QueryStringOku(name, url) {
    if (!url)
        url = window.location.href
    name = name.replace(/[\[\]]/g, '\\$&')
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url)
    if (!results)
        return null
    if (!results[2])
        return ''
    return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

function SekmeKapat(sure) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            SekmeKapat: true,
        })
    }, sure * 1000)
}

function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({
        AktifSekmeBilgileri: true,
    })
}

function waitForElement(elementPath, callBack) {
    window.setTimeout(function () {
        if ($(elementPath).text().length > 0) {
            callBack(elementPath, $(elementPath))
        } else {
            waitForElement(elementPath, callBack)
        }
    }, 100)
}

function ClearData() {
    AppLog(log)
    AppLogGonder()
    sessionStorage.clear()
    chrome.runtime.sendMessage({
        LinkHata: 'LinkteError',
        YeniSekme: true,
    })
    clearTimeout(HataKontrol)
}

function AppLogGonder() {
    chrome.runtime.sendMessage({
        HataDurum: HataDurum,
        isStarted: isStarted,
        AppLog: logs,
    })
}

function AppLog(log) {
    var time = new Date().toLocaleString()
    var test = log + ' - ' + time
    var loglar = logs
    if (loglar.length < 6) {
        loglar.push(test)
    } else {
        loglar.splice(0, 1)
        loglar.push(test)
    }
    logs = loglar
    localStorage.setItem('LocalStorageAppLog', JSON.stringify(logs))
    chrome.storage.sync.set(
            {
                AppLog: test,
            },
            function () {}
    )
}

function SayfaGit(adres, time) {
    setTimeout(function () {
        window.location.href = adres
    }, parseInt(time) * 1000)
}

function BellekSil() {
    chrome.storage.sync.remove(['isStarted', 'Durum'], function () {})
}

var HataKontrol

function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(function () {
        //location.reload();
        chrome.storage.sync.get(
                ['isStarted', 'PcName', 'UygulamaAdi', 'Durum', 'UrunID', 'MagazaAdi'],
                function (item) {
                    var aciklama = ''
                    if (msj2 == undefined) {
                        aciklama = ''
                    } else {
                        aciklama = msj2
                    }
                    var msj = `Bilgisayar: ${item.PcName} Mağaza Adı: ${item.MagazaAdi}  Durum: ${item.Durum} iken extension çalışmayı durdurdu! ${aciklama}`
                    var datam = {
                        ID: item.UrunID,
                        tip: 'newOrderBreak',
                        mesaj: msj,
                    }
                    console.log(msj)

                    $.ajax({
                        type: 'post',
                        url: 'https://www.andromedaworkspace.com/Extension/ajaxCall',
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                        },
                        cache: false,
                        dataType: 'json',
                        data: datam,
                        success: function (cevap) {
                            if (cevap.hata == 0) {
                                console.log('Hata: Hata Bilgisi Gönderilemedi!')
                            } else {
                                if (cevap.result) {
                                    console.log(cevap.result)
                                    setTimeout(function () {}, 3000)
                                }
                            }
                            console.log('Hata Bilgisi  Gönder Response!')
                        },
                        error: function (req, textStatus, errorThrown) {
                            console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                        },
                    })
                }
        )
    }, parseInt(time) * 1000)
}

function getRandomInt(max) {
    return Math.floor(Math.random() * (max - 0 + 1)) + 0
}

function SekmeAc(link) {
    setTimeout(function () {
        console.log('Sekme Açılıyor: ' + link)
        chrome.runtime.sendMessage({
            YeniSekme: true,
            Url: link,
        })
    }, 1000)
}