<?php

namespace GriffinForms\Frontend\Html\Forms\Traits;

/**
 * ExternalAssets Trait
 *
 * Handles enqueuing of external theme assets including:
 * - External theme CSS files
 * - External theme JavaScript files
 * - Google Fonts
 *
 * This trait provides a clean separation of concerns by extracting
 * asset enqueuing logic from the main Form class.
 */
trait ExternalAssets
{
    /**
     * Enqueues external theme CSS file if it exists
     *
     * Converts theme name to filename format and enqueues the CSS file
     * if it exists in the themes directory.
     *
     * Example: "Modern Peach" theme → enqueue "modern_peach.css"
     */
    private function enqueueThemeCss()
    {
        // Check if theme is set
        $theme_id = $this->item->getProp('form_theme');
        if (empty($theme_id)) {
            return;
        }

        // Fetch theme name directly from database
        $theme_name = $this->sql->getItemValue('formtheme', 'id', absint($theme_id), 'name');
        if (empty($theme_name)) {
            return;
        }

        // Convert theme name to filename format (e.g., "Modern Peach" → "modern_peach")
        $filename = strtolower(str_replace(' ', '_', trim($theme_name))) . '.css';

        // Build the full path and URL to theme CSS file
        $root_url = $this->config->getRootUrl();
        $root_path = $this->config->getRootPath();
        $theme_css_file = $root_url . 'frontend/css/themes/' . $filename;
        $theme_css_path = $root_path . 'frontend/css/themes/' . $filename;

        // Check if file exists
        if (!file_exists($theme_css_path)) {
            return;
        }

        // Enqueue the theme CSS file
        wp_enqueue_style(
            'griffinforms-theme-' . $theme_id,
            $theme_css_file,
            array(),
            filemtime($theme_css_path)
        );
    }

    /**
     * Enqueues external theme JavaScript file if it exists
     *
     * Converts theme name to filename format and enqueues the JS file
     * if it exists in the themes directory.
     *
     * Example: "Modern Peach" theme → enqueue "modern_peach.js"
     */
    private function enqueueThemeJs()
    {
        // Check if theme is set
        $theme_id = $this->item->getProp('form_theme');
        if (empty($theme_id)) {
            return;
        }

        // Fetch theme name directly from database
        $theme_name = $this->sql->getItemValue('formtheme', 'id', absint($theme_id), 'name');
        if (empty($theme_name)) {
            return;
        }

        // Convert theme name to filename format (e.g., "Modern Peach" → "modern_peach")
        $filename = strtolower(str_replace(' ', '_', trim($theme_name))) . '.js';

        // Build the full path and URL to theme JS file
        $root_url = $this->config->getRootUrl();
        $root_path = $this->config->getRootPath();
        $theme_js_file = $root_url . 'frontend/js/themes/' . $filename;
        $theme_js_path = $root_path . 'frontend/js/themes/' . $filename;

        // Check if file exists
        if (!file_exists($theme_js_path)) {
            return;
        }

        // Enqueue the theme JS file
        wp_enqueue_script(
            'griffinforms-theme-js-' . $theme_id,
            $theme_js_file,
            array('griffinforms-frontend'),
            filemtime($theme_js_path),
            true
        );
    }

    /**
     * Enqueues external Google Fonts used in the theme
     *
     * Extracts font families from the theme using FormTheme::getExternalFontFamilies()
     * and enqueues them from Google Fonts API.
     *
     * Each font is requested with multiple weight variants (400, 500, 600, 700)
     * for maximum flexibility.
     */
    private function enqueueGoogleFonts()
    {
        // Check if theme is set
        $theme_id = $this->item->getProp('form_theme');
        if (empty($theme_id) || $theme_id < 0) {
            return;
        }

        // Load FormTheme object
        $form_theme = new \GriffinForms\Items\FormTheme();
        if (!$form_theme->loadItem(absint($theme_id))) {
            return;
        }

        // Get external fonts used in the theme
        $external_fonts = $form_theme->getExternalFontFamilies();
        if (empty($external_fonts) || !is_array($external_fonts)) {
            return;
        }

        // Enqueue each external font from Google Fonts
        foreach ($external_fonts as $font_name) {
            // Create a safe handle for the font (e.g., "Roboto" → "roboto")
            $font_handle = 'google-font-' . strtolower(str_replace(' ', '-', trim($font_name)));

            // Build Google Fonts URL with weight variants
            $font_url = $this->buildGoogleFontsUrl($font_name);

            // Enqueue the Google Fonts stylesheet
            wp_enqueue_style(
                $font_handle,
                $font_url,
                array(),
                null
            );
        }
    }

    /**
     * Builds a Google Fonts URL for a given font family
     *
     * Includes common weight variants (400, 500, 600, 700) for flexibility.
     * Uses display=swap for optimal font loading performance.
     *
     * @param string $font_name Font family name (e.g., "Roboto", "Open Sans")
     * @return string Google Fonts API URL
     */
    private function buildGoogleFontsUrl($font_name)
    {
        // URL-encode the font name (e.g., "Open Sans" → "Open+Sans")
        $encoded_font = str_replace(' ', '+', urlencode(trim($font_name)));

        // Include common font weights for maximum flexibility
        // Google Fonts allows multiple weights in format: family:wght@400;500;600;700
        return "https://fonts.googleapis.com/css2?family={$encoded_font}:wght@400;500;600;700&display=swap";
    }
}
