<?php

namespace WPIS;

class ClientAssetsManager
{

    private static $formsScriptFilename = 'wpis-forms.js';

    static public function init()
    {
        $class = new self();

        if (SettingsManager::get('enableVueShortcodes')) {
            add_action('wp_enqueue_scripts', [$class, 'wpis_add_frontend_js']);
        }
    }

    public function wpis_add_frontend_js($hook)
    {
        wp_enqueue_script('wpis_app', plugin_dir_url(__FILE__) . '../dist/client/frontend.js');
    }

    static public function enqueueFormsScript()
    {
        $script = self::getFormsScript();
        $version = $script['path'] ? filemtime($script['path']) : false;

        wp_enqueue_script('wpis_forms', $script['url'], [], $version);
    }

    static public function getFormsScript()
    {
        $filename = self::$formsScriptFilename;

        $candidates = [
            [get_stylesheet_directory(), get_stylesheet_directory_uri()],
        ];

        if (get_stylesheet_directory() !== get_template_directory()) {
            $candidates[] = [get_template_directory(), get_template_directory_uri()];
        }

        foreach ($candidates as [$directory, $uri]) {
            $path = $directory . '/' . $filename;

            if (file_exists($path)) {
                return apply_filters('wpis_forms_script', [
                    'url'  => $uri . '/' . $filename,
                    'path' => $path,
                ], $path);
            }
        }

        return apply_filters('wpis_forms_script', [
            'url'  => plugin_dir_url(__FILE__) . '../dist/client/' . $filename,
            'path' => null,
        ], null);
    }
}
