<?php
// Setup the Theme Customizer settings and controls...
add_action('customize_register', array('Communet_Customize', 'register'));

// Output custom CSS to live site
//add_action( 'wp_head' , array( 'Communet_Customize' , 'header_output' ) );
// Enqueue live preview javascript in Theme Customizer admin screen
add_action('customize_preview_init', array('Communet_Customize', 'live_preview'));

// Generate new CSS file for front-end
add_action('customize_save_after', array('Communet_Customize', 'generate_css_frontend'));

/**
 * Contains methods for customizing the theme customization screen.
 *
 * @link http://codex.wordpress.org/Theme_Customization_API
 * @since MyTheme 1.0
 */
class Communet_Customize
    {

    const listePolices = array(
        'BioRhyme' => array("font" => "'BioRhyme', serif", "link" => "BioRhyme:400,700"),
        'Droid Serif' => array("font" => "'Droid Serif', serif", "link" => "Droid+Serif:400,400i,700,700i"),
        'Glegoo' => array("font" => "'Glegoo', serif", "link" => "Glegoo:400,700"),
        'Khand' => array("font" => "'Khand', serif", "link" => "Khand:400,700"),
        'Expletus Sans' => array("font" => "'Expletus Sans', sans-serif", "link" => "Expletus+Sans:400,700"),
        'Ubuntu' => array("font" => "'Ubuntu', sans-serif", "link" => "Ubuntu:300italic,300,700,700italic"),
        'Martel' => array("font" => "'Martel', serif", "link" => "Martel:400,700"),
        'Montserrat' => array("font" => "'Montserrat', serif", "link" => "Montserrat:400,700"),
        'Noto Sans' => array("font" => "'Noto Sans', sans-serif", "link" => "Noto+Sans:400,400i,700,700i"),
        'Open Sans' => array("font" => "'Open Sans', sans-serif", "link" => "Open+Sans:400,400i,700,700i"),
        'Podkova' => array("font" => "'Podkova', serif", "link" => "Podkova:400,700"),
        'PT Sans Narrow' => array("font" => "'PT Sans Narrow', serif", "link" => "PT+Sans+Narrow:400,700"),
        'PT Serif' => array("font" => "'PT Serif', serif", "link" => "PT+Serif:400,400i,700,700i"),
        'Roboto Slab' => array("font" => "'Roboto Slab', serif", "link" => "Roboto+Slab:400,700"),
        'Yanone Kaffeesatz' => array("font" => "'Yanone Kaffeesatz', sans-serif", "link" => "Yanone+Kaffeesatz:400,700"),
    );
    const selectListePolices = array(
        "BioRhyme:400,700|'BioRhyme', serif" => "BioRhyme",
        "Droid+Serif:400,400i,700,700i|'Droid Serif', serif" => 'Droid Serif',
        "Glegoo:400,700|'Glegoo', serif" => "Glegoo",
        "Khand:400,700|'Glegoo', serif" => "Khand",
        "ExpletusSans:400,700|'Expletus Sans', sans-serif" => "Expletus Sans",
        "Ubuntu:300italic,300,700,700italic|'Ubuntu', sans-serif" => 'Ubuntu',
        "Martel:400,700|'Martel', serif" => "Martel",
        "Montserrat:400,700|'Montserrat', serif" => "Montserrat",
        "Noto+Sans:400,400i,700,700i|'Noto Sans', sans-serif" => 'Noto Sans',
        "Open+Sans:400,400i,700,700i|'Open Sans', sans-serif" => 'Open Sans',
        "Podkova:400,700|'Podkova', serif" => 'Podkova',
        "PT+Sans+Narrow:400,700|'PT Sans Narrow', serif" => "PT Sans Narrow",
        "PT+Serif:400,400i,700,700i|'PT Serif', serif" => 'PT Serif',
        "Roboto+Slab:400,700|'Roboto Slab', serif" => 'Roboto Slab',
        "Yanone+Kaffeesatz:400,700|'Yanone Kaffeesatz', sans-serif" => 'Yanone Kaffeesatz',
    );

    public static function register($wp_customize)
        {
        //1. Define a new section (if desired) to the Theme Customizer
        // Création d'un nouveau panneau
        $wp_customize->add_panel('panel_communet', array(
            'title' => 'Gestion Communet',
            'description' => 'Panneau d\'administration du site',
            'priority' => 150,
        ));

        // 1. Création d'une nouvelle section dans le Theme Customizer
        $wp_customize->add_section('section_couleur', array(
            'title' => 'Gestion des couleurs',
            'priority' => 10,
            'panel' => 'panel_communet',
        ));


        //********************
        // COULEUR & COULEUR POLICE
        //********************

        for ($i = 1; $i <= 5; $i++) {
            // 2. Enregistrement d'un nouveau paramètre dans la base WP
            $wp_customize->add_setting(
                'couleur_site_' . $i, //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
                array(
                    'default' => '#2BA6CB', //Default setting/value to save
                    'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                    'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                    'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
                )
            );

            $description = '';
            $desciptionPolice = '';
            if ($i == 1) {
                $description = 'Couleur de fond pour les accès direct et le slider';
                $desciptionPolice = 'Couleur de police pour les liens';
                } elseif ($i == 2) {
                $description = 'Couleur de fond pour l\'acces rapides et rechercher';
                } elseif ($i == 3) {
                $description = 'Couleur de fond pour le flash info et le bouton newsletter';
                } elseif ($i >= 4) {
                $description = 'Couleur de fond pour l\'agenda';
                $desciptionPolice = 'Couleur de police pour l\'agenda';
                }

            //3. On définit le contrôleur (lié au paramètre précédent et crée le rendu HTML) ....
            $wp_customize->add_control(new WP_Customize_Color_Control(//Instantiate the color control class
                $wp_customize, //Pass the $wp_customize object (required)
                'communet_couleur_site_' . $i, //Set a unique ID for the control
                array(
                    'label' => __('Couleur site ' . $i, 'mytheme'), //Admin-visible name of the control
                    'description' => $description, //Admin-visible name of the control
                    'settings' => 'couleur_site_' . $i, //Which setting to load and manipulate (serialized is okay)
                    'priority' => 10, //Determines the order this control appears in for the specified section
                    'section' => 'section_couleur', //ID of the section this control should render in (can be one of yours, or a WordPress default section)
                )
            ));

            // 2. Enregistrement d'un nouveau paramètre dans la base WP
            $wp_customize->add_setting(
                'couleur_police_' . $i, //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
                array(
                    'default' => '#2BA6CB', //Default setting/value to save
                    'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                    'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                    'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
                )
            );
            //3. On définit le contrôleur (lié au paramètre précédent et crée le rendu HTML) ....
            $wp_customize->add_control(new WP_Customize_Color_Control(//Instantiate the color control class
                $wp_customize, //Pass the $wp_customize object (required)
                'communet_couleur_police_' . $i, //Set a unique ID for the control
                array(
                    'label' => __('Couleur police ' . $i, 'mytheme'), //Admin-visible name of the control
                    'description' => $desciptionPolice,
                    'settings' => 'couleur_police_' . $i, //Which setting to load and manipulate (serialized is okay)
                    'priority' => 10, //Determines the order this control appears in for the specified section
                    'section' => 'section_couleur', //ID of the section this control should render in (can be one of yours, or a WordPress default section)
                )
            ));
            }

        //********************
        // TYPOGRAPHIE
        //********************
        // 1. Création d'une nouvelle section dans le Theme Customizer
        $wp_customize->add_section('section_typo', array(
            'title' => 'Gestion de la police',
            'priority' => 20,
            'panel' => 'panel_communet',
        ));
        // 2. Enregistrement d'un nouveau paramètre dans la base WP
        $wp_customize->add_setting(
            'police_site', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
            array(
                'default' => '', //Default setting/value to save
                'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
            )
        );
        $wp_customize->add_control(
            new WP_Customize_Control(
                $wp_customize,
                'communet_police_site',
                array(
                    'label' => __('Selection de la typo', 'theme_name'),
                    'section' => 'section_typo',
                    'settings' => 'police_site',
                    'type' => 'select',
                    'choices' => self::selectListePolices
                )
            )
        );

        //********************
        // IMAGES
        //********************
        /*         * ******* HEADER ******** */
        // 1. Création d'une nouvelle section dans le Theme Customizer
        $wp_customize->add_section('section_images', array(
            'title' => 'Gestion des images',
            'priority' => 20,
            'panel' => 'panel_communet',
        ));
        // 2. Enregistrement d'un nouveau paramètre dans la base WP
        $wp_customize->add_setting(
            'logo_header', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
            array(
                'default' => '', //Default setting/value to save
                'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
            )
        );
        $wp_customize->add_control(
            new WP_Customize_Image_Control(
                $wp_customize,
                'communet_logo_header',
                array(
                    'label' => __('Choisir un logo Header', 'theme_name'),
                    'section' => 'section_images',
                    'settings' => 'logo_header',
                    'context' => 'your_setting_context'
                )
            )
        );
        /*         * ******* FOOTER ******** */
        // 2. Enregistrement d'un nouveau paramètre dans la base WP
        $wp_customize->add_setting(
            'logo_footer', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
            array(
                'default' => '', //Default setting/value to save
                'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
            )
        );
        $wp_customize->add_control(
            new WP_Customize_Image_Control(
                $wp_customize,
                'communet_logo_footer',
                array(
                    'label' => __('Choisir un logo Footer', 'theme_name'),
                    'section' => 'section_images',
                    'settings' => 'logo_footer',
                    'context' => 'your_setting_context'
                )
            )
        );
        /*         * ******* IMAGE PAR DEFAUT ******** */
        // 2. Enregistrement d'un nouveau paramètre dans la base WP
        $wp_customize->add_setting(
            'image_defaut', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
            array(
                'default' => '', //Default setting/value to save
                'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
            )
        );
        $wp_customize->add_control(
            new WP_Customize_Image_Control(
                $wp_customize,
                'communet_image_defaut',
                array(
                    'label' => __('Choisir une image par défaut', 'theme_name'),
                    'section' => 'section_images',
                    'settings' => 'image_defaut',
                    'context' => 'your_setting_context'
                )
            )
        );

        /*         * ******* PARAMETRAGE ******** */
        // 1. Création d'une nouvelle section dans le Theme Customizer
        $wp_customize->add_section('section_parametres', array(
            'title' => 'Paramétrage',
            'priority' => 30,
            'panel' => 'panel_communet',
        ));
        // 2. Enregistrement d'un nouveau paramètre dans la base WP
        $wp_customize->add_setting(
            'parametre_onepage', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
            array(
                'default' => '', //Default setting/value to save
                'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
            )
        );
        $wp_customize->add_control(
            new WP_Customize_Control(
                $wp_customize,
                'communet_parametre_onepage',
                array(
                    'label' => __('Site onepage?', 'theme_name'),
                    'section' => 'section_parametres',
                    'settings' => 'parametre_onepage',
                    'type' => 'checkbox',
                )
            )
        );
        // 2. Enregistrement d'un nouveau paramètre dans la base WP
        $wp_customize->add_setting(
            'parametre_newsletter', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
            array(
                'default' => '', //Default setting/value to save
                'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'?
                'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting.
                'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)?
            )
        );
        $wp_customize->add_control(
            new WP_Customize_Control(
                $wp_customize,
                'communet_parametre_newsletter',
                array(
                    'label' => __('Activer newsletter?', 'theme_name'),
                    'section' => 'section_parametres',
                    'settings' => 'parametre_newsletter',
                    'type' => 'checkbox',
                )
            )
        );


        //4. We can also change built-in settings by modifying properties. For instance, let's make some stuff use live preview JS...
        $wp_customize->get_setting('blogname')->transport = 'postMessage';
        $wp_customize->get_setting('blogdescription')->transport = 'postMessage';
        $wp_customize->get_setting('header_textcolor')->transport = 'postMessage';
        $wp_customize->get_setting('background_color')->transport = 'postMessage';
        $wp_customize->get_setting('police_site')->transport = 'postMessage';
        $wp_customize->get_setting('logo_header')->transport = 'postMessage';
        $wp_customize->get_setting('logo_footer')->transport = 'postMessage';
        $wp_customize->get_setting('image_defaut')->transport = 'postMessage';
        }

    /**
     * This will output the custom WordPress settings to the live theme's WP head.
     *
     * Used by hook: 'wp_head'
     *
     * @see add_action('wp_head',$func)
     * @since MyTheme 1.0
     */
    public static function header_output()
        {
        ?>
        <!--Customizer CSS-->
        <style type="text/css">
            <?php self::generate_css('#site-title a', 'color', 'header_textcolor', '#'); ?>
            <?php self::generate_css('body', 'background-color', 'background_color', '#'); ?>
            <?php self::generate_css('a', 'color', 'link_textcolor'); ?>
            <?php self::generate_css('.header--direct', 'background-color', 'header_direct_bg_color'); ?>
            <?php self::generate_css('body', 'font-family', 'typo_site'); ?>
        </style>
        <!--/Customizer CSS-->
        <?php
        }

    /**
     * Génère la feuille de style avec les informations du mod_theme
     *
     * Used by hook: 'customize_save_after'
     *
     */
    public static function generate_css_frontend()
        {
        // Récupération de la feuille de style modèle
        $url = get_template_directory() . '/css/styleModele.css';
        $cssContent = file_get_contents($url);
        for ($i = 1; $i <= 5; $i++) {
            $cssContent = self::generate_css('couleur_site_' . $i, $cssContent);
            $cssContent = self::generate_css('couleur_police_' . $i, $cssContent);
            }
        $cssContent = self::generate_css('police_site', $cssContent);

        // Ajout des styles la feuille appelée en front-end
        $fileCss = get_template_directory() . '/css/styleA111.css';
        if (file_exists($fileCss)) {
            file_put_contents($fileCss, $cssContent);
            }
        }

    /**
     * This outputs the javascript needed to automate the live settings preview.
     * Also keep in mind that this function isn't necessary unless your settings
     * are using 'transport'=>'postMessage' instead of the default 'transport'
     * => 'refresh'
     *
     * Used by hook: 'customize_preview_init'
     *
     * @see add_action('customize_preview_init',$func)
     * @since MyTheme 1.0
     */
    public static function live_preview()
        {
        wp_enqueue_script(
            'mytheme-themecustomizer', // Give the script a unique ID
            get_template_directory_uri() . '/inc/customizer/js/theme-customizer.js', // Define the path to the JS file
            array('jquery', 'customize-preview'), // Define dependencies
            '', // Define a version (optional)
            true // Specify whether to put in footer (leave this true)
        );
        }

    /**
     * This will generate a line of CSS for use in header output. If the setting
     * ($mod_name) has no defined value, the CSS will not be output.
     *
     * @uses get_theme_mod()
     * @param string $selector CSS selector
     * @param string $style The name of the CSS *property* to modify
     * @param string $mod_name The name of the 'theme_mod' option to fetch
     * @param string $prefix Optional. Anything that needs to be output before the CSS property
     * @param string $postfix Optional. Anything that needs to be output after the CSS property
     * @param bool $echo Optional. Whether to print directly to the page (default: true).
     * @return string Returns a single line of CSS with selectors and a property.
     * @since MyTheme 1.0
     */
    public static function generate_css($mod_name, $cssContent)
        {

        $mod = get_theme_mod($mod_name);
        if ($mod_name == 'police_site') {
            $tabMod = explode('|', $mod);
            $mod = $tabMod[1];
            }
        if (!empty($mod)) {

            $cssContent = str_replace('[' . strtoupper($mod_name) . ']', $mod, $cssContent);
            }

        return $cssContent;
        }

    }
