<?php
/**
 * Name: Alpine.js Enqueue
 * Description: Enqueue Alpine.js JavaScript framework on frontend pages and admin dashboard to enable reactive components and dynamic interactions without complex build tools or frameworks
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-09-28
 * Tags: alpine, javascript, framework, frontend, admin
 * WhereToFind: {
 *   "location": "Developer - View Page Source",
 *   "url": "",
 *   "instructions": "Alpine.js library is loaded. Check browser console or page source for alpine.js script. Use Alpine directives (x-data, x-show, etc.) in your theme/plugin code.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardAlpineJsEnqueue {
    
    public function __construct() {
        $settings = get_option('switchboard_alpine-js-enqueue_settings', []);
        
        $load_frontend = isset($settings['load_frontend']) && $settings['load_frontend'] === 'yes';
        $load_admin = isset($settings['load_admin']) && $settings['load_admin'] === 'yes';
        $version = isset($settings['version']) ? sanitize_text_field($settings['version']) : '3.x.x';

        // Validate version format (only allow alphanumeric, dots, hyphens, and 'x')
        if (!preg_match('/^[\d\.x\-]+$/', $version)) {
            $version = '3.x.x';
        }

        $defer = isset($settings['defer']) && $settings['defer'] === 'yes';
        
        if ($load_frontend) {
            add_action('wp_enqueue_scripts', function() use ($version, $defer) {
                $this->enqueue_alpine($version, $defer);
            });
        }
        
        if ($load_admin) {
            add_action('admin_enqueue_scripts', function() use ($version, $defer) {
                $this->enqueue_alpine($version, $defer);
            });
        }
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_alpine-js-enqueue_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => []
        ];
    }
    
    /**
     * Render settings panel for Alpine.js Enqueue
     *
     * Displays settings interface for Alpine.js library loading with:
     * - Frontend loading checkbox to enable on public pages
     * - Admin loading checkbox to enable in WordPress dashboard
     * - Version selector dropdown (3.x.x Latest vs 2.x.x Legacy)
     * - Simple, clean interface with checkbox styling
     * - Helpful description about configuration options
     *
     * The interface provides straightforward control over where the Alpine.js CDN library
     * is loaded. Frontend loading is enabled by default for public-facing pages, while
     * admin loading is disabled by default to avoid conflicts with WordPress admin scripts.
     * The version selector allows choosing between Alpine 3.x (recommended, modern syntax)
     * and Alpine 2.x (legacy, for backward compatibility with older code). The library is
     * loaded from CDN (unpkg) with high priority (999) to ensure it loads after other
     * scripts. Alpine.js is a lightweight JavaScript framework perfect for adding reactive
     * components, toggles, dropdowns, and dynamic interactions without the complexity of
     * Vue or React. Ideal for theme developers wanting to add interactivity with minimal
     * overhead, or for creating admin custom fields with reactive behavior.
     *
     * @param array $settings Current module settings with 'load_frontend', 'load_admin', 'version' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $load_frontend = isset($settings['load_frontend']) ? $settings['load_frontend'] : 'yes';
        $load_admin = isset($settings['load_admin']) ? $settings['load_admin'] : 'no';
        $version = isset($settings['version']) ? $settings['version'] : '3.x.x';
        $defer = isset($settings['defer']) ? $settings['defer'] : 'no';
        ?>
        <input type="hidden" name="module" value="alpine-js-enqueue">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading"><?php esc_html_e('Alpine.js Enqueue', 'wpswitchboard'); ?></h3>
            <p class="sb-sp-description"><?php esc_html_e('Enqueue Alpine.js JavaScript framework on frontend pages and admin dashboard to enable reactive components and dynamic interactions.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 16px;">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Load on Frontend', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_load_frontend" value="yes" <?php checked($load_frontend, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Load Alpine.js on public-facing pages', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 16px;">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Load in Admin', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_load_admin" value="yes" <?php checked($load_admin, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Load Alpine.js in WordPress admin dashboard', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 24px;">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Defer Loading', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_defer" value="yes" <?php checked($defer, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Add defer attribute to script tag for better page load performance', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <label for="setting_version" class="sb-sp-label"><?php esc_html_e('Alpine.js Version', 'wpswitchboard'); ?></label>
            <select name="setting_version" id="setting_version" class="sb-sp-input sb-sp-w-full" style="max-width: 300px;">
                <option value="3.x.x" <?php selected($version, '3.x.x'); ?>><?php esc_html_e('3.x.x (Latest)', 'wpswitchboard'); ?></option>
                <option value="2.x.x" <?php selected($version, '2.x.x'); ?>><?php esc_html_e('2.x.x (Legacy)', 'wpswitchboard'); ?></option>
            </select>
            <p class="sb-sp-description"><?php esc_html_e('Choose the Alpine.js version to load. Version 3.x is recommended for new projects.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('About Alpine.js', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description" style="margin: 0;">
                <?php esc_html_e('Alpine.js is a lightweight JavaScript framework perfect for adding reactive components, toggles, dropdowns, and dynamic interactions without the complexity of Vue or React. Ideal for theme developers wanting to add interactivity with minimal overhead.', 'wpswitchboard'); ?>
            </p>
        </div>
        <?php
    }
    
    private function enqueue_alpine($version, $defer) {
        wp_enqueue_script(
            'alpine-js',
            'https://cdn.jsdelivr.net/npm/alpinejs@' . $version . '/dist/cdn.min.js',
            [],
            null,
            !$defer
        );
        
        if ($defer) {
            add_filter('script_loader_tag', function($tag, $handle) {
                if ($handle === 'alpine-js') {
                    return str_replace(' src', ' defer src', $tag);
                }
                return $tag;
            }, 10, 2);
        }
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardAlpineJsEnqueue();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
