<?php
/**
 * Kontroler Linków Zewnętrznych
 */

require_once __DIR__ . '/BaseController.php';
require_once PANEL_PATH . '/classes/ExternalLinks.php';

class LinksController extends BaseController
{
    private ExternalLinks $linksModel;
    private AuditLog $auditLog;
    
    public function __construct()
    {
        parent::__construct();
        
        // Tylko admin ma dostęp
        if (!$this->auth->isAdmin()) {
            $this->redirect('dashboard', 'danger', 'Brak dostępu.');
            exit;
        }
        
        $this->linksModel = new ExternalLinks();
        $this->auditLog = new AuditLog();
    }
    
    /**
     * Lista linków
     */
    public function index(): void
    {
        $links = $this->linksModel->getAll();
        $icons = ExternalLinks::getAvailableIcons();
        
        $this->render('admin/links.tpl', [
            'pageTitle' => 'Linki zewnętrzne',
            'links' => $links,
            'icons' => $icons
        ]);
    }
    
    /**
     * Dodaj link
     */
    public function add(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('admin/links');
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $data = [
            'name' => post('name'),
            'url' => post('url'),
            'icon' => post('icon', 'bi-link-45deg'),
            'sort_order' => post('sort_order', 0),
            'is_active' => post('is_active'),
            'open_new_tab' => post('open_new_tab')
        ];
        
        $result = $this->linksModel->create($data);
        
        if ($result['success']) {
            // Audit log
            $this->auditLog->log(
                'external_link',
                $result['id'],
                AuditLog::ACTION_CREATE,
                null,
                ['name' => $data['name'], 'url' => $data['url'], 'icon' => $data['icon']]
            );
            
            if (isAjax()) {
                $this->json(['success' => true, 'id' => $result['id']]);
            } else {
                $this->redirect('admin/links', 'success', 'Link został dodany.');
            }
        } else {
            if (isAjax()) {
                $this->json($result);
            } else {
                $this->redirect('admin/links', 'danger', $result['error']);
            }
        }
    }
    
    /**
     * Edytuj link
     */
    public function edit(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('admin/links');
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $id = (int)post('id');
        $oldLink = $this->linksModel->getById($id);
        
        if (!$oldLink) {
            if (isAjax()) {
                $this->json(['success' => false, 'error' => 'Link nie istnieje.']);
            } else {
                $this->redirect('admin/links', 'danger', 'Link nie istnieje.');
            }
            return;
        }
        
        $data = [
            'name' => post('name'),
            'url' => post('url'),
            'icon' => post('icon', 'bi-link-45deg'),
            'sort_order' => post('sort_order', 0),
            'is_active' => post('is_active'),
            'open_new_tab' => post('open_new_tab')
        ];
        
        $result = $this->linksModel->update($id, $data);
        
        if ($result['success']) {
            // Audit log
            $this->auditLog->log(
                'external_link',
                $id,
                AuditLog::ACTION_UPDATE,
                ['name' => $oldLink['name'], 'url' => $oldLink['url'], 'icon' => $oldLink['icon']],
                ['name' => $data['name'], 'url' => $data['url'], 'icon' => $data['icon']]
            );
            
            if (isAjax()) {
                $this->json(['success' => true]);
            } else {
                $this->redirect('admin/links', 'success', 'Link został zaktualizowany.');
            }
        } else {
            if (isAjax()) {
                $this->json($result);
            } else {
                $this->redirect('admin/links', 'danger', $result['error']);
            }
        }
    }
    
    /**
     * Usuń link
     */
    public function delete(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('admin/links');
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $id = (int)post('id');
        $link = $this->linksModel->getById($id);
        
        if (!$link) {
            if (isAjax()) {
                $this->json(['success' => false, 'error' => 'Link nie istnieje.']);
            } else {
                $this->redirect('admin/links', 'danger', 'Link nie istnieje.');
            }
            return;
        }
        
        $result = $this->linksModel->delete($id);
        
        if ($result['success']) {
            // Audit log
            $this->auditLog->log(
                'external_link',
                $id,
                AuditLog::ACTION_DELETE,
                ['name' => $link['name'], 'url' => $link['url']],
                null
            );
            
            if (isAjax()) {
                $this->json(['success' => true]);
            } else {
                $this->redirect('admin/links', 'success', 'Link został usunięty.');
            }
        } else {
            if (isAjax()) {
                $this->json($result);
            } else {
                $this->redirect('admin/links', 'danger', $result['error']);
            }
        }
    }
    
    /**
     * Przełącz aktywność
     */
    public function toggleActive(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('admin/links');
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $id = (int)post('id');
        $result = $this->linksModel->toggleActive($id);
        
        if (isAjax()) {
            $this->json($result);
        } else {
            if ($result['success']) {
                $this->redirect('admin/links', 'success', 'Status linku został zmieniony.');
            } else {
                $this->redirect('admin/links', 'danger', $result['error']);
            }
        }
    }
    
    /**
     * Aktualizuj kolejność (AJAX)
     */
    public function updateOrder(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(['success' => false, 'error' => 'Nieprawidłowa metoda.']);
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $order = post('order');
        if (!is_array($order)) {
            $this->json(['success' => false, 'error' => 'Nieprawidłowe dane.']);
            return;
        }
        
        $result = $this->linksModel->updateOrder($order);
        $this->json($result);
    }
}
