<?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) || !is_file($assetConfigFile)) {
            // todo: log asset not found
            return;
        }

        $assetConfig = require($assetConfigFile);

        wp_enqueue_script(
            $name,
            $this->baseUrl . $js_src,
            [...$assetConfig['dependencies'], ...$additionalDependencies],
            $assetConfig['version'],
            $footer
        );

        if (is_file($this->baseDir . $css_src)) {
            wp_enqueue_style(
                $name,
                $this->baseUrl . $css_src,
                [],
                $assetConfig['version']
            );
        }
    }

}
