<?php
/**
 * Plugin Name: Doli Training Management
 * Description: Intégration du gestionnaire de formations TrainingManagement (Dolibarr) pour WordPress
 * Version: 1.0.1
 * Author: Aplose
 * Author URI: https://aplose.fr
 * Text Domain: doli-training-management
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * License: GPLv3 or later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 */

if (!defined('ABSPATH')) {
    exit;
}

// Constants
define('DOLI_TRAINING_MANAGEMENT_VERSION', '1.0.1');
define('DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('DOLI_TRAINING_MANAGEMENT_PLUGIN_URL', plugin_dir_url(__FILE__));

class Doli_Training_Management {
    private static $instance = null;
    private $ajax_controller;

    public static function getInstance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->init();
    }

    private function init() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_shortcode('doli-training-management', array($this, 'renderDolibarrTrainingManagement'));
        $this->bootstrap_ajax_proxy();
    }

    /**
     * Initialize public AJAX proxy layer.
     */
    private function bootstrap_ajax_proxy() {
        require_once DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR . 'includes/class-doli-training-management-dolibarr-client.php';
        require_once DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR . 'includes/class-doli-training-management-proxy.php';
        require_once DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR . 'includes/class-doli-training-management-ajax.php';

        $client = new Doli_Training_Management_Dolibarr_Client();
        $proxy  = new Doli_Training_Management_Proxy($client);
        $this->ajax_controller = new Doli_Training_Management_Ajax($proxy);
    }

    public function enqueue_scripts() {
        if (!$this->should_enqueue_frontend_assets()) {
            return;
        }

        // Fonts are bundled in Angular styles.css (same approach as doli-appointments).

        // Enqueue polyfills first with type="module"
        wp_enqueue_script(
            'doli-training-management-polyfills',
            plugin_dir_url(__FILE__) . 'assets/doli-training-management/browser/polyfills.js',
            array(),
            DOLI_TRAINING_MANAGEMENT_VERSION,
            true
        );

        // Enqueue main script with type="module"
        wp_enqueue_script(
            'doli-training-management-main',
            plugin_dir_url(__FILE__) . 'assets/doli-training-management/browser/main.js',
            array('doli-training-management-polyfills'),
            DOLI_TRAINING_MANAGEMENT_VERSION,
            true
        );

        wp_localize_script(
            'doli-training-management-main',
            'doliTrainingManagementConfig',
            array(
                'ajaxUrl'             => admin_url('admin-ajax.php'),
                'assetsBaseUrl'       => trailingslashit(plugin_dir_url(__FILE__) . 'assets/doli-training-management/browser/assets'),
                'createInquiryNonce'  => wp_create_nonce('doli_training_management_create_inquiry'),
            )
        );
        // Add script to verify custom element loading
        wp_add_inline_script('doli-training-management-main', '
            window.addEventListener("load", function() {
                if (!customElements.get("dolibarr-training-management")) {
                    console.error("The custom element dolibarr-training-management was not loaded correctly");
                }
            });
        ');

        // Enqueue styles
        wp_enqueue_style(
            'doli-training-management-styles',
            plugin_dir_url(__FILE__) . 'assets/doli-training-management/browser/styles.css',
            array(),
            DOLI_TRAINING_MANAGEMENT_VERSION
        );
    }

    /**
     * Load front-end assets only when the shortcode is present (performance; matches doli-appointments pattern).
     *
     * @return bool
     */
    private function should_enqueue_frontend_assets() {
        if (apply_filters('doli_training_management_force_enqueue_assets', false)) {
            return true;
        }

        global $post;

        return is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'doli-training-management');
    }

    public function renderDolibarrTrainingManagement($atts) {
        $dolibarr_url = get_option('doli_training_management_dolibarr_url');
        $api_key = get_option('doli_training_management_dolibarr_api_key');

        if (empty($dolibarr_url) || empty($api_key)) {
            return sprintf(
                '<div class="notice notice-warning">
                    <p>%s <a href="%s">%s</a></p>
                </div>',
                esc_html__('Please configure your Dolibarr connection in the Doli Training Management settings.', 'doli-training-management'),
                esc_url(admin_url('admin.php?page=doli-training-management')),
                esc_html__('Configure now', 'doli-training-management')
            );
        }

        return '<dolibarr-training-management></dolibarr-training-management>';
    }
}

/**
 * Angular build outputs `polyfills.js` and `main.js` as ES modules.
 * WordPress enqueues scripts without `type="module"` by default, so we
 * force it for our two handles to avoid runtime errors.
 */
function doli_training_management_force_module_type($tag, $handle, $src) {
    if (in_array($handle, array('doli-training-management-polyfills', 'doli-training-management-main'), true)) {
        // If `type` is already present, don't duplicate.
        if (strpos($tag, 'type=') === false) {
            $tag = str_replace('<script ', '<script type="module" ', $tag);
        }
    }
    return $tag;
}

add_filter('script_loader_tag', 'doli_training_management_force_module_type', 10, 3);

/**
 * Bootstrap front-end plugin instance.
 *
 * @return Doli_Training_Management
 */
function doli_training_management() {
    return Doli_Training_Management::getInstance();
}

/**
 * Load admin UI on dashboard requests only.
 */
function doli_training_management_load_admin() {
    if (!is_admin()) {
        return;
    }
    require_once DOLI_TRAINING_MANAGEMENT_PLUGIN_DIR . 'includes/class-doli-training-management-admin.php';
    new Doli_Training_Management_Admin();
}

add_action('plugins_loaded', 'doli_training_management', 5);
add_action('plugins_loaded', 'doli_training_management_load_admin', 6);
