<?php
/**
 * Class Core - Version Robuste & Dynamique
 * Gère l'initialisation et la récupération des paramètres URL (Nom Entreprise, Langue)
 */

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

if ( ! class_exists( 'Avision_Core' ) ) {

    class Avision_Core {

        public function __construct() {
            $this->load_dependencies();
            $this->define_public_hooks();
        }

        private function load_dependencies() {
            if ( file_exists( AVISION_PATH . 'includes/class-assets.php' ) ) {
                require_once AVISION_PATH . 'includes/class-assets.php';
            }
            // Routeur AJAX chargé et instancié dans avision-dashboard.php (point d'entrée unique)
            if ( file_exists( AVISION_PATH . 'includes/services/class-user-state.php' ) ) {
                require_once AVISION_PATH . 'includes/services/class-user-state.php';
            }
        }

        private function define_public_hooks() {
            if ( class_exists( 'Avision_Assets' ) ) {
                $assets_manager = new Avision_Assets();
                add_action( 'wp_enqueue_scripts', array( $assets_manager, 'enqueue_scripts' ) );
            }

            add_shortcode( 'avision_dashboard', array( $this, 'render_dashboard' ) );
            add_shortcode( 'avision_dashboard_demo', array( $this, 'render_dashboard' ) );
            add_shortcode( 'avision_dashboard_pro', array( $this, 'render_dashboard' ) );
        }

        public function render_dashboard( $atts ) {
            $atts = shortcode_atts( array(
                'lang' => 'en',
                'company_name' => 'Mon Entreprise'
            ), $atts, 'avision_dashboard' );

            if ( isset( $_GET['company'] ) && ! empty( $_GET['company'] ) ) {
                $atts['company_name'] = sanitize_text_field( $_GET['company'] );
            }

            if ( isset( $_GET['lang'] ) && ! empty( $_GET['lang'] ) ) {
                $atts['lang'] = sanitize_text_field( $_GET['lang'] );
            }

            $user_id = get_current_user_id();
            $progress = array();
            
            if ( class_exists( 'Avision_User_State' ) ) {
                $progress = Avision_User_State::get_all_progress( $user_id );
            }

            ob_start();
            if ( file_exists( AVISION_PATH . 'templates/layout-main.php' ) ) {
                include AVISION_PATH . 'templates/layout-main.php';
            } else {
                echo '<p style="color:red; text-align:center;">Erreur critique : Le template layout-main.php est introuvable.</p>';
            }
            return ob_get_clean();
        }
    }
}
