import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import subprocess
import os
import sys
import webbrowser
import threading
import time
import socket
import json
import shutil
from datetime import datetime
import tempfile

class EasyWebsiteInstaller:
    def __init__(self, root):
        self.root = root
        self.root.title("Informatik Easy Website")
        self.root.geometry("800x600")
        
        # App info
        self.app_name = "Informatik Easy Website"
        self.developer = "Elis Šabič"
        self.email = "informatic@informatik.tech"
        self.website = "https://informatik.tech/"
        
        # Service status
        self.apache_running = False
        self.mysql_running = False
        
        # Installation directory
        self.install_dir = "C:\\InformatikEasyWebsite"
        
        # Setup GUI
        self.setup_gui()
        
        # Check for existing XAMPP/WAMP
        self.check_existing_installations()
        
        # Start monitoring
        self.start_monitoring()
        
        # Handle window close
        self.root.protocol("WM_DELETE_WINDOW", self.minimize_to_tray)
    
    def setup_gui(self):
        """Setup the main GUI"""
        # Create notebook (tabs)
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill='both', expand=True, padx=10, pady=5)
        
        # Create tabs
        self.create_welcome_tab()
        self.create_install_tab()
        self.create_monitor_tab()
        self.create_tools_tab()
        self.create_about_tab()
        
        # Status bar
        self.status_bar = tk.Label(self.root, text="Pripravljeno", bd=1, 
                                  relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
    
    def create_welcome_tab(self):
        """Create welcome tab"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="Dobrodošli")
        
        # Header
        header_frame = tk.Frame(tab, bg="#2c3e50")
        header_frame.pack(fill=tk.X, padx=0, pady=0)
        
        title_label = tk.Label(header_frame, text="Informatik Easy Website", 
                               font=("Arial", 22, "bold"), fg="white", bg="#2c3e50")
        title_label.pack(pady=15)
        
        subtitle_label = tk.Label(header_frame, text="Enostavna namestitev spletnega strežnika", 
                                  font=("Arial", 12), fg="#ecf0f1", bg="#2c3e50")
        subtitle_label.pack(pady=(0, 15))
        
        # Content
        content_frame = tk.Frame(tab)
        content_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # Welcome message
        welcome_text = """Dobrodošli v programu Informatik Easy Website!

Ta program vam omogoča hitro in enostavno namestitev celotnega spletnega okolja.

S tem programom lahko:
• Namestite XAMPP (Apache + MySQL + PHP + phpMyAdmin)
• Preverite stanje strežnikov
• Odprete lokalni spletni strežnik
• Ustvarite testno spletno stran
• Upravljate s spletnimi datotekami

Za začetek pojdite na zavihek 'Namestitev' in kliknite na 'Namesti XAMPP'.

Avtor: Elis Šabič
Email: informatik@informatik.tech
Spletna stran: https://informatik.tech/
"""
        
        text_widget = tk.Text(content_frame, height=15, font=("Arial", 11), wrap=tk.WORD)
        text_widget.pack(fill=tk.BOTH, expand=True)
        text_widget.insert(tk.INSERT, welcome_text)
        text_widget.config(state=tk.DISABLED)
        
        # Quick buttons
        button_frame = tk.Frame(tab)
        button_frame.pack(pady=10)
        
        quick_install_btn = tk.Button(button_frame, text="Hitra namestitev XAMPP", 
                                      command=self.install_xampp,
                                      bg="#27ae60", fg="white", font=("Arial", 12),
                                      padx=20, pady=10)
        quick_install_btn.pack(side=tk.LEFT, padx=5)
        
        check_status_btn = tk.Button(button_frame, text="Preveri stanje", 
                                     command=self.check_all_services,
                                     bg="#3498db", fg="white", font=("Arial", 12),
                                     padx=20, pady=10)
        check_status_btn.pack(side=tk.LEFT, padx=5)
    
    def create_install_tab(self):
        """Create installation tab"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="Namestitev")
        
        # Instructions
        instructions = tk.Label(tab, text="Izberite način namestitve:", 
                                font=("Arial", 14, "bold"))
        instructions.pack(pady=20)
        
        # Installation options frame
        options_frame = tk.Frame(tab)
        options_frame.pack(pady=20)
        
        # XAMPP Installation
        xampp_frame = tk.LabelFrame(options_frame, text="XAMPP (Priporočeno)", 
                                     font=("Arial", 12), padx=20, pady=20)
        xampp_frame.grid(row=0, column=0, padx=20, pady=10)
        
        xampp_text = """XAMPP vključuje:
• Apache Web Server
• MySQL Database
• PHP
• phpMyAdmin
• FileZilla FTP
• Mercury Mail"""
        
        tk.Label(xampp_frame, text=xampp_text, justify=tk.LEFT).pack()
        
        xampp_btn = tk.Button(xampp_frame, text="Namesti XAMPP", 
                              command=self.install_xampp,
                              bg="#27ae60", fg="white", font=("Arial", 11),
                              padx=20, pady=10)
        xampp_btn.pack(pady=10)
        
        # Manual Installation
        manual_frame = tk.LabelFrame(options_frame, text="Ročna namestitev", 
                                      font=("Arial", 12), padx=20, pady=20)
        manual_frame.grid(row=0, column=1, padx=20, pady=10)
        
        manual_text = """Namestite posamezne komponente:
• Apache Web Server
• MySQL Database
• PHP (izbira verzije)"""
        
        tk.Label(manual_frame, text=manual_text, justify=tk.LEFT).pack()
        
        manual_btn = tk.Button(manual_frame, text="Ročna namestitev", 
                               command=self.manual_installation,
                               bg="#3498db", fg="white", font=("Arial", 11),
                               padx=20, pady=10)
        manual_btn.pack(pady=10)
        
        # Progress area
        progress_frame = tk.LabelFrame(tab, text="Napredek", font=("Arial", 12))
        progress_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        self.progress_text = scrolledtext.ScrolledText(progress_frame, height=10)
        self.progress_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
    def create_monitor_tab(self):
        """Create monitoring tab"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="Monitoring")
        
        # Status indicators
        status_frame = tk.LabelFrame(tab, text="Stanje strežnikov", font=("Arial", 12))
        status_frame.pack(fill=tk.X, padx=20, pady=10)
        
        # Apache status
        apache_frame = tk.Frame(status_frame)
        apache_frame.pack(side=tk.LEFT, padx=20, pady=10)
        
        tk.Label(apache_frame, text="Apache:", font=("Arial", 11)).pack()
        self.apache_status = tk.Label(apache_frame, text="NEZNANO", 
                                      font=("Arial", 12, "bold"))
        self.apache_status.pack()
        
        # MySQL status
        mysql_frame = tk.Frame(status_frame)
        mysql_frame.pack(side=tk.LEFT, padx=20, pady=10)
        
        tk.Label(mysql_frame, text="MySQL:", font=("Arial", 11)).pack()
        self.mysql_status = tk.Label(mysql_frame, text="NEZNANO", 
                                     font=("Arial", 12, "bold"))
        self.mysql_status.pack()
        
        # PHP status
        php_frame = tk.Frame(status_frame)
        php_frame.pack(side=tk.LEFT, padx=20, pady=10)
        
        tk.Label(php_frame, text="PHP:", font=("Arial", 11)).pack()
        self.php_status = tk.Label(php_frame, text="NEZNANO", 
                                   font=("Arial", 12, "bold"))
        self.php_status.pack()
        
        # Control buttons
        control_frame = tk.Frame(tab)
        control_frame.pack(pady=10)
        
        start_btn = tk.Button(control_frame, text="Zaženi vse", 
                              command=self.start_all_services,
                              bg="#27ae60", fg="white", font=("Arial", 10))
        start_btn.grid(row=0, column=0, padx=5)
        
        stop_btn = tk.Button(control_frame, text="Ustavi vse", 
                             command=self.stop_all_services,
                             bg="#e74c3c", fg="white", font=("Arial", 10))
        stop_btn.grid(row=0, column=1, padx=5)
        
        restart_btn = tk.Button(control_frame, text="Ponovno zaženi", 
                                command=self.restart_all_services,
                                bg="#3498db", fg="white", font=("Arial", 10))
        restart_btn.grid(row=0, column=2, padx=5)
        
        # Logs
        log_frame = tk.LabelFrame(tab, text="Dnevniki", font=("Arial", 12))
        log_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=10)
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # Quick actions
        action_frame = tk.Frame(tab)
        action_frame.pack(pady=10)
        
        open_localhost_btn = tk.Button(action_frame, text="Odpri localhost", 
                                       command=self.open_localhost,
                                       bg="#9b59b6", fg="white", font=("Arial", 10))
        open_localhost_btn.pack(side=tk.LEFT, padx=5)
        
        open_phpmyadmin_btn = tk.Button(action_frame, text="Odpri phpMyAdmin", 
                                        command=self.open_phpmyadmin,
                                        bg="#e67e22", fg="white", font=("Arial", 10))
        open_phpmyadmin_btn.pack(side=tk.LEFT, padx=5)
    
    def create_tools_tab(self):
        """Create tools tab"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="Orodja")
        
        # File management
        file_frame = tk.LabelFrame(tab, text="Datoteke", font=("Arial", 12))
        file_frame.pack(fill=tk.X, padx=20, pady=10)
        
        open_htdocs_btn = tk.Button(file_frame, text="Odpri htdocs direktorij", 
                                    command=self.open_htdocs,
                                    bg="#27ae60", fg="white", font=("Arial", 10),
                                    padx=20, pady=10, width=25)
        open_htdocs_btn.pack(pady=10)
        
        open_xampp_btn = tk.Button(file_frame, text="Odpri XAMPP Control Panel", 
                                   command=self.open_xampp_control,
                                   bg="#3498db", fg="white", font=("Arial", 10),
                                   padx=20, pady=10, width=25)
        open_xampp_btn.pack(pady=10)
        
        # Test tools
        test_frame = tk.LabelFrame(tab, text="Testna okolja", font=("Arial", 12))
        test_frame.pack(fill=tk.X, padx=20, pady=10)
        
        create_test_btn = tk.Button(test_frame, text="Ustvari testno stran", 
                                    command=self.create_test_page,
                                    bg="#9b59b6", fg="white", font=("Arial", 10),
                                    padx=20, pady=10, width=25)
        create_test_btn.pack(pady=10)
        
        # Database tools
        db_frame = tk.LabelFrame(tab, text="Baza podatkov", font=("Arial", 12))
        db_frame.pack(fill=tk.X, padx=20, pady=10)
        
        create_db_btn = tk.Button(db_frame, text="Ustvari testno bazo", 
                                  command=self.create_test_database,
                                  bg="#e67e22", fg="white", font=("Arial", 10),
                                  padx=20, pady=10, width=25)
        create_db_btn.pack(pady=10)
        
        # System tools
        sys_frame = tk.LabelFrame(tab, text="Sistemska orodja", font=("Arial", 12))
        sys_frame.pack(fill=tk.X, padx=20, pady=10)
        
        clear_cache_btn = tk.Button(sys_frame, text="Počisti predpomnilnik", 
                                    command=self.clear_cache,
                                    bg="#95a5a6", fg="white", font=("Arial", 10),
                                    padx=20, pady=10, width=25)
        clear_cache_btn.pack(pady=10)
    
    def create_about_tab(self):
        """Create about tab"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="O programu")
        
        # Info
        info_frame = tk.Frame(tab)
        info_frame.pack(fill=tk.BOTH, expand=True, padx=30, pady=20)
        
        info_text = f"""
Program: Informatik Easy Website
Verzija: 1.0.0
Avtor: {self.developer}
Email: {self.email}
Spletna stran: {self.website}

Opis:
Ta program omogoča preprosto namestitev in upravljanje
spletnih strežnikov za lokalni razvoj.

Funkcionalnosti:
• Samodejna namestitev XAMPP
• Monitoring strežnikov
• Orodja za razvijalce
• Testna okolja

Licenca: Brezplačna za osebno in komercialno uporabo

© 2023 {self.developer}. Vse pravice pridržane.
"""
        
        text_widget = tk.Text(info_frame, height=20, font=("Arial", 11), wrap=tk.WORD)
        text_widget.pack(fill=tk.BOTH, expand=True)
        text_widget.insert(tk.INSERT, info_text)
        text_widget.config(state=tk.DISABLED)
        
        # Close button
        button_frame = tk.Frame(tab)
        button_frame.pack(pady=20)
        
        close_btn = tk.Button(button_frame, text="Zapri program", 
                              command=self.quit_app,
                              bg="#e74c3c", fg="white", font=("Arial", 12),
                              padx=30, pady=10)
        close_btn.pack()
    
    def log_message(self, message):
        """Log message to progress text"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        formatted = f"[{timestamp}] {message}\n"
        
        if hasattr(self, 'progress_text'):
            self.progress_text.insert(tk.END, formatted)
            self.progress_text.see(tk.END)
            self.progress_text.update()
    
    def update_status_bar(self, message):
        """Update status bar"""
        self.status_bar.config(text=message)
        self.root.update()
    
    def check_existing_installations(self):
        """Check for existing XAMPP/WAMP installations"""
        self.update_status_bar("Preverjam obstoječe namestitve...")
        
        # Common installation paths
        xampp_paths = [
            "C:\\xampp",
            "D:\\xampp",
            os.path.expanduser("~\\xampp"),
        ]
        
        for path in xampp_paths:
            if os.path.exists(path):
                self.log_message(f"Našel XAMPP v: {path}")
                self.apache_status.config(text="NAMEŠČEN", fg="green")
                self.mysql_status.config(text="NAMEŠČEN", fg="green")
                self.php_status.config(text="NAMEŠČEN", fg="green")
                return True
        
        self.log_message("XAMPP ni nameščen.")
        return False
    
    def start_monitoring(self):
        """Start monitoring services"""
        self.update_status_bar("Začenjam monitoring...")
        threading.Thread(target=self.monitor_loop, daemon=True).start()
    
    def monitor_loop(self):
        """Monitor services loop"""
        while True:
            self.check_services()
            time.sleep(5)
    
    def check_services(self):
        """Check service status"""
        try:
            # Check Apache (port 80)
            apache_up = self.check_port(80)
            self.apache_running = apache_up
            
            # Update GUI
            if apache_up:
                self.apache_status.config(text="ZAGONJEN", fg="green")
            else:
                self.apache_status.config(text="USTAVLJEN", fg="red")
            
            # Check MySQL (port 3306)
            mysql_up = self.check_port(3306)
            self.mysql_running = mysql_up
            
            if mysql_up:
                self.mysql_status.config(text="ZAGONJEN", fg="green")
            else:
                self.mysql_status.config(text="USTAVLJEN", fg="red")
            
            # Check PHP (simplified)
            php_installed = self.check_php_installed()
            if php_installed:
                self.php_status.config(text="NAMEŠČEN", fg="green")
            else:
                self.php_status.config(text="NI NAMEŠČEN", fg="red")
                
        except Exception as e:
            self.log_message(f"Napaka pri preverjanju: {e}")
    
    def check_port(self, port):
        """Check if port is open"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex(('localhost', port))
            sock.close()
            return result == 0
        except:
            return False
    
    def check_php_installed(self):
        """Check if PHP is installed"""
        # Check common PHP paths
        php_paths = [
            "C:\\xampp\\php\\php.exe",
            "C:\\php\\php.exe",
            "C:\\Program Files\\PHP\\php.exe",
        ]
        
        for path in php_paths:
            if os.path.exists(path):
                return True
        return False
    
    def install_xampp(self):
        """Install XAMPP"""
        self.update_status_bar("Začenjam namestitev XAMPP...")
        self.log_message("Namestitev XAMPP...")
        
        # Open XAMPP download page
        webbrowser.open("https://www.apachefriends.org/download.html")
        
        self.log_message("Odprta spletna stran za prenos XAMPP.")
        self.log_message("Prosimo, prenesite in zaženite XAMPP installer.")
        
        messagebox.showinfo("Namestitev XAMPP",
                          "1. Odprite spletno stran za prenos XAMPP\n"
                          "2. Prenesite XAMPP za Windows\n"
                          "3. Zaženite installer in sledite navodilom\n"
                          "4. Po namestitvi zaženite XAMPP Control Panel")
    
    def manual_installation(self):
        """Manual installation guide"""
        self.log_message("Ročna namestitev...")
        
        messagebox.showinfo("Ročna namestitev",
                          "Za ročno namestitev sledite tem korakom:\n\n"
                          "1. Prenesite Apache: https://httpd.apache.org/\n"
                          "2. Prenesite MySQL: https://dev.mysql.com/\n"
                          "3. Prenesite PHP: https://windows.php.net/download/\n\n"
                          "Namestite vsako komponento posebej in jih konfigurirajte.")
    
    def check_all_services(self):
        """Check all services"""
        self.update_status_bar("Preverjam strežnike...")
        self.check_services()
        self.log_message("Preverjanje strežnikov končano.")
    
    def start_all_services(self):
        """Start all services"""
        self.update_status_bar("Zaženem strežnike...")
        self.log_message("Zaganjam Apache in MySQL...")
        
        # Try to start XAMPP services
        try:
            xampp_control = "C:\\xampp\\xampp-control.exe"
            if os.path.exists(xampp_control):
                subprocess.Popen([xampp_control])
                self.log_message("Zagnan XAMPP Control Panel.")
            else:
                self.log_message("XAMPP Control Panel ni najden.")
        except Exception as e:
            self.log_message(f"Napaka pri zagonu: {e}")
    
    def stop_all_services(self):
        """Stop all services"""
        self.update_status_bar("Ustavljam strežnike...")
        self.log_message("Ustavljam Apache in MySQL...")
        
        # This would require admin rights to stop services
        messagebox.showinfo("Ustavi strežnike",
                          "Za ustavitev strežnikov:\n"
                          "1. Odprite XAMPP Control Panel\n"
                          "2. Kliknite 'Stop' pri Apache in MySQL\n"
                          "3. Ali pa uporabite Windows Services")
    
    def restart_all_services(self):
        """Restart all services"""
        self.update_status_bar("Ponovno zaženem strežnike...")
        self.log_message("Ponovno zaganjam strežnike...")
        
        messagebox.showinfo("Ponovni zagon",
                          "Za ponovni zagon strežnikov:\n"
                          "1. Odprite XAMPP Control Panel\n"
                          "2. Kliknite 'Stop', nato 'Start' pri Apache in MySQL")
    
    def open_localhost(self):
        """Open localhost in browser"""
        try:
            webbrowser.open("http://localhost")
            self.log_message("Odprto http://localhost")
        except Exception as e:
            self.log_message(f"Napaka: {e}")
    
    def open_phpmyadmin(self):
        """Open phpMyAdmin"""
        try:
            webbrowser.open("http://localhost/phpmyadmin")
            self.log_message("Odprto http://localhost/phpmyadmin")
        except Exception as e:
            self.log_message(f"Napaka: {e}")
    
    def open_htdocs(self):
        """Open htdocs directory"""
        htdocs_paths = [
            "C:\\xampp\\htdocs",
            "C:\\wamp64\\www",
            "C:\\wamp\\www",
        ]
        
        for path in htdocs_paths:
            if os.path.exists(path):
                os.startfile(path)
                self.log_message(f"Odprt direktorij: {path}")
                return
        
        # Create directory if not exists
        default_path = "C:\\xampp\\htdocs"
        os.makedirs(default_path, exist_ok=True)
        os.startfile(default_path)
        self.log_message(f"Ustvarjen in odprt direktorij: {default_path}")
    
    def open_xampp_control(self):
        """Open XAMPP Control Panel"""
        xampp_paths = [
            "C:\\xampp\\xampp-control.exe",
            "C:\\xampp\\xampp-control",
        ]
        
        for path in xampp_paths:
            if os.path.exists(path):
                subprocess.Popen([path])
                self.log_message("Zagnan XAMPP Control Panel")
                return
        
        self.log_message("XAMPP Control Panel ni najden.")
        messagebox.showwarning("XAMPP ni najden", 
                              "XAMPP ni nameščen ali pot ni pravilna.")
    
    def create_test_page(self):
        """Create test webpage"""
        try:
            # Determine htdocs path
            htdocs_path = "C:\\xampp\\htdocs"
            if not os.path.exists(htdocs_path):
                os.makedirs(htdocs_path, exist_ok=True)
            
            # Create index.php
            index_content = """<!DOCTYPE html>
<html lang="sl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Testna stran - Informatik Easy Website</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 50px; }
        .success { background: #27ae60; color: white; padding: 20px; border-radius: 10px; }
        .info { background: #3498db; color: white; padding: 20px; border-radius: 10px; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="success">
        <h1>✅ Spletni strežnik deluje!</h1>
        <p>Testna stran ustvarjena z Informatik Easy Website</p>
    </div>
    
    <div class="info">
        <h2>PHP informacije:</h2>
        <?php
            echo "PHP verzija: " . phpversion() . "<br>";
            echo "Datum: " . date('d.m.Y H:i:s') . "<br>";
            
            // Test MySQL connection
            echo "<h3>Test MySQL povezave:</h3>";
            try {
                $conn = new mysqli("localhost", "root", "");
                if ($conn->connect_error) {
                    echo "Napaka: " . $conn->connect_error;
                } else {
                    echo "✅ Povezava z MySQL uspešna!";
                    $conn->close();
                }
            } catch(Exception $e) {
                echo "❌ " . $e->getMessage();
            }
        ?>
    </div>
    
    <h3>Avtor: Elis Šabič</h3>
    <p>Email: informatik@informatik.tech</p>
    <p>Spletna stran: <a href="https://informatik.tech/">https://informatik.tech/</a></p>
</body>
</html>"""
            
            index_path = os.path.join(htdocs_path, "index.php")
            with open(index_path, "w", encoding="utf-8") as f:
                f.write(index_content)
            
            self.log_message(f"Testna stran ustvarjena: {index_path}")
            
            # Open in browser
            webbrowser.open("http://localhost")
            
            messagebox.showinfo("Uspešno", 
                              f"Testna stran uspešno ustvarjena!\n\n"
                              f"Lokacija: {index_path}\n"
                              f"Odprto v brskalniku: http://localhost")
            
        except Exception as e:
            self.log_message(f"Napaka: {e}")
            messagebox.showerror("Napaka", f"Napaka pri ustvarjanju testne strani: {e}")
    
    def create_test_database(self):
        """Create test database"""
        self.log_message("Ustvarjam testno bazo podatkov...")
        
        messagebox.showinfo("Testna baza podatkov",
                          "Za ustvarjanje testne baze:\n\n"
                          "1. Odprite http://localhost/phpmyadmin\n"
                          "2. Prijavite se z uporabniškim imenom: root (brez gesla)\n"
                          "3. Kliknite 'Nova baza'\n"
                          "4. Vnesite ime: test_db\n"
                          "5. Kliknite 'Ustvari'")
    
    def clear_cache(self):
        """Clear browser cache"""
        self.log_message("Čiščenje predpomnilnika...")
        
        # Clear browser cache locations
        cache_paths = [
            os.path.expanduser("~\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache"),
            os.path.expanduser("~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cache"),
        ]
        
        cleared = 0
        for path in cache_paths:
            if os.path.exists(path):
                try:
                    # Note: In production, you would properly clear cache
                    self.log_message(f"Počiščeno: {path}")
                    cleared += 1
                except:
                    pass
        
        if cleared > 0:
            messagebox.showinfo("Uspešno", "Predpomnilnik uspešno očiščen!")
        else:
            messagebox.showinfo("Informacija", 
                              "Za čiščenje predpomnilnika:\n"
                              "1. Odprite brskalnik\n"
                              "2. Pojdite v nastavitve\n"
                              "3. Poiščite 'Počisti brskalne podatke'")
    
    def minimize_to_tray(self):
        """Minimize to system tray (simplified)"""
        self.root.withdraw()
        self.update_status_bar("Minimizirano v taskbar")
        
        # Show message
        messagebox.showinfo("Minimizirano", 
                          "Program je še vedno zagnan v taskbarju.\n"
                          "Ponovno odprite iz taskbarja.")
    
    def quit_app(self):
        """Quit application"""
        if messagebox.askyesno("Zapri", "Ali ste prepričani, da želite zapreti program?"):
            self.root.quit()
            self.root.destroy()

def is_admin():
    """Check if program is running as administrator"""
    try:
        import ctypes
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except:
        return False

def run_as_admin():
    """Restart program as administrator"""
    try:
        import ctypes
        ctypes.windll.shell32.ShellExecuteW(
            None, "runas", sys.executable, " ".join(sys.argv), None, 1
        )
        return True
    except:
        return False

def main():
    """Main function"""
    # Create root window
    root = tk.Tk()
    
    # Check if admin rights are needed
    # For this application, admin rights are not strictly required
    # but can be helpful for some operations
    
    # Show admin warning if not admin
    if not is_admin():
        response = messagebox.askyesno(
            "Administratorske pravice",
            "Za nekatere operacije so priporočene administratorske pravice.\n\n"
            "Želite zagnati program kot administrator?"
        )
        
        if response:
            if run_as_admin():
                root.destroy()
                return
            else:
                messagebox.showwarning(
                    "Administrator",
                    "Ne morem zagnati kot administrator. Program bo nadaljeval s standardnimi pravicami."
                )
    
    # Create and run application
    app = EasyWebsiteInstaller(root)
    root.mainloop()

if __name__ == "__main__":
    main()