<?php

namespace EstatebudConnect;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Configs\App;
use EstatebudConnect\Controllers\Admin;
use EstatebudConnect\Controllers\CurrencySelector;
use EstatebudConnect\Controllers\Favorites;
use EstatebudConnect\Controllers\Form;
use EstatebudConnect\Controllers\Frontend;
use EstatebudConnect\Controllers\Listing;
use EstatebudConnect\Controllers\Listings;
use EstatebudConnect\Core\RewriteRules;
use EstatebudConnect\Core\Compiler;
use EstatebudConnect\Core\Locale;
use EstatebudConnect\Core\OptionsAPI;
use EstatebudConnect\Core\Cache;
use EstatebudConnect\Core\Log;
use EstatebudConnect\Core\Update;
use Composer\InstalledVersions;

class Plugin
{
    private static $build_tools = false;
    private static $uninstall_pending = false;

    public static function activate() {}

    public static function deactivate()
    {
        Cache::instance()->flush();
    }

    public static function uninstall()
    {
        static::$uninstall_pending = true;
        Cache::instance()->flush();
    }

    public static function init()
    {
        Admin::instance();
        CurrencySelector::instance();
        Favorites::instance();
        Form::instance();
        Frontend::instance();
        Listing::instance();
        Listings::instance();
        RewriteRules::instance();
        Locale::instance();
        Update::instance();
        static::init_dev_features();

        add_action('init', function () {
            flush_rewrite_rules();
        });
    }

    public static function has_build_tools()
    {
        return static::$build_tools;
    }
    
    public static function is_uninstalling()
    {
        return static::$uninstall_pending;
    }

    public static function init_dev_features()
    {
        $root_package = InstalledVersions::getRootPackage();
        $current_mode = (bool) $root_package['dev'] ?? false;
        if ($current_mode === true) {
            static::$build_tools = true;

            add_action('init', [Compiler::class, 'compile']);
            add_filter('script_loader_tag', function ($tag, $handle) {
                if (str_contains($tag, App::SLUG . '/app/') && !str_contains($tag, 'type="module"')) {
                    return str_replace('<script', '<script type="module"', $tag);
                }
                return $tag;
            }, 10, 2);
        }

        return $current_mode;
    }
}
