<?php

namespace WordpressModels;

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

    private array $timberTemplateLocations;


    /**
     * @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)
    {
        $this->timberTemplateLocations = [];

        add_filter('timber/locations', $this->addTimberPagesTemplateLocations(...));
    }

    /**
     * Queue a directory in which Timber/Twig template can be searched.
     */
    public function addTimberTemplateLocation(string $location): void
    {
        $this->timberTemplateLocations[] = $location;
    }

    /**
     * @hooked timber/locations
     */
    public function addTimberPagesTemplateLocations(array $locations = []): array
    {
        return array_merge($locations, $this->timberTemplateLocations);
    }

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

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

        $assetConfig = is_file($assetConfigFile) ? require($assetConfigFile) : [];
        if (is_array($assetConfig)) {
            $dependencies = $assetConfig['dependencies'] ?? [];
            $assetVersion = $assetConfig['version'] ?? null;
        } else {
            $dependencies = [];
            $assetVersion = null;
        }

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

        if (is_file($this->baseDir . $css_src)) {
            wp_enqueue_style(
                $name,
                $this->baseUrl . $css_src,
                [],
                $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',
        ];
    }

}
