<?php

namespace WordpressModels;

/**
 * Manage compiled script- and style bundles.
 */
class Assets
{

    /**
     * @param string $baseDir the base directory for this plugin's scripts and styles
     * @param string $baseUrl idem, but the url
     */
    public function __construct(private readonly string $baseDir,
                                private readonly string $baseUrl)
    {
    }

    public function enqueueCompiledScript(string $name, array $additionalDependencies = [], bool $footer = true): void
    {
        $jsPath = '/js/' . $name . (WP_DEBUG ? '' : '.min') . '.js';
        $cssPath = '/css/' . $name . (WP_DEBUG ? '' : '.min') . '.css';
        $configPath = $this->baseDir . '/wp/' . $name . (WP_DEBUG ? '' : '.min') . '.asset.php';

        // check if asset exists
        if (!is_file($this->baseDir . $jsPath)) {
            // todo: log asset not found
            return;
        }

        // load asset config (generated with DependencyExtractionPlugin)
        $assetConfig = is_file($configPath) ? require($configPath) : [];
        if (is_array($assetConfig)) {
            $dependencies = $assetConfig['dependencies'] ?? [];
            $assetVersion = $assetConfig['version'] ?? null;
        } else {
            $dependencies = [];
            $assetVersion = null;
        }

        // enqueue script
        wp_enqueue_script(
            $name,
            $this->baseUrl . $jsPath,
            [...$dependencies, ...$additionalDependencies],
            $assetVersion,
            ['in_footer' => $footer]
        );

        // load corresponding css file
        if (is_file($this->baseDir . $cssPath)) {
            wp_enqueue_style(
                $name,
                $this->baseUrl . $cssPath,
                [],
                $assetVersion
            );
        }
    }


    public function getAssetsUrls(string $assetId)
    {
        return [
            'js' => $this->baseUrl . '/js/' . $assetId . (WP_DEBUG ? '' : '.min') . '.js',
            'css' => $this->baseUrl . '/css/' . $assetId . (WP_DEBUG ? '' : '.min') . '.css',
        ];
    }

}
