<?php

namespace RtmBusiness\PostSync;

use Exception;
use RtmBusiness\PostSync\Pages\PermissionsPage;
use RtmBusiness\PostSync\Pages\LoggerPage;
use RtmBusiness\PostSync\Rest\SettingsApi;
use RtmBusiness\PostSync\Pages\SettingsPage;
use WordpressModels\Assets;
use WordpressModels\Traits\SingletonTrait;
use Inpsyde\Wonolog;

class Core
{

    use SingletonTrait;

    const PLUGIN_VERSION = '0.1.5';

    private Assets $assets;

    private function __construct()
    {
        add_action('init', [$this, 'init']);
        $this->initializeAssets();

        $defaultSettings = [
            'postsync_enabled_post_types' => ['post', 'page'],
            'postsync_sync_metadata' => true,
            'postsync_sync_taxonomies' => true,
            'postsync_copy_media' => true,
        ];

        foreach ($defaultSettings as $option => $defaultValue) {
            if (!get_site_option($option)) {
                update_site_option($option, $defaultValue);
            }
        }
        
        SyncController::instance();
    }

    /**
     * @return void Trigger by init hook
     */
    public function init()
    {
        //Initialize REST API
        SettingsApi::instance();

        if (defined('Inpsyde\Wonolog\LOG')) {
            add_filter('wonolog.channels', function ($channels) {
                $channels[] = Logger::CHANNEL;
                return $channels;
            });
            Wonolog\bootstrap(new LogHandler());
        }

        if (is_admin()) {
            //Pages
            new SettingsPage($this->assets);
            new LoggerPage($this->assets);
            new PermissionsPage($this->assets);

            //Permissions
            new PermissionController($this->assets);

            //Metabox for every post type
            $enabledPostTypes = get_site_option('postsync_enabled_post_types');
            foreach ($enabledPostTypes as $postType) {
                new MetaBoxHandler($this->assets, $postType);
            }
        }
    }

    /**
     * Triggered by hook when plugin is activated
     * @return void
     * @throws Exception
     */
    public static function activatePlugin()
    {
        if (!is_multisite()) {
            throw new Exception('A wordpress network installation is required. This plugin does not support single installations.');
        }

        self::checkMigrations();
    }


    /**
     * Triggered by hook when plugin is uninstalled
     * @return void
     * @throws Exception
     */
    public static function uninstallPlugin()
    {
        global $wpdb;

        $meta_keys = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT meta_key FROM $wpdb->sitemeta WHERE meta_key LIKE %s AND site_id = %d",
                'postsync%', // This is the prefix you are looking for
                get_current_network_id() // This ensures we're only getting options for the current network
            )
        );

        foreach ($meta_keys as $optionName) {
            delete_site_option($optionName);
        }

        $migrator = Migrator::instance();
        $migrations = $migrator->getMigrations(false, 1);
        foreach ($migrations as $migration) {
            $migrator->rollback($migration);
        }
    }

    /**
     * Checks if migration is available and shows message on failed migration
     * @return void
     * @throws Exception
     */
    public static function checkMigrations(): void
    {
        // Check for migrations if version is updated
        $version = get_site_option('postsync_plugin_version');
        if (empty($version) || version_compare(self::PLUGIN_VERSION, $version, '>')) {
            Migrator::instance()->run();
        }
    }


    /**
     * @return void Load the assets directory to be used in the plugin
     */
    private function initializeAssets()
    {
        $baseDir = plugin_dir_path(__DIR__) . 'assets/build/';
        $baseUrl = plugin_dir_url(__DIR__) . 'assets/build/';
        $this->assets = new Assets($baseDir, $baseUrl);
        $this->assets->addTimberTemplateLocation(plugin_dir_path(__DIR__) . 'templates/');
        $this->assets->addTimberTemplateLocation(plugin_dir_path(__DIR__) . 'templates/admin/');
    }
}
