<?php
/**
 * Klasa ExternalLinks - zarządzanie linkami zewnętrznymi w menu
 */

class ExternalLinks
{
    private Database $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
        $this->ensureTable();
    }
    
    /**
     * Utwórz tabelę jeśli nie istnieje
     */
    private function ensureTable(): void
    {
        $this->db->execute("
            CREATE TABLE IF NOT EXISTS external_links (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name VARCHAR(100) NOT NULL,
                url VARCHAR(500) NOT NULL,
                icon VARCHAR(50) DEFAULT 'bi-link-45deg',
                sort_order INTEGER DEFAULT 0,
                is_active INTEGER DEFAULT 1,
                open_new_tab INTEGER DEFAULT 1,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");
        
        // Indeks na sort_order
        $this->db->execute("
            CREATE INDEX IF NOT EXISTS idx_external_links_sort ON external_links(sort_order, is_active)
        ");
    }
    
    /**
     * Pobierz wszystkie linki
     */
    public function getAll(): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM external_links ORDER BY sort_order ASC, name ASC"
        );
    }
    
    /**
     * Pobierz aktywne linki (do menu)
     */
    public function getActive(): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM external_links WHERE is_active = 1 ORDER BY sort_order ASC, name ASC"
        );
    }
    
    /**
     * Pobierz link po ID
     */
    public function getById(int $id): ?array
    {
        return $this->db->fetchOne(
            "SELECT * FROM external_links WHERE id = :id",
            ['id' => $id]
        );
    }
    
    /**
     * Utwórz nowy link
     */
    public function create(array $data): array
    {
        // Walidacja
        $name = trim($data['name'] ?? '');
        if (strlen($name) < 1) {
            return ['success' => false, 'error' => 'Nazwa linku jest wymagana.'];
        }
        
        $url = trim($data['url'] ?? '');
        if (strlen($url) < 1) {
            return ['success' => false, 'error' => 'URL jest wymagany.'];
        }
        
        // Walidacja URL
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return ['success' => false, 'error' => 'Nieprawidłowy format URL.'];
        }
        
        $icon = trim($data['icon'] ?? 'bi-link-45deg');
        $sortOrder = (int)($data['sort_order'] ?? 0);
        $isActive = isset($data['is_active']) ? 1 : 0;
        $openNewTab = isset($data['open_new_tab']) ? 1 : 0;
        
        $id = $this->db->insert(
            "INSERT INTO external_links (name, url, icon, sort_order, is_active, open_new_tab) 
             VALUES (:name, :url, :icon, :sort_order, :is_active, :open_new_tab)",
            [
                'name' => $name,
                'url' => $url,
                'icon' => $icon,
                'sort_order' => $sortOrder,
                'is_active' => $isActive,
                'open_new_tab' => $openNewTab
            ]
        );
        
        return ['success' => true, 'id' => $id];
    }
    
    /**
     * Aktualizuj link
     */
    public function update(int $id, array $data): array
    {
        $link = $this->getById($id);
        if (!$link) {
            return ['success' => false, 'error' => 'Link nie istnieje.'];
        }
        
        // Walidacja
        $name = trim($data['name'] ?? '');
        if (strlen($name) < 1) {
            return ['success' => false, 'error' => 'Nazwa linku jest wymagana.'];
        }
        
        $url = trim($data['url'] ?? '');
        if (strlen($url) < 1) {
            return ['success' => false, 'error' => 'URL jest wymagany.'];
        }
        
        // Walidacja URL
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return ['success' => false, 'error' => 'Nieprawidłowy format URL.'];
        }
        
        $icon = trim($data['icon'] ?? 'bi-link-45deg');
        $sortOrder = (int)($data['sort_order'] ?? 0);
        $isActive = isset($data['is_active']) ? 1 : 0;
        $openNewTab = isset($data['open_new_tab']) ? 1 : 0;
        
        $this->db->execute(
            "UPDATE external_links 
             SET name = :name, url = :url, icon = :icon, sort_order = :sort_order, 
                 is_active = :is_active, open_new_tab = :open_new_tab, updated_at = datetime('now')
             WHERE id = :id",
            [
                'id' => $id,
                'name' => $name,
                'url' => $url,
                'icon' => $icon,
                'sort_order' => $sortOrder,
                'is_active' => $isActive,
                'open_new_tab' => $openNewTab
            ]
        );
        
        return ['success' => true];
    }
    
    /**
     * Usuń link
     */
    public function delete(int $id): array
    {
        $link = $this->getById($id);
        if (!$link) {
            return ['success' => false, 'error' => 'Link nie istnieje.'];
        }
        
        $this->db->execute(
            "DELETE FROM external_links WHERE id = :id",
            ['id' => $id]
        );
        
        return ['success' => true];
    }
    
    /**
     * Przełącz aktywność
     */
    public function toggleActive(int $id): array
    {
        $link = $this->getById($id);
        if (!$link) {
            return ['success' => false, 'error' => 'Link nie istnieje.'];
        }
        
        $newStatus = $link['is_active'] ? 0 : 1;
        
        $this->db->execute(
            "UPDATE external_links SET is_active = :status, updated_at = datetime('now') WHERE id = :id",
            ['id' => $id, 'status' => $newStatus]
        );
        
        return ['success' => true, 'is_active' => $newStatus];
    }
    
    /**
     * Aktualizuj kolejność
     */
    public function updateOrder(array $order): array
    {
        foreach ($order as $position => $id) {
            $this->db->execute(
                "UPDATE external_links SET sort_order = :sort_order WHERE id = :id",
                ['id' => (int)$id, 'sort_order' => $position]
            );
        }
        
        return ['success' => true];
    }
    
    /**
     * Pobierz dostępne ikony Bootstrap
     */
    public static function getAvailableIcons(): array
    {
        return [
            'bi-link-45deg' => 'Link',
            'bi-globe' => 'Globus',
            'bi-box-arrow-up-right' => 'Zewnętrzny',
            'bi-house' => 'Dom',
            'bi-gear' => 'Ustawienia',
            'bi-tools' => 'Narzędzia',
            'bi-file-earmark' => 'Dokument',
            'bi-folder' => 'Folder',
            'bi-cloud' => 'Chmura',
            'bi-database' => 'Baza danych',
            'bi-server' => 'Serwer',
            'bi-hdd-network' => 'Sieć',
            'bi-router' => 'Router',
            'bi-wifi' => 'WiFi',
            'bi-tv' => 'TV',
            'bi-camera-video' => 'Wideo',
            'bi-play-circle' => 'Play',
            'bi-collection-play' => 'Playlisty',
            'bi-music-note-list' => 'Muzyka',
            'bi-broadcast' => 'Transmisja',
            'bi-diagram-3' => 'Diagram',
            'bi-graph-up' => 'Wykres',
            'bi-bar-chart' => 'Statystyki',
            'bi-pie-chart' => 'Raport',
            'bi-calculator' => 'Kalkulator',
            'bi-currency-dollar' => 'Finanse',
            'bi-credit-card' => 'Płatności',
            'bi-cart' => 'Sklep',
            'bi-bag' => 'Torba',
            'bi-shop' => 'Sklep',
            'bi-people' => 'Ludzie',
            'bi-person' => 'Osoba',
            'bi-building' => 'Budynek',
            'bi-telephone' => 'Telefon',
            'bi-envelope' => 'Email',
            'bi-chat' => 'Czat',
            'bi-bell' => 'Powiadomienia',
            'bi-bookmark' => 'Zakładka',
            'bi-star' => 'Gwiazda',
            'bi-heart' => 'Serce',
            'bi-lightning' => 'Błyskawica',
            'bi-fire' => 'Ogień',
            'bi-shield' => 'Tarcza',
            'bi-lock' => 'Kłódka',
            'bi-key' => 'Klucz',
            'bi-eye' => 'Oko',
            'bi-search' => 'Szukaj',
            'bi-filter' => 'Filtr',
            'bi-sliders' => 'Suwaki',
            'bi-list' => 'Lista',
            'bi-grid' => 'Siatka',
            'bi-layers' => 'Warstwy',
            'bi-puzzle' => 'Puzzle',
            'bi-cpu' => 'Procesor',
            'bi-memory' => 'Pamięć',
            'bi-usb-drive' => 'USB',
            'bi-terminal' => 'Terminal',
            'bi-code-slash' => 'Kod',
            'bi-bug' => 'Bug',
            'bi-github' => 'GitHub',
            'bi-youtube' => 'YouTube',
            'bi-facebook' => 'Facebook',
            'bi-twitter' => 'Twitter',
            'bi-instagram' => 'Instagram',
            'bi-telegram' => 'Telegram',
            'bi-discord' => 'Discord',
            'bi-whatsapp' => 'WhatsApp',
        ];
    }
}
