<?php

/**
 * Social Networks Plugin
 *
 * @name: Social Networks
 * @slug: social-networks
 * @version: 1.0.0
 * @description: Плагін для управління соціальними мережами
 * @author: Flowaxy Team
 * @author_url: https://flowaxy.com
 * @requires: 1.0.0
 * @tested: 1.0.0
 * @package: SocialNetworks
 *
 * FLOWAXY CMS 1.0.0 Stable
 */

declare(strict_types=1);

use Flowaxy\Support\Base\BasePlugin;

final class SocialNetworksPlugin extends BasePlugin
{
    public function registerHooks(): void
    {
        $this->registerFilter('admin_menu', function (array $menu): array {
            $adminUrl = function_exists('admin_url') ? admin_url('social-networks') : '/admin/social-networks';
            $menu[] = [
                'text' => 'Социальные сети',
                'title' => 'Управление социальными сетями',
                'icon' => 'fas fa-share-alt',
                'href' => $adminUrl,
                'page' => 'social-networks',
                'permission' => 'admin.access',
                'order' => 46,
            ];
            return $menu;
        });

        $this->registerFilter('theme_social_networks', function (array $networks): array {
            $settings = $this->getSettings();
            if (($settings['status'] ?? 'activated') === 'deactivated') {
                return $networks;
            }
            return array_merge($networks, $this->getSocialNetworks());
        });

        $this->registerFilter('theme_social_networks_settings', function (array $settings): array {
            return array_merge($settings, $this->getSettings());
        });
    }

    public function registerRoutes(): void
    {
        $this->registerHook('admin_routes', function ($router) {
            $pageFile = __DIR__ . DS . 'admin' . DS . 'pages' . DS . 'social-networks.php';
            if (file_exists($pageFile) && is_readable($pageFile)) {
                require_once $pageFile;
            }
            if ($router && method_exists($router, 'add')) {
                $router->add(['GET', 'POST'], 'social-networks', 'admin_social_networks_page', ['middleware' => ['admin.auth']]);
            }
        });
    }

    private function getSocialNetworks(): array
    {
        $configFile = __DIR__ . DS . 'config' . DS . 'networks.ini';
        if (!file_exists($configFile)) {
            return [];
        }

        $networks = [];
        try {
            $config = parse_ini_file($configFile, true);
            if (!is_array($config)) {
                return [];
            }

            foreach ($config as $sectionName => $sectionData) {
                if (!is_array($sectionData) || strpos($sectionName, 'networks.') !== 0) {
                    continue;
                }

                $id = substr($sectionName, strlen('networks.'));
                $enabled = isset($sectionData['enabled']) ? (bool)(int)$sectionData['enabled'] : true;
                if (!$enabled) {
                    continue;
                }

                $networks[] = [
                    'id' => (string)$id,
                    'name' => $sectionData['name'] ?? $id,
                    'url' => $sectionData['url'] ?? '#',
                    'icon' => $sectionData['icon'] ?? 'fas fa-link',
                    'order' => (int)($sectionData['order'] ?? 999),
                    'enabled' => $enabled,
                ];
            }
        } catch (\Throwable $e) {
            return [];
        }

        usort($networks, fn($a, $b) => $a['order'] <=> $b['order']);
        return $networks;
    }

    public function activate(): void
    {
        parent::activate();
        $this->initializeDefaultNetworks();
    }

    public function deactivate(): void
    {
        parent::deactivate();
    }

    private function initializeDefaultNetworks(): void
    {
        $configFile = __DIR__ . DS . 'config' . DS . 'networks.ini';
        if (file_exists($configFile)) {
            return;
        }

        $defaultNetworks = [
            'vk' => ['name' => 'VKontakte', 'url' => 'https://vk.com', 'icon' => 'fab fa-vk', 'order' => 1],
            'twitter' => ['name' => 'Twitter/X', 'url' => 'https://twitter.com', 'icon' => 'fab fa-twitter', 'order' => 2],
            'facebook' => ['name' => 'Facebook', 'url' => 'https://facebook.com', 'icon' => 'fab fa-facebook', 'order' => 3],
        ];

        $iniContent = "; Social Networks Configuration\n; Auto-generated by Social Networks Plugin\n\n[networks]\n\n";
        foreach ($defaultNetworks as $id => $network) {
            $iniContent .= "[networks.{$id}]\n";
            $iniContent .= "name = \"{$network['name']}\"\n";
            $iniContent .= "url = \"{$network['url']}\"\n";
            $iniContent .= "icon = \"{$network['icon']}\"\n";
            $iniContent .= "order = {$network['order']}\n";
            $iniContent .= "enabled = 1\n\n";
        }

        $configDir = dirname($configFile);
        if (!is_dir($configDir)) {
            mkdir($configDir, 0755, true);
        }
        file_put_contents($configFile, $iniContent);
    }
}
