import discord
from discord.ext import commands
import json
import os
import asyncio
import uuid
from datetime import datetime
import aiohttp
from typing import Optional, Dict, List, Union

class TicketSystem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.tickets_file = "tickets_data.json"
        self.config_file = "tickets_config.json"
        self.tickets_data = self.load_tickets()
        self.config = self.load_config()
        self.discord_blue = 0x5865F2
        
        # Vytvoř výchozí konfiguraci, pokud neexistuje
        if not self.config:
            self.config = {
                "enabled": True,
                "ticket_category_id": None,
                "log_channel_id": None,
                "staff_roles": [],
                "ticket_types": [
                    {
                        "name": "Podpora",
                        "emoji": "🔧",
                        "color": 3447003,
                        "description": "Potřebuješ pomoc s botem nebo serverem?"
                    },
                    {
                        "name": "Nahlášení",
                        "emoji": "⚠️",
                        "color": 15105570, 
                        "description": "Nahlásit uživatele nebo problém"
                    },
                    {
                        "name": "Ostatní",
                        "emoji": "❓",
                        "color": 10181046,
                        "description": "Jiné požadavky"
                    }
                ],
                "ticket_name_format": "ticket-{user}",
                "welcome_message": "Vítej v ticketu, {user}! Napiš svůj problém a staff ti brzy odpoví.",
                "auto_close_hours": 72,
                "max_tickets_per_user": 3,
                "archive_closed_tickets": True,
                "web_auth_token": str(uuid.uuid4()),
                "web_webhook_url": "http://localhost:5000/api/ticket-webhook"
            }
            self.save_config()
    
    def load_tickets(self) -> Dict:
        """Načte data ticketů ze souboru"""
        if os.path.exists(self.tickets_file):
            try:
                with open(self.tickets_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except Exception as e:
                print(f"Chyba při načítání ticketů: {e}")
                return {"tickets": [], "archived": [], "stats": {"total": 0, "open": 0, "closed": 0}}
        else:
            return {"tickets": [], "archived": [], "stats": {"total": 0, "open": 0, "closed": 0}}
    
    def save_tickets(self) -> None:
        """Uloží data ticketů do souboru"""
        try:
            with open(self.tickets_file, "w", encoding="utf-8") as f:
                json.dump(self.tickets_data, f, indent=4, ensure_ascii=False)
            
            # Pokus se odeslat webhook notifikaci na web
            if self.config.get("web_webhook_url"):
                asyncio.create_task(self.notify_web_update())
        except Exception as e:
            print(f"Chyba při ukládání ticketů: {e}")
    
    def load_config(self) -> Dict:
        """Načte konfiguraci ticketů"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except Exception as e:
                print(f"Chyba při načítání konfigurace ticketů: {e}")
                return {}
        else:
            return {}
    
    def save_config(self) -> None:
        """Uloží konfiguraci ticketů"""
        try:
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
        except Exception as e:
            print(f"Chyba při ukládání konfigurace ticketů: {e}")
    
    async def notify_web_update(self) -> None:
        """Odešle webhook notifikaci na web o aktualizaci ticketů"""
        if not self.config.get("web_webhook_url"):
            return
            
        webhook_url = self.config["web_webhook_url"]
        auth_token = self.config["web_auth_token"]
        
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    webhook_url,
                    json={"type": "update", "timestamp": datetime.now().isoformat()},
                    headers={"Authorization": f"Bearer {auth_token}", "Content-Type": "application/json"}
                ) as response:
                    if response.status != 200:
                        print(f"Chyba při odesílání webhook notifikace: {response.status}")
        except Exception as e:
            print(f"Chyba při odesílání webhook notifikace: {e}")
    
    @commands.group(name="ticket", invoke_without_command=True)
    async def ticket_cmd(self, ctx):
        """Základní ticket příkaz"""
        embed = discord.Embed(
            title="🎫 Ticket Systém",
            description="Použij `!ticket help` pro nápovědu",
            color=self.discord_blue
        )
        await ctx.send(embed=embed)
    
    @ticket_cmd.command(name="help")
    async def ticket_help(self, ctx):
        """Zobrazí nápovědu pro ticket příkazy"""
        embed = discord.Embed(
            title="🎫 Ticket Systém - Nápověda",
            description="Seznam dostupných příkazů pro ticket systém",
            color=self.discord_blue
        )
        
        embed.add_field(
            name="👤 Uživatelské příkazy",
            value=(
                "`!ticket create [typ] [důvod]` - Vytvoří nový ticket\n"
                "`!ticket close [důvod]` - Uzavře aktuální ticket\n"
                "`!ticket add <@user>` - Přidá uživatele do ticketu\n"
                "`!ticket remove <@user>` - Odebere uživatele z ticketu"
            ),
            inline=False
        )
        
        # Kontrola, zda má uživatel roli staff nebo je admin
        is_staff = False
        if ctx.author.guild_permissions.administrator:
            is_staff = True
        else:
            for role_id in self.config.get("staff_roles", []):
                role = ctx.guild.get_role(int(role_id))
                if role and role in ctx.author.roles:
                    is_staff = True
                    break
        
        if is_staff:
            embed.add_field(
                name="🛡️ Staff příkazy",
                value=(
                    "`!ticket setup` - Nastaví panel pro vytváření ticketů\n"
                    "`!ticket archive` - Archivuje uzavřený ticket\n"
                    "`!ticket delete` - Smaže ticket permanentně\n"
                    "`!ticket reopen` - Znovu otevře uzavřený ticket\n"
                    "`!ticket list` - Zobrazí seznam aktivních ticketů\n"
                    "`!ticket view <id>` - Zobrazí detaily ticketu\n"
                    "`!ticket stats` - Zobrazí statistiky ticketů"
                ),
                inline=False
            )
            
            embed.add_field(
                name="⚙️ Admin příkazy",
                value=(
                    "`!ticket config` - Zobrazí aktuální konfiguraci\n"
                    "`!ticket config set <klíč> <hodnota>` - Nastaví hodnotu\n"
                    "`!ticket config reset` - Resetuje konfiguraci\n"
                    "`!ticket category <#kategorie>` - Nastaví kategorii\n"
                    "`!ticket log <#kanál>` - Nastaví log kanál\n"
                    "`!ticket addrole <@role>` - Přidá staff roli\n"
                    "`!ticket removerole <@role>` - Odebere staff roli"
                ),
                inline=False
            )
            
            embed.add_field(
                name="🌐 Web Dashboard",
                value=(
                    "Pro pokročilou správu ticketů použij web rozhraní:\n"
                    "**[localhost:5000/tickets](http://localhost:5000/tickets)**"
                ),
                inline=False
            )
        
        await ctx.send(embed=embed)
    
    @ticket_cmd.command(name="create")
    async def create_ticket(self, ctx, ticket_type: Optional[str] = None, *, reason: Optional[str] = None):
        """Vytvoří nový ticket"""
        # Kontrola, zda je systém povolen
        if not self.config.get("enabled", True):
            await ctx.send("❌ Ticket systém je momentálně vypnutý.")
            return
        
        # Kontrola limitů na počet ticketů pro uživatele
        max_tickets = self.config.get("max_tickets_per_user", 3)
        user_tickets = [t for t in self.tickets_data["tickets"] if t["user_id"] == str(ctx.author.id) and t["status"] == "open"]
        
        if len(user_tickets) >= max_tickets:
            await ctx.send(f"❌ Dosáhl jsi maximálního počtu otevřených ticketů ({max_tickets}).")
            return
        
        # Kontrola, zda existuje kategorie pro tickety
        category_id = self.config.get("ticket_category_id")
        if not category_id:
            await ctx.send("❌ Kategorie pro tickety není nastavena. Kontaktuj administrátora.")
            return
            
        category = ctx.guild.get_channel(int(category_id))
        if not category:
            await ctx.send("❌ Kategorie pro tickety nebyla nalezena. Kontaktuj administrátora.")
            return
        
        # **DEBUG: Zkontroluj práva bota**
        bot_permissions = category.permissions_for(ctx.guild.me)
        if not bot_permissions.manage_channels:
            await ctx.send("❌ Bot nemá práva na správu kanálů v této kategorii!")
            return
        
        # Vytvoření nového ticketu
        ticket_types = self.config.get("ticket_types", [])
        selected_type = None
        
        # Pokud byl zadán typ ticketu, najdi ho
        if ticket_type:
            for t_type in ticket_types:
                if t_type["name"].lower() == ticket_type.lower():
                    selected_type = t_type
                    break
        
        # Pokud nebyl typ nalezen, použij první typ
        if not selected_type and ticket_types:
            selected_type = ticket_types[0]
        elif not selected_type:
            selected_type = {
                "name": "Podpora",
                "emoji": "🔧",
                "color": 3447003,
                "description": "Podpora"
            }
        
        # Formát jména ticketu
        ticket_name = self.config.get("ticket_name_format", "ticket-{user}").format(
            user=ctx.author.name.lower().replace(" ", "-"),
            id=len(self.tickets_data["tickets"]) + 1
        )
        
        # Vytvoření kanálu
        overwrites = {
            ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            ctx.author: discord.PermissionOverwrite(read_messages=True, send_messages=True),
            ctx.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_channels=True)
        }
        
        # Přidání povolení pro staff role
        for role_id in self.config.get("staff_roles", []):
            try:
                role = ctx.guild.get_role(int(role_id))
                if role:
                    overwrites[role] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
            except:
                pass
    
        try:
            # **DEBUG: Vypíš informace před vytvořením**
            print(f"DEBUG: Creating channel '{ticket_name}' in category '{category.name}'")
            print(f"DEBUG: Overwrites: {overwrites}")
            
            # Vytvoření kanálu
            channel = await category.create_text_channel(name=ticket_name, overwrites=overwrites)
            
            print(f"DEBUG: Channel created: {channel.name} (ID: {channel.id})")
            
            # Generování ticket ID
            ticket_id = str(uuid.uuid4())[:8]
            
            # Vytvoření uvítací zprávy
            welcome_message = self.config.get("welcome_message", "Vítej v ticketu, {user}! Napiš svůj problém a staff ti brzy odpoví.")
            welcome_message = welcome_message.format(user=ctx.author.mention)
            
            embed = discord.Embed(
                title=f"{selected_type['emoji']} Ticket: {selected_type['name']}",
                description=welcome_message,
                color=selected_type["color"]
            )
            
            embed.add_field(name="Uživatel", value=ctx.author.mention, inline=True)
            embed.add_field(name="ID Ticketu", value=f"`{ticket_id}`", inline=True)
            
            if reason:
                embed.add_field(name="Důvod", value=reason, inline=False)
            
            embed.set_footer(text=f"Pro uzavření ticketu použij !ticket close")
            
            welcome_msg = await channel.send(embed=embed)
            await welcome_msg.pin()
            
            # Přidání reakcí pro rychlé akce
            await welcome_msg.add_reaction("🔒")  # Zavřít
            await welcome_msg.add_reaction("📝")  # Přidat poznámku
            
            # Odeslání potvrzení do původního kanálu
            confirm_embed = discord.Embed(
                title="✅ Ticket vytvořen",
                description=f"Tvůj ticket byl vytvořen: {channel.mention}",
                color=self.discord_blue
            )
            await ctx.send(embed=confirm_embed)
            
            # Uložení ticketu do databáze
            ticket_data = {
                "id": ticket_id,
                "channel_id": str(channel.id),
                "user_id": str(ctx.author.id),
                "user_name": ctx.author.name,
                "guild_id": str(ctx.guild.id),
                "type": selected_type["name"],
                "reason": reason or "Žádný důvod nebyl uveden",
                "status": "open",
                "created_at": datetime.now().isoformat(),
                "closed_at": None,
                "messages": [],
                "participants": [str(ctx.author.id)],
                "color": selected_type["color"]
            }
            
            self.tickets_data["tickets"].append(ticket_data)
            self.tickets_data["stats"]["total"] += 1
            self.tickets_data["stats"]["open"] += 1
            self.save_tickets()
            
            # Logování vytvoření ticketu
            await self.log_ticket_event(ctx.guild, f"Ticket vytvořen: #{ticket_id}", ctx.author, ticket_data)
            
        except Exception as e:
            print(f"ERROR: {e}")  # Debug výpis chyby
            await ctx.send(f"❌ Chyba při vytváření ticketu: {e}")
    
    @ticket_cmd.command(name="close")
    async def close_ticket(self, ctx, *, reason: Optional[str] = "Žádný důvod nebyl uveden"):
        """Uzavře aktuální ticket"""
        # Kontrola, zda je příkaz použit v ticketu
        ticket_data = None
        for ticket in self.tickets_data["tickets"]:
            if ticket["channel_id"] == str(ctx.channel.id) and ticket["status"] == "open":
                ticket_data = ticket
                break
        
        if not ticket_data:
            await ctx.send("❌ Tento kanál není otevřeným ticketem.")
            return
        
        # Kontrola oprávnění
        is_staff = False
        is_ticket_creator = str(ctx.author.id) == ticket_data["user_id"]
        
        if ctx.author.guild_permissions.administrator:
            is_staff = True
        else:
            for role_id in self.config.get("staff_roles", []):
                role = ctx.guild.get_role(int(role_id))
                if role and role in ctx.author.roles:
                    is_staff = True
                    break
        
        if not (is_staff or is_ticket_creator):
            await ctx.send("❌ Nemáš oprávnění uzavřít tento ticket.")
            return
        
        # Uzavření ticketu
        try:
            # Aktualizace dat
            ticket_data["status"] = "closed"
            ticket_data["closed_at"] = datetime.now().isoformat()
            ticket_data["close_reason"] = reason
            ticket_data["closed_by"] = str(ctx.author.id)
            
            # Aktualizace statistik
            self.tickets_data["stats"]["open"] -= 1
            self.tickets_data["stats"]["closed"] += 1
            
            self.save_tickets()
            
            # Úprava oprávnění kanálu
            for user_id in ticket_data["participants"]:
                try:
                    user = ctx.guild.get_member(int(user_id))
                    if user:
                        await ctx.channel.set_permissions(user, send_messages=False)
                except:
                    pass
            
            # Odeslání zprávy o uzavření
            embed = discord.Embed(
                title="🔒 Ticket uzavřen",
                description=f"Tento ticket byl uzavřen uživatelem {ctx.author.mention}",
                color=0xf44336
            )
            embed.add_field(name="Důvod", value=reason, inline=False)
            embed.add_field(name="ID Ticketu", value=f"`{ticket_data['id']}`", inline=True)
            embed.add_field(name="Možnosti", value="🔓 - Znovu otevřít\n📁 - Archivovat\n❌ - Smazat", inline=False)
            
            close_msg = await ctx.send(embed=embed)
            
            # Přidání reakcí pro další akce
            await close_msg.add_reaction("🔓")  # Znovu otevřít
            await close_msg.add_reaction("📁")  # Archivovat
            await close_msg.add_reaction("❌")   # Smazat
            
            # Logování uzavření ticketu
            await self.log_ticket_event(ctx.guild, f"Ticket uzavřen: #{ticket_data['id']}", ctx.author, ticket_data)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při uzavírání ticketu: {e}")
    
    @ticket_cmd.command(name="setup")
    @commands.has_permissions(administrator=True)
    async def setup_ticket_panel(self, ctx):
        """Nastaví panel pro vytváření ticketů"""
        embed = discord.Embed(
            title="🎫 Vytvoření Ticketu",
            description="Klikni na reakci podle typu problému, který potřebuješ vyřešit.",
            color=self.discord_blue
        )
        
        ticket_types = self.config.get("ticket_types", [])
        
        if not ticket_types:
            ticket_types = [
                {"name": "Podpora", "emoji": "🔧", "description": "Potřebuješ pomoc s botem nebo serverem?"},
                {"name": "Nahlášení", "emoji": "⚠️", "description": "Nahlásit uživatele nebo problém"},
                {"name": "Ostatní", "emoji": "❓", "description": "Jiné požadavky"}
            ]
        
        for t_type in ticket_types:
            embed.add_field(
                name=f"{t_type['emoji']} {t_type['name']}",
                value=t_type['description'],
                inline=False
            )
        
        embed.set_footer(text="Reaguj na tuto zprávu pro vytvoření ticketu")
        
        panel_msg = await ctx.send(embed=embed)
        
        # Přidání reakcí
        for t_type in ticket_types:
            await panel_msg.add_reaction(t_type['emoji'])
        
        # Uložení ID zprávy pro pozdější použití
        self.config["ticket_panel_message_id"] = str(panel_msg.id)
        self.config["ticket_panel_channel_id"] = str(ctx.channel.id)
        self.save_config()
        
        await ctx.message.delete()
    
    @ticket_cmd.command(name="add")
    async def add_user_to_ticket(self, ctx, user: discord.Member):
        """Přidá uživatele do ticketu"""
        # Kontrola, zda je příkaz použit v ticketu
        ticket_data = None
        for ticket in self.tickets_data["tickets"]:
            if ticket["channel_id"] == str(ctx.channel.id) and ticket["status"] == "open":
                ticket_data = ticket
                break
        
        if not ticket_data:
            await ctx.send("❌ Tento kanál není otevřeným ticketem.")
            return
        
        # Kontrola oprávnění
        is_staff = False
        is_ticket_creator = str(ctx.author.id) == ticket_data["user_id"]
        
        if ctx.author.guild_permissions.administrator:
            is_staff = True
        else:
            for role_id in self.config.get("staff_roles", []):
                role = ctx.guild.get_role(int(role_id))
                if role and role in ctx.author.roles:
                    is_staff = True
                    break
        
        if not (is_staff or is_ticket_creator):
            await ctx.send("❌ Nemáš oprávnění přidat uživatele do tohoto ticketu.")
            return
        
        # Kontrola, zda uživatel už není v ticketu
        if str(user.id) in ticket_data["participants"]:
            await ctx.send(f"❌ {user.mention} už má přístup k tomuto ticketu.")
            return
        
        # Přidání uživatele
        try:
            await ctx.channel.set_permissions(user, read_messages=True, send_messages=True)
            
            ticket_data["participants"].append(str(user.id))
            self.save_tickets()
            
            embed = discord.Embed(
                title="✅ Uživatel přidán",
                description=f"{user.mention} byl přidán do ticketu.",
                color=self.discord_blue
            )
            await ctx.send(embed=embed)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při přidávání uživatele: {e}")
    
    @ticket_cmd.command(name="remove")
    async def remove_user_from_ticket(self, ctx, user: discord.Member):
        """Odebere uživatele z ticketu"""
        # Kontrola, zda je příkaz použit v ticketu
        ticket_data = None
        for ticket in self.tickets_data["tickets"]:
            if ticket["channel_id"] == str(ctx.channel.id) and ticket["status"] == "open":
                ticket_data = ticket
                break
        
        if not ticket_data:
            await ctx.send("❌ Tento kanál není otevřeným ticketem.")
            return
        
        # Kontrola oprávnění
        is_staff = False
        is_ticket_creator = str(ctx.author.id) == ticket_data["user_id"]
        
        if ctx.author.guild_permissions.administrator:
            is_staff = True
        else:
            for role_id in self.config.get("staff_roles", []):
                role = ctx.guild.get_role(int(role_id))
                if role and role in ctx.author.roles:
                    is_staff = True
                    break
        
        if not (is_staff or is_ticket_creator):
            await ctx.send("❌ Nemáš oprávnění odebrat uživatele z tohoto ticketu.")
            return
        
        # Kontrola, zda není uživatel vlastníkem ticketu
        if str(user.id) == ticket_data["user_id"]:
            await ctx.send("❌ Nelze odebrat vlastníka ticketu.")
            return
        
        # Kontrola, zda je uživatel v ticketu
        if str(user.id) not in ticket_data["participants"]:
            await ctx.send(f"❌ {user.mention} nemá přístup k tomuto ticketu.")
            return
        
        # Odebrání uživatele
        try:
            await ctx.channel.set_permissions(user, overwrite=None)
            
            ticket_data["participants"].remove(str(user.id))
            self.save_tickets()
            
            embed = discord.Embed(
                title="✅ Uživatel odebrán",
                description=f"{user.mention} byl odebrán z ticketu.",
                color=self.discord_blue
            )
            await ctx.send(embed=embed)
            
        except Exception as e:
            await ctx.send(f"❌ Chyba při odebírání uživatele: {e}")
    
    @ticket_cmd.command(name="stats")
    @commands.has_permissions(administrator=True)
    async def ticket_stats(self, ctx):
        """Zobrazí statistiky ticketů"""
        stats = self.tickets_data["stats"]
        
        embed = discord.Embed(
            title="📊 Statistiky Ticketů",
            color=self.discord_blue
        )
        
        embed.add_field(name="📝 Celkem vytvořeno", value=stats["total"], inline=True)
        embed.add_field(name="🔓 Aktuálně otevřené", value=stats["open"], inline=True)
        embed.add_field(name="🔒 Uzavřené", value=stats["closed"], inline=True)
        
        # Nejaktivnější uživatelé
        user_tickets = {}
        for ticket in self.tickets_data["tickets"]:
            user_id = ticket["user_id"]
            if user_id not in user_tickets:
                user_tickets[user_id] = 0
            user_tickets[user_id] += 1
        
        # Seřazení podle počtu ticketů
        top_users = sorted(user_tickets.items(), key=lambda x: x[1], reverse=True)[:5]
        
        if top_users:
            users_text = ""
            for i, (user_id, count) in enumerate(top_users, 1):
                try:
                    user = await self.bot.fetch_user(int(user_id))
                    users_text += f"**{i}.** {user.name}: **{count}** ticketů\n"
                except:
                    users_text += f"**{i}.** ID {user_id}: **{count}** ticketů\n"
            
            embed.add_field(name="👥 Nejaktivnější uživatelé", value=users_text or "Žádní uživatelé", inline=False)
        
        embed.add_field(
            name="🌐 Web Dashboard",
            value="Podrobné statistiky najdeš na [web dashboardu](http://localhost:5000/tickets/stats)",
            inline=False
        )
        
        await ctx.send(embed=embed)
    
    @ticket_cmd.command(name="category")
    @commands.has_permissions(administrator=True)
    async def set_ticket_category(self, ctx, category: discord.CategoryChannel):
        """Nastaví kategorii pro tickety"""
        self.config["ticket_category_id"] = str(category.id)
        self.save_config()
        
        embed = discord.Embed(
            title="✅ Kategorie nastavena",
            description=f"Tickety budou vytvářeny v kategorii: {category.name}",
            color=self.discord_blue
        )
        await ctx.send(embed=embed)
    
    @ticket_cmd.command(name="log")
    @commands.has_permissions(administrator=True)
    async def set_log_channel(self, ctx, channel: discord.TextChannel):
        """Nastaví kanál pro logování ticketů"""
        self.config["log_channel_id"] = str(channel.id)
        self.save_config()
        
        embed = discord.Embed(
            title="✅ Log kanál nastaven",
            description=f"Logy ticketů budou odesílány do: {channel.mention}",
            color=self.discord_blue
        )
        await ctx.send(embed=embed)
    
    async def log_ticket_event(self, guild, action, user, ticket_data=None):
        """Loguje událost ticketu do nastaveného kanálu"""
        log_channel_id = self.config.get("log_channel_id")
        if not log_channel_id:
            return
        
        log_channel = guild.get_channel(int(log_channel_id))
        if not log_channel:
            return
        
        embed = discord.Embed(
            title="🎫 Ticket Log",
            description=action,
            color=self.discord_blue,
            timestamp=datetime.now()
        )
        
        embed.add_field(name="👤 Uživatel", value=f"{user.mention} ({user.id})", inline=True)
        
        if ticket_data:
            embed.add_field(name="🆔 Ticket ID", value=ticket_data["id"], inline=True)
            
            if ticket_data.get("channel_id"):
                channel = guild.get_channel(int(ticket_data["channel_id"]))
                if channel:
                    embed.add_field(name="📝 Kanál", value=channel.mention, inline=True)
            
            embed.add_field(name="📊 Status", value=ticket_data["status"].capitalize(), inline=True)
            
            if ticket_data.get("created_at"):
                created_time = datetime.fromisoformat(ticket_data["created_at"])
                embed.add_field(name="⏰ Vytvořeno", value=f"<t:{int(created_time.timestamp())}:R>", inline=True)
            
            if ticket_data.get("closed_at") and ticket_data["closed_at"] is not None:
                closed_time = datetime.fromisoformat(ticket_data["closed_at"])
                embed.add_field(name="🔒 Uzavřeno", value=f"<t:{int(closed_time.timestamp())}:R>", inline=True)
        
        await log_channel.send(embed=embed)
    
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        """Zpracování reakcí na ticket zprávy"""
        if payload.user_id == self.bot.user.id:
            return
        
        # Kontrola, zda je reakce na ticket panel
        if str(payload.message_id) == self.config.get("ticket_panel_message_id", ""):
            guild = self.bot.get_guild(payload.guild_id)
            if not guild:
                return
            
            channel = guild.get_channel(payload.channel_id)
            if not channel:
                return
            
            user = guild.get_member(payload.user_id)
            if not user:
                return
            
            # Získání zprávy
            try:
                message = await channel.fetch_message(payload.message_id)
                await message.remove_reaction(payload.emoji, user)
            except:
                return
            
            # Zjištění typu ticketu podle emoji
            ticket_type = None
            for t_type in self.config.get("ticket_types", []):
                if str(payload.emoji) == t_type["emoji"]:
                    ticket_type = t_type["name"]
                    break
            
            if ticket_type:
                # Vytvoření ticketu přes command context
                ctx = await self.bot.get_context(message)
                ctx.author = user
                await self.create_ticket(ctx, ticket_type)
        
        # Kontrola, zda je reakce na zprávu v ticketu
        else:
            # Hledání ticketu podle channel_id
            ticket_data = None
            for ticket in self.tickets_data["tickets"]:
                if ticket["channel_id"] == str(payload.channel_id):
                    ticket_data = ticket
                    break
            
            if not ticket_data:
                return
            
            guild = self.bot.get_guild(payload.guild_id)
            if not guild:
                return
            
            channel = guild.get_channel(payload.channel_id)
            if not channel:
                return
            
            user = guild.get_member(payload.user_id)
            if not user:
                return
            
            # Kontrola oprávnění
            is_staff = False
            is_ticket_creator = str(user.id) == ticket_data["user_id"]
            
            if user.guild_permissions.administrator:
                is_staff = True
            else:
                for role_id in self.config.get("staff_roles", []):
                    role = guild.get_role(int(role_id))
                    if role and role in user.roles:
                        is_staff = True
                        break
            
            # Získání zprávy
            try:
                message = await channel.fetch_message(payload.message_id)
                await message.remove_reaction(payload.emoji, user)
            except:
                return
            
            # Zpracování akce podle emoji
            emoji = str(payload.emoji)
            
            if emoji == "🔒" and ticket_data["status"] == "open":
                # Uzavření ticketu
                if is_staff or is_ticket_creator:
                    ctx = await self.bot.get_context(message)
                    ctx.author = user
                    await self.close_ticket(ctx, reason="Uzavřeno pomocí reakce")
            
            elif emoji == "🔓" and ticket_data["status"] == "closed":
                # Znovu otevření ticketu
                if is_staff:
                    # Aktualizace dat
                    ticket_data["status"] = "open"
                    ticket_data["closed_at"] = None
                    
                    # Aktualizace statistik
                    self.tickets_data["stats"]["open"] += 1
                    self.tickets_data["stats"]["closed"] -= 1
                    
                    self.save_tickets()
                    
                    # Obnovení oprávnění
                    for user_id in ticket_data["participants"]:
                        try:
                            member = guild.get_member(int(user_id))
                            if member:
                                await channel.set_permissions(member, send_messages=True)
                        except:
                            pass
                    
                    # Odeslání zprávy
                    embed = discord.Embed(
                        title="🔓 Ticket znovu otevřen",
                        description=f"Tento ticket byl znovu otevřen uživatelem {user.mention}",
                        color=self.discord_blue
                    )
                    await channel.send(embed=embed)
                    
                    # Logování
                    await self.log_ticket_event(guild, f"Ticket znovu otevřen: #{ticket_data['id']}", user, ticket_data)
            
            elif emoji == "📁" and ticket_data["status"] == "closed":
                # Archivace ticketu
                if is_staff:
                    # Přidání do archivu
                    self.tickets_data["archived"].append(ticket_data)
                    
                    # Odebrání z aktivních ticketů
                    self.tickets_data["tickets"] = [t for t in self.tickets_data["tickets"] if t["id"] != ticket_data["id"]]
                    
                    self.save_tickets()
                    
                    # Odeslání zprávy
                    embed = discord.Embed(
                        title="📁 Ticket archivován",
                        description=f"Tento ticket byl archivován uživatelem {user.mention}",
                        color=0xffa726
                    )
                    await channel.send(embed=embed)
                    
                    # Logování
                    await self.log_ticket_event(guild, f"Ticket archivován: #{ticket_data['id']}", user, ticket_data)
                    
                    # Nastavení cooldownu pro smazání kanálu
                    await asyncio.sleep(10)
                    
                    try:
                        await channel.delete()
                    except:
                        pass
            
            elif emoji == "❌" and ticket_data["status"] == "closed":
                # Smazání ticketu
                if is_staff:
                    # Odebrání z aktivních ticketů
                    self.tickets_data["tickets"] = [t for t in self.tickets_data["tickets"] if t["id"] != ticket_data["id"]]
                    
                    self.save_tickets()
                    
                    # Odeslání zprávy
                    embed = discord.Embed(
                        title="❌ Ticket bude smazán",
                        description=f"Tento ticket bude smazán za 5 sekund...",
                        color=0xf44336
                    )
                    await channel.send(embed=embed)
                    
                    # Logování
                    await self.log_ticket_event(guild, f"Ticket smazán: #{ticket_data['id']}", user, ticket_data)
                    
                    # Nastavení cooldownu pro smazání kanálu
                    await asyncio.sleep(5)
                    
                    try:
                        await channel.delete()
                    except:
                        pass
            
            elif emoji == "📝":
                # Přidání poznámky do ticketu
                if is_staff:
                    # Získání poznámky pomocí DM
                    try:
                        dm_embed = discord.Embed(
                            title="📝 Přidání poznámky do ticketu",
                            description=f"Zadej poznámku, kterou chceš přidat do ticketu. Máš 60 sekund.\nOdpověz `cancel` pro zrušení.",
                            color=self.discord_blue
                        )
                        dm_message = await user.send(embed=dm_embed)
                        
                        def check(m):
                            return m.channel == dm_message.channel and m.author == user
                        
                        try:
                            note_message = await self.bot.wait_for('message', timeout=60.0, check=check)
                            
                            if note_message.content.lower() == "cancel":
                                await user.send("❌ Přidání poznámky zrušeno.")
                                return
                            
                            # Přidání poznámky do ticketu
                            embed = discord.Embed(
                                title="📝 Poznámka Staff",
                                description=note_message.content,
                                color=0xff9800
                            )
                            embed.set_author(name=user.name, icon_url=user.display_avatar.url)
                            embed.set_footer(text=f"Ticket ID: {ticket_data['id']}")
                            
                            await channel.send(embed=embed)
                            await user.send("✅ Poznámka byla přidána do ticketu.")
                            
                        except asyncio.TimeoutError:
                            await user.send("❌ Čas vypršel. Přidání poznámky zrušeno.")
                    except:
                        # Pokud nelze poslat DM, pokus se o přímou odpověď v kanálu
                        embed = discord.Embed(
                            title="📝 Přidání poznámky do ticketu",
                            description="Nelze ti poslat DM. Použij příkaz `!ticket note <text>` přímo v tomto kanálu.",
                            color=self.discord_blue
                        )
                        await channel.send(embed=embed)

    @ticket_cmd.command(name="addrole")
    @commands.has_permissions(administrator=True)
    async def add_staff_role(self, ctx, role: discord.Role):
        """Přidá roli do staff rolí pro ticket systém"""
        if str(role.id) in self.config.get("staff_roles", []):
            await ctx.send("❌ Tato role už je v seznamu staff rolí.")
            return
        
        if "staff_roles" not in self.config:
            self.config["staff_roles"] = []
        
        self.config["staff_roles"].append(str(role.id))
        self.save_config()
        
        embed = discord.Embed(
            title="✅ Role přidána",
            description=f"Role {role.mention} byla přidána do staff rolí pro ticket systém.",
            color=self.discord_blue
        )
        await ctx.send(embed=embed)

    @ticket_cmd.command(name="removerole")
    @commands.has_permissions(administrator=True)
    async def remove_staff_role(self, ctx, role: discord.Role):
        """Odebere roli ze staff rolí pro ticket systém"""
        if str(role.id) not in self.config.get("staff_roles", []):
            await ctx.send("❌ Tato role není v seznamu staff rolí.")
            return
        
        self.config["staff_roles"].remove(str(role.id))
        self.save_config()
        
        embed = discord.Embed(
            title="✅ Role odebrána",
            description=f"Role {role.mention} byla odebrána ze staff rolí pro ticket systém.",
            color=self.discord_blue
        )
        await ctx.send(embed=embed)

    @ticket_cmd.command(name="list")
    @commands.has_permissions(administrator=True)
    async def list_tickets(self, ctx):
        """Zobrazí seznam aktivních ticketů"""
        embed = discord.Embed(
            title="🎫 Seznam Ticketů",
            color=self.discord_blue
        )
        
        open_tickets = [t for t in self.tickets_data["tickets"] if t["status"] == "open"]
        closed_tickets = [t for t in self.tickets_data["tickets"] if t["status"] == "closed"]
        
        if not open_tickets and not closed_tickets:
            embed.description = "Žádné aktivní tickety."
            await ctx.send(embed=embed)
            return
        
        if open_tickets:
            open_text = ""
            for i, ticket in enumerate(open_tickets[:10], 1):
                channel = ctx.guild.get_channel(int(ticket["channel_id"]))
                channel_mention = channel.mention if channel else "Kanál nenalezen"
                
                try:
                    user = await self.bot.fetch_user(int(ticket["user_id"]))
                    user_name = user.name
                except:
                    user_name = ticket["user_name"] if "user_name" in ticket else "Unknown"
                
                open_text += f"**{i}.** ID: `{ticket['id']}` | {channel_mention} | 👤 {user_name}\n"
            
            if open_text:
                embed.add_field(name="🔓 Otevřené Tickety", value=open_text, inline=False)
        
        if closed_tickets:
            closed_text = ""
            for i, ticket in enumerate(closed_tickets[:5], 1):
                channel = ctx.guild.get_channel(int(ticket["channel_id"]))
                channel_mention = channel.mention if channel else "Kanál nenalezen"
                
                try:
                    user = await self.bot.fetch_user(int(ticket["user_id"]))
                    user_name = user.name
                except:
                    user_name = ticket["user_name"] if "user_name" in ticket else "Unknown"
                
                closed_text += f"**{i}.** ID: `{ticket['id']}` | {channel_mention} | 👤 {user_name}\n"
            
            if closed_text:
                embed.add_field(name="🔒 Uzavřené Tickety", value=closed_text, inline=False)
        
        embed.add_field(
            name="🌐 Web Dashboard",
            value="Kompletní seznam ticketů najdeš na [web dashboardu](http://localhost:5000/tickets)",
            inline=False
        )
        
        await ctx.send(embed=embed)

    @ticket_cmd.command(name="config")
    @commands.has_permissions(administrator=True)
    async def show_config(self, ctx):
        """Zobrazí aktuální konfiguraci ticket systému"""
        embed = discord.Embed(
            title="⚙️ Konfigurace Ticket Systému",
            color=self.discord_blue
        )
        
        # Základní konfigurace
        embed.add_field(
            name="🔧 Základní nastavení",
            value=(
                f"• Status: **{'Zapnuto' if self.config.get('enabled', True) else 'Vypnuto'}**\n"
                f"• Max ticketů na uživatele: **{self.config.get('max_tickets_per_user', 3)}**\n"
                f"• Auto-zavření po: **{self.config.get('auto_close_hours', 72)} hodinách**\n"
                f"• Archivace uzavřených: **{'Ano' if self.config.get('archive_closed_tickets', True) else 'Ne'}**"
            ),
            inline=False
        )
        
        # Kanály a kategorie
        category = None
        if self.config.get("ticket_category_id"):
            category = ctx.guild.get_channel(int(self.config["ticket_category_id"]))
        
        log_channel = None
        if self.config.get("log_channel_id"):
            log_channel = ctx.guild.get_channel(int(self.config["log_channel_id"]))
        
        embed.add_field(
            name="📁 Kanály a kategorie",
            value=(
                f"• Kategorie: **{category.name if category else 'Nenastaveno'}**\n"
                f"• Log kanál: **{log_channel.mention if log_channel else 'Nenastaveno'}**"
            ),
            inline=False
        )
        
        # Staff role
        roles_text = ""
        for role_id in self.config.get("staff_roles", []):
            role = ctx.guild.get_role(int(role_id))
            if role:
                roles_text += f"• {role.mention}\n"
        
        embed.add_field(
            name="👮 Staff role",
            value=roles_text or "Žádné role nastaveny",
            inline=False
        )
        
        # Typy ticketů
        types_text = ""
        for t_type in self.config.get("ticket_types", []):
            types_text += f"• {t_type['emoji']} **{t_type['name']}**\n"
        
        embed.add_field(
            name="🏷️ Typy ticketů",
            value=types_text or "Žádné typy nastaveny",
            inline=False
        )
        
        # Web konfigurace
        embed.add_field(
            name="🌐 Web rozhraní",
            value=(
                "• Dashboard: **[localhost:5000/tickets](http://localhost:5000/tickets)**\n"
                "• API endpoint: **http://localhost:5000/api/tickets**\n"
                f"• Auth token: `{self.config.get('web_auth_token', 'nenastaven')[:6]}...`"
            ),
            inline=False
        )
        
        await ctx.send(embed=embed)

    @ticket_cmd.command(name="sync")
    @commands.has_permissions(administrator=True)
    async def sync_web_config(self, ctx):
        """Synchronizuje konfiguraci s webovým rozhraním"""
        await self.notify_web_update()
        
        embed = discord.Embed(
            title="✅ Synchronizace dokončena",
            description="Konfigurace a data ticket systému byla synchronizována s webovým rozhraním.",
            color=self.discord_blue
        )
        await ctx.send(embed=embed)

    @commands.Cog.listener()
    async def on_message(self, message):
        """Zachycení zpráv v ticket kanálech pro logování"""
        if message.author.bot:
            return
        
        # Kontrola, zda je zpráva v ticket kanálu
        ticket_data = None
        for ticket in self.tickets_data["tickets"]:
            if ticket["channel_id"] == str(message.channel.id):
                ticket_data = ticket
                break
        
        if not ticket_data or ticket_data["status"] != "open":
            return
        
        # Přidání zprávy do logu ticketu
        message_data = {
            "id": str(message.id),
            "author_id": str(message.author.id),
            "author_name": message.author.name,
            "content": message.content,
            "timestamp": datetime.now().isoformat(),
            "attachments": [attachment.url for attachment in message.attachments]
        }
        
        if "messages" not in ticket_data:
            ticket_data["messages"] = []
        
        ticket_data["messages"].append(message_data)
        
        # Přidání uživatele do participants, pokud tam ještě není
        if str(message.author.id) not in ticket_data["participants"]:
            ticket_data["participants"].append(str(message.author.id))
        
        self.save_tickets()

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"📩 Ticket System loaded")
        self.bot.add_view(TicketView())
        # Spustí kontrolu požadavků na panel
        self.bot.loop.create_task(self.check_panel_requests())

    async def check_panel_requests(self):
        """Pravidelně kontroluje požadavky na vytvoření ticket panelu z webového rozhraní"""
        await self.bot.wait_until_ready()
        while not self.bot.is_closed():
            try:
                panel_request_file = os.path.join(self.base_dir, 'ticket_panel_request.json')
                if os.path.exists(panel_request_file):
                    with open(panel_request_file, 'r') as f:
                        request = json.load(f)
                    
                    # Zpracuj požadavek
                    if request.get('action') == 'post_panel':
                        await self.post_ticket_panel()
                    
                    # Smaž soubor s požadavkem
                    os.remove(panel_request_file)
            except Exception as e:
                print(f"Error checking panel requests: {e}")
            
            # Kontroluj každých 5 sekund
            await asyncio.sleep(5)

    async def post_ticket_panel(self):
        """Vytvoří ticket panel v nastaveném kanálu"""
        try:
            # Zkontroluj konfiguraci
            if not self.config.get('channel_id'):
                return False
            
            # Získej kanál
            channel = self.bot.get_channel(int(self.config['channel_id']))
            if not channel:
                return False
            
            # Vytvoř embed a view
            embed = discord.Embed(
                title=self.config["embed"]["title"],
                description=self.config["embed"]["description"],
                color=self.config["embed"]["color"]
            )
            
            view = TicketView()
            await channel.send(embed=embed, view=view)
            return True
        except Exception as e:
            print(f"Error posting ticket panel: {e}")
            return False

async def setup(bot):
    await bot.add_cog(TicketSystem(bot))