-- Début du fichier
local addonName = "RaidPlayerExport"
local addon = LibStub("AceAddon-3.0"):GetAddon(addonName)
if not addon then return end

-- Vérifie si un joueur (nom sans serveur) est dans le groupe/raid actuel
local function IsPlayerInMyGroup(name)
    if not name then return false end
    if name == UnitName("player"):gsub("-.*", "") then return true end
    for i = 1, GetNumGroupMembers() do
        local unitName = GetRaidRosterInfo(i)
        if unitName and (unitName:gsub("-.*", "") == name) then
            return true
        end
    end
    return false
end

function addon:SaveLoot(playerName, itemLink)
    if not playerName or not itemLink then return end
    local classFileName = self.raidRosterCache[playerName]
    local dateStr = date("%d/%m/%Y")
    local history = self.lootDB.global.lootHistory
    if not history[dateStr] then history[dateStr] = {} end
    if not history[dateStr][playerName] then history[dateStr][playerName] = {} end
    if classFileName and not self.lootDB.global.playerClasses[playerName] then
        self.lootDB.global.playerClasses[playerName] = classFileName
    end
    table.insert(history[dateStr][playerName], itemLink)
    if self.frames.loot and self.frames.loot:IsShown() then
        self:UpdateLootHistoryDisplay()
    end
end

function addon:ProcessLoot(playerName, itemLink)
    local _, _, itemQuality, _, _, _, _, _, itemEquipLoc = GetItemInfo(itemLink)
    if not itemQuality or itemQuality < self.db.profile.lootQuality then
        return
    end
    if self.db.profile.lootTypeFilter == "EQUIPMENT" then
        if not itemEquipLoc or itemEquipLoc == "" or itemEquipLoc == "INVTYPE_NON_EQUIP_IGNORE" then
            return
        end
    end
    self:SaveLoot(playerName, itemLink)
end

function addon:LootEventHandler(event, msg, playerNameArg, ...)
    if not msg or not playerNameArg or playerNameArg == "" then return end
    local itemLink = msg:match("(|c.-|r)")
    if not itemLink then return end
    local cleanPlayerName = playerNameArg:gsub("-.*", "")
    local myName = UnitName("player"):gsub("-.*", "")
    local isForMe = (cleanPlayerName == myName)
    local iAmInGroup = IsInGroup()
    if IsPlayerInMyGroup(cleanPlayerName) then
        -- OK
    elseif self.db.profile.trackSoloLoot and isForMe and not iAmInGroup then
        -- OK
    else
        return
    end
    local _, _, itemQuality = GetItemInfo(itemLink)
    if itemQuality then
        self:ProcessLoot(cleanPlayerName, itemLink)
    else
        local itemID = itemLink:match("item:(%d+):")
        if itemID then
            self.pendingLoot[tonumber(itemID)] = cleanPlayerName
        end
    end
end

function addon:ItemInfoReceivedHandler(event, itemID, success)
    if not success or not self.pendingLoot[itemID] then return end
    local playerName = self.pendingLoot[itemID]
    local _, itemLink = GetItemInfo(itemID)
    if playerName and itemLink then
        self:ProcessLoot(playerName, itemLink)
    end
    self.pendingLoot[itemID] = nil
end

function addon:UpdateLootHistoryDisplay(isDefaultOpen)
    if self.isUpdatingLootDisplay then return end; self.isUpdatingLootDisplay = true
    local history = self.lootDB.global.lootHistory; local playerClasses = self.lootDB.global.playerClasses; local lines = {}
    for _, button in ipairs(self.frames.dateButtons) do button:Hide() end; wipe(self.frames.dateButtons)
    if not history or next(history) == nil then
        self.frames.lootHistory.officialText = "\nAucun butin n'a été enregistré pour le moment."; self.frames.lootHistory:SetText(self.frames.lootHistory.officialText); self.isUpdatingLootDisplay = false; return
    end
    local allDates = {}; for dateStr in pairs(history) do table.insert(allDates, dateStr) end
    table.sort(allDates, function(a, b)
        local d1,m1,y1=a:match("(%d+)/(%d+)/(%d+)") local d2,m2,y2=b:match("(%d+)/(%d+)/(%d+)")
        if not(d1 and d2) then return false end; d1,m1,y1,d2,m2,y2=tonumber(d1),tonumber(m1),tonumber(y1),tonumber(d2),tonumber(m2),tonumber(y2)
        if y1~=y2 then return y1>y2 end; if m1~=m2 then return m1>m2 end; return d1>d2
    end)
    local BUTTON_HEIGHT = 20; local yOffset = 0
    for i, dateStr in ipairs(allDates) do
        local button=CreateFrame("Button",nil,self.frames.dateListScrollChild,"UIPanelButtonTemplate"); button:SetText(dateStr); button:SetSize(self.frames.dateListScroll:GetWidth()-30,BUTTON_HEIGHT); button:SetPoint("TOP",0,yOffset-5)
        button:GetFontString():SetFontObject("GameFontNormalSmall"); button:SetScript("OnClick", function() if self.isUpdatingLootDisplay then return end; self.lootFilter=dateStr; self:UpdateLootHistoryDisplay() end)
        table.insert(self.frames.dateButtons,button); yOffset=yOffset-BUTTON_HEIGHT-2
    end
    self.frames.dateListScrollChild:SetHeight(math.abs(yOffset)+10)
    self.frames.lootFilterButtons.all:SetDisabled(self.lootFilter=="all")
    for _, button in ipairs(self.frames.dateButtons) do button:SetEnabled(button:GetText()~=self.lootFilter) end
    local datesToDisplay = {}; local todayStr=date("%d/%m/%Y")
    if self.lootFilter=="all" then datesToDisplay=allDates else if history[self.lootFilter] then table.insert(datesToDisplay,self.lootFilter) end end
    if #datesToDisplay==0 then
        if isDefaultOpen and self.lootFilter==todayStr then
            local message = string.format("\n\nAucun butin n'a été enregistré pour la date du %s.",todayStr)
            if #allDates>0 then message=message .. "\n\nN'hésitez pas à sélectionner une autre date dans la liste." end
            lines={message}
        else
            lines={"\n\nAucun butin ne correspond à ce filtre."}
        end
    else
        for i,dateStr in ipairs(datesToDisplay) do
            if i>1 then table.insert(lines,"") end
            table.insert(lines,"|cffffd100--- "..dateStr.." ---|r"); table.insert(lines,"")
            local playersOnDate=history[dateStr]; local sortedPlayers={}; for playerName in pairs(playersOnDate) do table.insert(sortedPlayers,playerName) end; table.sort(sortedPlayers)
            for _,playerName in ipairs(sortedPlayers) do
                local classFile=playerClasses[playerName]; local colorHex="|cffffffff"
                if classFile then colorHex=string.format("|cff%02x%02x%02x",C_ClassColor.GetClassColor(classFile).r*255,C_ClassColor.GetClassColor(classFile).g*255,C_ClassColor.GetClassColor(classFile).b*255) end
                if #lines>0 and lines[#lines]~="" then table.insert(lines,"") end
                table.insert(lines,string.format("%s%s :|r",colorHex,playerName))
                for _,itemLink in ipairs(playersOnDate[playerName]) do
                    table.insert(lines,"    » "..itemLink)
                end
            end
        end
    end
    local final_text=table.concat(lines,"\n"); self.frames.lootHistory.officialText=final_text; self.frames.lootHistory:SetText(final_text)
    self.isUpdatingLootDisplay=false
end

function addon:ClearLootHistory()
    wipe(self.lootDB.global.lootHistory); wipe(self.lootDB.global.playerClasses); wipe(self.pendingLoot)
    print("|cff00ff00[RPE]|r L'historique des butins a été vidé.")
    if self.frames.loot and self.frames.loot:IsShown() then self:UpdateLootHistoryDisplay() end
end
-- Fin du fichier