<?php
/**
 * Chalet Montagne functions and definitions
 *
 * @package ChaletMontagne
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Theme version
 */
define('CHALETMONTAGNE_VERSION', '1.4.9');


/**
 * Theme setup
 */
function chaletmontagne_setup() {
    // Make theme available for translation
    load_theme_textdomain('chalet-montagne', get_template_directory() . '/languages');

    // Add default posts and comments RSS feed links to head
    add_theme_support('automatic-feed-links');

    // Let WordPress manage the document title
    add_theme_support('title-tag');

    // Enable support for Post Thumbnails
    add_theme_support('post-thumbnails');

    // Set default thumbnail sizes
    set_post_thumbnail_size(1200, 800, true);
    add_image_size('chaletmontagne-large', 1200, 800, true);
    add_image_size('chaletmontagne-medium', 800, 600, true);
    add_image_size('chaletmontagne-small', 400, 300, true);

    // Register navigation menus
    register_nav_menus(array(
        'primary' => esc_html__('Menu Principal', 'chalet-montagne'),
        'footer'  => esc_html__('Menu Pied de page', 'chalet-montagne'),
    ));

    // Switch default core markup to output valid HTML5
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
        'style',
        'script',
    ));

    // Add theme support for selective refresh for widgets
    add_theme_support('customize-selective-refresh-widgets');

    // Add support for custom logo
    add_theme_support('custom-logo', array(
        'height'      => 100,
        'width'       => 300,
        'flex-height' => true,
        'flex-width'  => true,
    ));

    // Add support for responsive embeds
    add_theme_support('responsive-embeds');

    // Add support for wide alignment
    add_theme_support('align-wide');

    // Add support for block styles
    add_theme_support('wp-block-styles');

    // Note: custom-header and custom-background are NOT used
    // Background and header colors are managed by our preset system
    // in Apparence et Style > Couleurs personnalisées

    // Add support for editor styles
    add_theme_support('editor-styles');
    add_editor_style('assets/css/editor-style.css');
}
add_action('after_setup_theme', 'chaletmontagne_setup');

/**
 * Set the content width in pixels
 */
function chaletmontagne_content_width() {
    $GLOBALS['content_width'] = apply_filters('chaletmontagne_content_width', 1200);
}
add_action('after_setup_theme', 'chaletmontagne_content_width', 0);

/**
 * Enqueue scripts and styles
 */
function chaletmontagne_scripts() {
    // Self-hosted fonts
    wp_enqueue_style(
        'chaletmontagne-fonts',
        get_template_directory_uri() . '/assets/css/fonts.css',
        array(),
        CHALETMONTAGNE_VERSION
    );

    // Main stylesheet
    wp_enqueue_style('chaletmontagne-style', get_stylesheet_uri(), array(), CHALETMONTAGNE_VERSION);

    // Main CSS file
    wp_enqueue_style(
        'chaletmontagne-main',
        get_template_directory_uri() . '/assets/css/main.css',
        array(),
        CHALETMONTAGNE_VERSION
    );


    // Animations CSS
    wp_enqueue_style(
        'chaletmontagne-animations',
        get_template_directory_uri() . '/assets/css/animations.css',
        array('chaletmontagne-main'),
        CHALETMONTAGNE_VERSION
    );

    // Header & Hero CSS
    wp_enqueue_style(
        'chaletmontagne-header-hero',
        get_template_directory_uri() . '/assets/css/header-hero.css',
        array('chaletmontagne-main'),
        CHALETMONTAGNE_VERSION
    );

    // Responsive CSS
    wp_enqueue_style(
        'chaletmontagne-responsive',
        get_template_directory_uri() . '/assets/css/responsive.css',
        array('chaletmontagne-main', 'chaletmontagne-animations', 'chaletmontagne-header-hero'),
        CHALETMONTAGNE_VERSION
    );

    // Luxury CSS - Load if luxury preset is selected
    $luxury_preset = get_theme_mod('chaletmontagne_luxury_preset', 'marron-sobre');
    if ($luxury_preset !== 'custom') {
        wp_enqueue_style(
            'chaletmontagne-luxury',
            get_template_directory_uri() . '/assets/css/luxury.css',
            array('chaletmontagne-main'),
            CHALETMONTAGNE_VERSION
        );
    }

    // Plugin overrides CSS - Load after luxury for proper cascade
    wp_enqueue_style(
        'chaletmontagne-plugin-overrides',
        get_template_directory_uri() . '/assets/css/plugin-overrides.css',
        array('chaletmontagne-main'),
        CHALETMONTAGNE_VERSION
    );

    // Slider CSS & JS - Load only on front page when slider is enabled
    $slider_enabled = get_theme_mod('chaletmontagne_slider_enable', false);
    $slider_images = get_theme_mod('chaletmontagne_slider_images', '');

    if (is_front_page() && $slider_enabled && !empty($slider_images)) {
        wp_enqueue_style(
            'chaletmontagne-slider',
            get_template_directory_uri() . '/assets/css/slider.css',
            array('chaletmontagne-main'),
            CHALETMONTAGNE_VERSION
        );

        wp_enqueue_script(
            'chaletmontagne-slider',
            get_template_directory_uri() . '/assets/js/slider.js',
            array(),
            CHALETMONTAGNE_VERSION,
            true
        );

        // Pass slider options to JavaScript
        wp_localize_script('chaletmontagne-slider', 'chaletMontagneSlider', array(
            'speed'           => get_theme_mod('chaletmontagne_slider_speed', 5) * 1000,
            'transitionSpeed' => get_theme_mod('chaletmontagne_slider_transition_speed', 1000),
            'transition'      => get_theme_mod('chaletmontagne_slider_transition', 'fade'),
            'autoplay'        => get_theme_mod('chaletmontagne_slider_autoplay', true) ? '1' : '0',
            'pauseOnHover'    => get_theme_mod('chaletmontagne_slider_pause_hover', true) ? '1' : '0',
            'dots'            => get_theme_mod('chaletmontagne_slider_dots', true) ? '1' : '0',
            'arrows'          => get_theme_mod('chaletmontagne_slider_arrows', true) ? '1' : '0',
        ));
    }

    // Main JavaScript
    wp_enqueue_script(
        'chaletmontagne-main',
        get_template_directory_uri() . '/assets/js/main.js',
        array('jquery'),
        CHALETMONTAGNE_VERSION,
        true
    );

    // Localize script for AJAX and translations
    wp_localize_script('chaletmontagne-main', 'chaletMontagneData', array(
        'ajaxUrl'       => admin_url('admin-ajax.php'),
        'nonce'         => wp_create_nonce('chaletmontagne_nonce'),
        'menuText'       => __('Menu', 'chalet-montagne'),
        'requiredField'  => __('Ce champ est requis', 'chalet-montagne'),
        'invalidEmail'   => __('Email invalide', 'chalet-montagne'),
        'backToTop'      => __('Retour en haut', 'chalet-montagne'),
        'prevSlide'      => __('Slide précédent', 'chalet-montagne'),
        'nextSlide'      => __('Slide suivant', 'chalet-montagne'),
        'goToSlide'      => __('Aller au slide', 'chalet-montagne'),
    ));

    // Comment reply script
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }

    // Theme Effects JS - Load for special themes with animated effects
    $colors = chaletmontagne_get_luxury_colors($luxury_preset);
    if (isset($colors['effect']) && !empty($colors['effect'])) {
        wp_enqueue_script(
            'chaletmontagne-effects',
            get_template_directory_uri() . '/assets/js/theme-effects.js',
            array(),
            CHALETMONTAGNE_VERSION,
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'chaletmontagne_scripts');

/**
 * Output body attributes for theme effects
 */
function chaletmontagne_body_attributes() {
    $luxury_preset = get_theme_mod('chaletmontagne_luxury_preset', 'marron-sobre');
    $colors = chaletmontagne_get_luxury_colors($luxury_preset);

    $attributes = array();

    // Add theme effect attribute
    if (isset($colors['effect']) && !empty($colors['effect'])) {
        $attributes[] = 'data-theme-effect="' . esc_attr($colors['effect']) . '"';
    }

    // Add dark theme attribute
    if (isset($colors['is_dark']) && $colors['is_dark']) {
        $attributes[] = 'data-theme-dark="true"';
    }

    // Add theme preset attribute
    $attributes[] = 'data-theme-preset="' . esc_attr($luxury_preset) . '"';

    echo implode(' ', $attributes);
}

/**
 * Register widget areas
 */
function chaletmontagne_widgets_init() {
    // Sidebar
    register_sidebar(array(
        'name'          => esc_html__('Sidebar', 'chalet-montagne'),
        'id'            => 'sidebar-1',
        'description'   => esc_html__('Ajoutez des widgets ici.', 'chalet-montagne'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ));

    // Footer columns
    for ($i = 1; $i <= 3; $i++) {
        register_sidebar(array(
            'name'          => sprintf(esc_html__('Footer colonne %d', 'chalet-montagne'), $i),
            'id'            => "footer-{$i}",
            'description'   => sprintf(esc_html__('Contenu de la colonne %d du pied de page.', 'chalet-montagne'), $i),
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h3 class="widget-title">',
            'after_title'   => '</h3>',
        ));
    }

    // Custom widgets
    register_widget('ChaletMontagne_Contact_Widget');
    register_widget('ChaletMontagne_Social_Widget');
    register_widget('ChaletMontagne_Station_Widget');
    register_widget('ChaletMontagne_Features_Widget');
}
add_action('widgets_init', 'chaletmontagne_widgets_init');

/**
 * Rename "Legacy Widget" / "Ancien widget" to "Widget du thème" via official block API.
 */
function chaletmontagne_rename_legacy_widget_block($args, $block_type) {
    if ($block_type === 'core/legacy-widget') {
        $args['title'] = __('Widget du thème', 'chalet-montagne');
    }
    return $args;
}
add_filter('register_block_type_args', 'chaletmontagne_rename_legacy_widget_block', 10, 2);

/**
 * Widget: CM — Contact
 * Displays contact info from the Customizer settings.
 */
class ChaletMontagne_Contact_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'chaletmontagne_contact',
            esc_html__('CM — Contact', 'chalet-montagne'),
            array('description' => esc_html__('Affiche les coordonnées (téléphone, email, adresse, horaires) configurées dans le Customizer.', 'chalet-montagne'))
        );
    }

    public function widget($args, $instance) {
        $phone   = get_theme_mod('chaletmontagne_phone');
        $email   = get_theme_mod('chaletmontagne_email');
        $address = get_theme_mod('chaletmontagne_address');
        $hours   = get_theme_mod('chaletmontagne_hours');

        if (!$phone && !$email && !$address && !$hours) {
            return;
        }

        echo $args['before_widget'];
        echo $args['before_title'] . esc_html__('Contact', 'chalet-montagne') . $args['after_title'];

        if ($phone) {
            printf(
                '<p class="footer-phone"><a href="tel:%s">%s</a></p>',
                esc_attr(str_replace(' ', '', $phone)),
                esc_html($phone)
            );
        }
        if ($email) {
            printf(
                '<p class="footer-email"><a href="mailto:%s">%s</a></p>',
                esc_attr($email),
                esc_html($email)
            );
        }
        if ($address) {
            echo '<p class="footer-address">' . nl2br(esc_html($address)) . '</p>';
        }
        if ($hours) {
            echo '<p class="footer-hours">' . esc_html($hours) . '</p>';
        }

        echo $args['after_widget'];
    }

    public function form($instance) {
        echo '<p>' . esc_html__('Les données proviennent de Personnalisation ▸ Contact & Informations ▸ Coordonnées.', 'chalet-montagne') . '</p>';
    }

    public function update($new_instance, $old_instance) {
        return $new_instance;
    }
}

/**
 * Widget: CM — Réseaux sociaux
 * Displays social links from the Customizer settings.
 */
class ChaletMontagne_Social_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'chaletmontagne_social',
            esc_html__('CM — Réseaux sociaux', 'chalet-montagne'),
            array('description' => esc_html__('Affiche les liens vers vos réseaux sociaux configurés dans le Customizer.', 'chalet-montagne'))
        );
    }

    public function widget($args, $instance) {
        $social_networks = array('facebook', 'instagram', 'twitter', 'youtube', 'chalet-montagne', 'airbnb', 'booking');
        $has_social = false;
        foreach ($social_networks as $network) {
            if (get_theme_mod("chaletmontagne_social_{$network}")) {
                $has_social = true;
                break;
            }
        }

        if (!$has_social) {
            return;
        }

        echo $args['before_widget'];
        echo $args['before_title'] . esc_html__('Suivez-nous', 'chalet-montagne') . $args['after_title'];
        chaletmontagne_social_links();
        echo $args['after_widget'];
    }

    public function form($instance) {
        echo '<p>' . esc_html__('Les liens proviennent de Personnalisation ▸ Réseaux sociaux.', 'chalet-montagne') . '</p>';
    }

    public function update($new_instance, $old_instance) {
        return $new_instance;
    }
}

/**
 * Widget: CM — Informations station
 * Displays station info from the Customizer settings.
 */
class ChaletMontagne_Station_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'chaletmontagne_station',
            esc_html__('CM — Informations station', 'chalet-montagne'),
            array('description' => esc_html__('Affiche les informations de la station (nom, distances, activités) configurées dans le Customizer.', 'chalet-montagne'))
        );
    }

    public function widget($args, $instance) {
        $station_name     = get_theme_mod('chaletmontagne_station_name');
        $distance_slopes  = get_theme_mod('chaletmontagne_distance_slopes');
        $distance_center  = get_theme_mod('chaletmontagne_distance_center');
        $activities       = get_theme_mod('chaletmontagne_activities');

        if (!$station_name && !$distance_slopes && !$distance_center && !$activities) {
            return;
        }

        echo $args['before_widget'];
        echo $args['before_title'] . esc_html($station_name ?: __('La Station', 'chalet-montagne')) . $args['after_title'];

        echo '<ul class="station-info-list">';
        if ($distance_slopes) {
            echo '<li><strong>' . esc_html__('Pistes', 'chalet-montagne') . '</strong> ' . esc_html($distance_slopes) . '</li>';
        }
        if ($distance_center) {
            echo '<li><strong>' . esc_html__('Centre-ville', 'chalet-montagne') . '</strong> ' . esc_html($distance_center) . '</li>';
        }
        if ($activities) {
            echo '<li><strong>' . esc_html__('Activités', 'chalet-montagne') . '</strong> ' . esc_html($activities) . '</li>';
        }
        echo '</ul>';

        echo $args['after_widget'];
    }

    public function form($instance) {
        echo '<p>' . esc_html__('Les données proviennent de Personnalisation ▸ Contact & Informations ▸ Informations station.', 'chalet-montagne') . '</p>';
    }

    public function update($new_instance, $old_instance) {
        return $new_instance;
    }
}

/**
 * Widget: CM — Arguments de vente
 * Displays selling features from the Customizer settings.
 */
class ChaletMontagne_Features_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'chaletmontagne_features',
            esc_html__('CM — Arguments de vente', 'chalet-montagne'),
            array('description' => esc_html__('Affiche les arguments de vente configurés dans le Customizer.', 'chalet-montagne'))
        );
    }

    public function widget($args, $instance) {
        $defaults = array(
            1 => __('Wifi gratuit inclus', 'chalet-montagne'),
            2 => __('Parking privé gratuit', 'chalet-montagne'),
            3 => __('Ménage final offert', 'chalet-montagne'),
            4 => __('Réservation directe - meilleurs tarifs', 'chalet-montagne'),
        );
        $features = array();
        for ($i = 1; $i <= 4; $i++) {
            $feature = get_theme_mod("chaletmontagne_feature_{$i}", $defaults[$i]);
            if ($feature) {
                $features[] = $feature;
            }
        }

        if (empty($features)) {
            return;
        }

        echo $args['before_widget'];
        echo $args['before_title'] . esc_html__('Nos atouts', 'chalet-montagne') . $args['after_title'];

        echo '<ul class="features-list">';
        foreach ($features as $feature) {
            echo '<li>' . esc_html($feature) . '</li>';
        }
        echo '</ul>';

        echo $args['after_widget'];
    }

    public function form($instance) {
        echo '<p>' . esc_html__('Les données proviennent de Personnalisation ▸ Contact & Informations ▸ Arguments de vente.', 'chalet-montagne') . '</p>';
    }

    public function update($new_instance, $old_instance) {
        return $new_instance;
    }
}

/**
 * Include required files
 */
require get_template_directory() . '/inc/template-functions.php';
require get_template_directory() . '/inc/theme-migration.php';
require get_template_directory() . '/inc/customizer-controls.php';
require get_template_directory() . '/inc/customizer.php';

// Widgets custom supprimés — le footer utilise directement les données du Customizer
