<?php

final class CommoditechApps
{
    private static $instance = null;

    private function __construct()
    {
        $this->loadStylesAndScripts();
        $this->addThemeSupport();
        $this->registerMenus();
        $this->registerCustomLogo();
    }

    public static function getInstance(): self
    {
        if(null === self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    private function loadStylesAndScripts(): void
    {
        add_action( 'wp_enqueue_scripts', function() {
            $this->enqueueBuild('index', 'commoditech-apps');
        }, 999);
    }

    private function addThemeSupport(): void
    {
        add_theme_support( 'title-tag' );
        add_theme_support( 'custom-logo' );
    }

    private function registerMenus(): void
    {
        add_action( 'init', function() {
            register_nav_menus([
                'footer-menu' => 'Stopka'
            ]);
        });
    }

    private function registerCustomLogo(): void
    {
        add_filter( 'get_custom_logo', function($html) {
            return str_replace(['custom-logo-link', 'custom-logo'], ['o-logo', ''], $html);
        });
    }

    private function enqueueBuild(string $entrypoint, ?string $handle = null): void
    {
        if(null === $handle) {
            $handle = $entrypoint;
        }

        $buildDirectory = __DIR__ . '/../../build';
        $assetFile = "$buildDirectory/$entrypoint.asset.php";

        if(!file_exists($assetFile)) {
            return;
        }

        $assetInformation = include($assetFile);
        $buildPath = get_stylesheet_directory_uri() . '/build';

        $jsFilePath = "$buildDirectory/$entrypoint.js";
        $styleAssetsFilePath = "$buildDirectory/$entrypoint.css";
        $styleFilePath = "$buildDirectory/style-$entrypoint.css";

        if(file_exists($jsFilePath)) {
            wp_enqueue_script(
                $handle,
                str_replace($buildDirectory, $buildPath, $jsFilePath),
                $assetInformation['dependencies'],
                $assetInformation['version'],
                true
            );
        }

        if(file_exists($styleAssetsFilePath)) {
            wp_enqueue_style(
                "$handle-assets",
                str_replace($buildDirectory, $buildPath, $styleAssetsFilePath),
                [],
                $assetInformation['version']
            );
        }

        if(file_exists($styleFilePath)) {
            wp_enqueue_style(
                $handle,
                str_replace($buildDirectory, $buildPath, $styleFilePath),
                [],
                $assetInformation['version']
            );
        }
    }
}