<?php
/**
 * Contains methods for customizing the theme customization screen.
 *
 * @since Edition 1.0
 */
global $tw_categories;
$tw_categories = get_categories(); // get categories once

class Themewich_Customize {
   /**
    * This hooks into 'customize_register' (available as of WP 3.4) and allows
    * you to add new sections and controls to the Theme Customize screen.
    *
    * Note: To enable instant preview, we have to actually write a bit of custom
    * javascript. See live_preview() for more.
    *
    * @see add_action('customize_register',$func)
    * @param \WP_Customize_Manager $wp_customize
    * @since Edition 1.0
    */

   public static function register ( $wp_customize ) {

      // Define a new section to the Theme Customizer
      $wp_customize->add_section( 'themewich_options',
         array(
            'title'       => __( 'Color Options', 'themewich' ), // Visible title of section
            'priority'    => 35, // Determines what order this appears in
            'capability'  => 'edit_theme_options', // Capability needed to tweak
            'description' => __('Adjust the themes colors.', 'themewich'), // Descriptive tooltip
         )
      );

      // Register new settings to the WP database...
      $wp_customize->add_setting( 'highlight_color', // No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
         array(
            'default'     => '#00a498',             // Default setting/value to save
            'type'        => 'theme_mod',              // Is this an 'option' or a 'theme_mod'?
            'capability'  => 'edit_theme_options',  // Special permissions for accessing this setting.
            'transport'   => 'refresh',         // Set to 'postMessage' for instant color change
            'sanitize_callback' => 'sanitize_hex_color',
         )
      );

      // Register new settings to the WP database...
      $wp_customize->add_setting( 'tw_background_color', // No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
         array(
            'default'     => '#f3f3f3',             // Default setting/value to save
            'type'        => 'theme_mod',              // Is this an 'option' or a 'theme_mod'?
            'capability'  => 'edit_theme_options',  // Special permissions for accessing this setting.
            'transport'   => 'refresh',         // Set to 'postMessage' for instant color change
            'sanitize_callback' => 'sanitize_hex_color',
         )
      );

      // Define the control itself (which links a setting to a section and renders the HTML controls)...
      $wp_customize->add_control( new WP_Customize_Color_Control( //Instantiate the color control class
         $wp_customize, //Pass the $wp_customize object (required)
         'themewich_highlight_color', // Set a unique ID for the control
         array(
            'label' => __( 'Highlight Color', 'themewich' ), //Admin-visible name of the control
            'section' => 'colors', //ID of the section this control should render in (can be one of yours, or a WordPress default section)
            'settings' => 'highlight_color', //Which setting to load and manipulate (serialized is okay)
            'priority' => 10, //Determines the order this control appears in for the specified section
         )
      ) );

      // Define the control itself (which links a setting to a section and renders the HTML controls)...
      $wp_customize->add_control( new WP_Customize_Color_Control( //Instantiate the color control class
         $wp_customize, //Pass the $wp_customize object (required)
         'themewich_background_color', // Set a unique ID for the control
         array(
            'label' => __( 'Background Color', 'themewich' ), //Admin-visible name of the control
            'section' => 'colors', //ID of the section this control should render in (can be one of yours, or a WordPress default section)
            'settings' => 'tw_background_color', //Which setting to load and manipulate (serialized is okay)
            'priority' => 11, //Determines the order this control appears in for the specified section
         )
      ) );

      /**
       * Get All Categories
       */
      global $tw_categories;
      foreach($tw_categories as $category) {

        // Register new settings to the WP database...
        $wp_customize->add_setting( 'highlight_color_' . $category->term_id, // No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record
           array(
              'default'     => '#00a498',             // Default setting/value to save
              'type'        => 'theme_mod',              // Is this an 'option' or a 'theme_mod'?
              'capability'  => 'edit_theme_options',  // Special permissions for accessing this setting.
              'transport'   => 'refresh',         // Set to 'postMessage' for instant color change
              'sanitize_callback' => 'sanitize_hex_color',
           )
        );

        // Define the control itself (which links a setting to a section and renders the HTML controls)...
        $wp_customize->add_control( new WP_Customize_Color_Control( //Instantiate the color control class
           $wp_customize, //Pass the $wp_customize object (required)
           'themewich_highlight_color' . $category->term_id, // Set a unique ID for the control
           array(
              'label' => $category->name . ' ' . __( 'Category Color', 'themewich' ), //Admin-visible name of the control
              'section' => 'colors', //ID of the section this control should render in (can be one of yours, or a WordPress default section)
              'settings' => 'highlight_color_' . $category->term_id, //Which setting to load and manipulate (serialized is okay)
              'priority' => 12, //Determines the order this control appears in for the specified section
           )
        ) );

       // $wp_customize->get_setting( 'highlight_color_' . $category->term_id )->transport = 'postMessage';

      }

      // 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( 'highlight_color' )->transport = 'postMessage';
      $wp_customize->get_setting( 'tw_background_color' )->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 Edition 1.0
    */
   public static function header_output() {

      /**
       * Site Background
       * @var string
       */
      $siteBackground =
        '#sitecontainer,
        .rightside,
        .sidebar,
        .pagination .pagenumbers,
        .woocommerce nav.woocommerce-pagination .page-numbers,
        .full-post .full-image-section .fullcontent,
        .tw-tabs-shortcode .ui-state-active,
        .tw-tabs-shortcode .ui-widget-content .ui-state-active,
        .tw-tabs-shortcode .ui-widget-header .ui-state-active';

      /**
       * Backgrounds
       * @var string
       */
      $backgrounds =
        '.badge a,
        .widget .tagcloud a,
        .woocommerce span.onsale,
        .badgesliver.highlight, .sharing a .sharecircle,
        .tabswrap ul.tabs li a.active, .tabswrap ul.tabs li a:hover,
        .woocommerce div.product .woocommerce-tabs ul.tabs li.active,
        .breakdown .line,
        .woocommerce #respond input#submit.alt,
        .woocommerce a.button.alt,
        .woocommerce button.button.alt,
        .woocommerce input.button.alt';

        /**
         * Border Colors
         * @var string
         */
      $borderColors =
        '.pagetitleloading .pagercontainer #bx-pager a.active,
        .pagetitleloading .pagercontainer #bx-pager a:hover,
        a.more-link, .regular-posts a.more-link, .woocommerce a.button,
        .woocommerce #respond input#submit.alt, .woocommerce a.button.alt,
        .woocommerce #respond input#submit, .woocommerce input.button,
        .woocommerce button.button.alt, .woocommerce input.button.alt,
        .pie, .c100 .bar, .c100.p51 .fill, .c100.p52 .fill,
        .c100.p53 .fill, .c100.p54 .fill, .c100.p55 .fill,
        .c100.p56 .fill, .c100.p57 .fill, .c100.p58 .fill,
        .c100.p59 .fill, .c100.p60 .fill, .c100.p61 .fill,
        .c100.p62 .fill, .c100.p63 .fill, .c100.p64 .fill,
        .c100.p65 .fill, .c100.p66 .fill, .c100.p67 .fill,
        .c100.p68 .fill, .c100.p69 .fill, .c100.p70 .fill,
        .c100.p71 .fill, .c100.p72 .fill, .c100.p73 .fill,
        .c100.p74 .fill, .c100.p75 .fill, .c100.p76 .fill,
        .c100.p77 .fill, .c100.p78 .fill, .c100.p79 .fill,
        .c100.p80 .fill, .c100.p81 .fill, .c100.p82 .fill,
        .c100.p83 .fill, .c100.p84 .fill, .c100.p85 .fill,
        .c100.p86 .fill, .c100.p87 .fill, .c100.p88 .fill,
        .c100.p89 .fill, .c100.p90 .fill, .c100.p91 .fill,
        .c100.p92 .fill, .c100.p93 .fill, .c100.p94 .fill,
        .c100.p95 .fill, .c100.p96 .fill, .c100.p97 .fill,
        .c100.p98 .fill, .c100.p99 .fill, .c100.p100 .fill,
        .tw-button, a.tw-button, .tw-postshortcode a.more-link';

      /**
       * Colors styles
       * @var string
       */
      $colors =
        'a, a:hover, #share-box span, .thumbintro span a,
        .c100:hover > span, a.more-link,
        span.highlight,
        .score,
        .button,
        .tw-button,
        a.tw-button,
        a.button,
        a.more-link,
        .woocommerce a.button,
        .woocommerce ul.products li.product .price,
        .woocommerce .woocommerce-product-rating .star-rating,
        .woocommerce #respond input#submit, .woocommerce input.button,
        #submit,
        input[type=button],
        .tw-postshortcode a.more-link,
        input[type=submit],
        .single .authorinfo.not-full a:hover,
        .tw-button, a.tw-button, .tw-postshortcode a.more-link';

      /**
       * Hover background style
       * @var string
       */
      $hoverBackgrounds =
        '.tabswrap ul.tabs a:hover, a.more-link:hover,
        .regular-posts a.more-link:hover,.button:hover,
        .tw-button:hover,
        a.tw-button:hover,
        a.button:hover,
        a.more-link:hover,
        .woocommerce a.button:hover,
        .woocommerce #respond input#submit:hover, .woocommerce input.button:hover,
        #submit:hover,
        .tw-postshortcode a.more-link:hover,
        input[type=submit]:hover,
        input[type=button]:hover,
        .button:active,
        .tw-button:active,
        a.tw-button:active,
        a.button:active,
        a.more-link:active,
        #submit:active,
        .tw-postshortcode a.more-link:active,
        input[type=submit]:active,
        input[type=button]:active';

      /**
       * Border Colors Pseudo Styles
       * @var string
       */
      $borders =
        '.pagetitleloading .pagercontainer .bx-slider-pager a.active,
        .pagetitleloading .pagercontainer .bx-slider-pager a:hover,
        .button,
        .tw-button,
        a.tw-button,
        a.button,
        a.more-link,
        #submit,
        .tw-postshortcode a.more-link,
        input[type=submit],
        input[type=button],
        .top-nav.altnav #menu > ul > li > a:hover,
        .top-nav.altnav #menu > ul > li.sfHover > a,
        .top-nav.altnav #menu > ul > li.current_page_item > a';

      /**
       * Right Border Colors Pseudo Styles
       * @var string
       */
      $rightBorders =
        '.badge a:before, .badgesliver.highlight:before';

      /**
       * Left Border Colors Pseudo Styles
       * @var string
       */
      $leftBorders =
        '.badge a:after, .badgesliver.highlight:after';

      /**
       * Category Colors
       * @var string
       */
      global $tw_categories;
      foreach($tw_categories as $category) {

        $cat_class = '.highlight_category_' . $category->term_id;

        /**
         * Background Color
         */
        $catbg[$category->term_id] =
          '.badge a.category-' . $category->term_id . ',
          ' . $cat_class  . ' a.more-link:hover,
          ' . $cat_class . ' .tagcloud.badge a,
          ' . $cat_class . ' .widget .tagcloud a,
          ' . $cat_class . ' .sharing a.post-share .sharecircle,
          ' . $cat_class . ' input[type=submit]:hover,
          ' . $cat_class . ' #submit:hover,
          ' . $cat_class . ' .breakdown .line,
          ' . $cat_class . ' .ie8 .c100,
          ' . $cat_class . ' .ie8 .section .c100,
          ' . $cat_class . ' .ie8 .section .inner-content .c100';

        $cat_color[$category->term_id] =
          $cat_class . ' .postcontent p a,
          .tiny-details a.category-' . $category->term_id. ':hover,
          ' . $cat_class . ' .commentwrapper p a,
          ' . $cat_class . ' .singlecomment a:hover,
          ' . $cat_class . ' #respond a:hover,
          ' . $cat_class . ' .postcontent p a:hover,
          ' . $cat_class . ' #share-box span,
          ' . $cat_class . ' .breakdown .c100:hover > span,
          ' . $cat_class . ' .reviewtop .c100:hover > span,
          ' . $cat_class . ' .score,
          ' . $cat_class . ' .tw-button,
          ' . $cat_class . ' a.tw-button,
          ' . $cat_class . ' a.button,
          ' . $cat_class . ' a:hover,
          ' . $cat_class . ' a.more-link,
          ' . $cat_class . ' #submit,
          ' . $cat_class . ' .tw-postshortcode a.more-link,
          ' . $cat_class . ' input[type=submit],
          ' . $cat_class . ' .authorinfo.not-full a:hover';

        /**
         * Border Color
         */
        $cat_border[$category->term_id] =
          $cat_class . ' .pie,
          ' . $cat_class . ' .c100 .bar,
          ' . $cat_class . ' .c100 .fill,
          ' . $cat_class . ' a.more-link,
          ' . $cat_class . ' #submit,
          ' . $cat_class . ' input[type=submit],
          .pagetitleloading .pagercontainer .bx-slider-pager ' . $cat_class . ' a.active,
          .pagetitleloading .pagercontainer .bx-slider-pager ' . $cat_class . ' a:hover';

        /**
         * Border Left Color
         */
        $cat_left_border[$category->term_id] =
          '.badge a.category-' . $category->term_id . ':after,
          .single ' . $cat_class . ' .tagcloud.badge a:after';

        /**
         * Border Right Color
         */
        $cat_right_border[$category->term_id] =
          '.badge a.category-' . $category->term_id . ':before,
          .single ' . $cat_class . ' .tagcloud.badge a:before';
      }
    ?>

      <!--Customizer CSS-->
      <style type="text/css">
           <?php self::generate_css($siteBackground, 'background', 'tw_background_color'); ?>
           <?php self::generate_css($backgrounds, 'background', 'highlight_color'); ?>
           <?php self::generate_css($borderColors, 'border-color', 'highlight_color'); ?>
           <?php self::generate_css($colors, 'color', 'highlight_color'); ?>
           <?php self::generate_css($hoverBackgrounds, 'background', 'highlight_color'); ?>
           <?php self::generate_css($borders, 'border-color', 'highlight_color'); ?>
           <?php self::generate_css($rightBorders, 'border-right-color', 'highlight_color'); ?>
           <?php self::generate_css($leftBorders, 'border-left-color', 'highlight_color'); ?>
           <?php self::generate_css('*::selection', 'background', 'highlight_color'); ?>
           <?php
             // Generate each category css value
             foreach($tw_categories as $category) {
                self::generate_css($catbg[$category->term_id], 'background', 'highlight_color_' . $category->term_id);
                self::generate_css($cat_color[$category->term_id], 'color', 'highlight_color_' . $category->term_id);
                self::generate_css($cat_border[$category->term_id], 'border-color', 'highlight_color_' . $category->term_id);
                self::generate_css($cat_left_border[$category->term_id], 'border-left-color', 'highlight_color_' . $category->term_id);
                self::generate_css($cat_right_border[$category->term_id], 'border-right-color', 'highlight_color_' . $category->term_id);
             }

           ?>
      </style>
      <!--Customizer CSS-->

      <?php
   }

   /**
    * 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 Edition 1.0
    */
   public static function live_preview() {
    global $themewich_theme_info;
      wp_enqueue_script(
        'themewich-themecustomizer',        //Give the script an ID
        get_template_directory_uri().'/js/theme-customizer.js',  //Point to file
        array( 'jquery','customize-preview' ),  //Define dependencies
        $themewich_theme_info->Version,     //Define a version
        true                    //Put script in footer
      );
   }

    /**
     * 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 Edition 1.0
     */
    public static function generate_css( $selector, $style, $mod_name, $prefix='', $postfix='', $echo=true ) {
      $return = '/* No CSS */';
      $mod = get_theme_mod($mod_name);
      if ( ! empty( $mod ) ) {
         $return = sprintf('%s { %s:%s; }',
            $selector,
            $style,
            $prefix.$mod.$postfix
         );
         if ( $echo ) {
            echo htmlspecialchars_decode( esc_html( $return ) );
         }
      }
      return $return;
    }
}

// Setup the Theme Customizer settings and controls...
add_action( 'customize_register' , array( 'Themewich_Customize' , 'register' ) );

// Output custom CSS to live site
add_action( 'wp_head', array( 'Themewich_Customize' , 'header_output' ) );

// Enqueue live preview javascript in Theme Customizer admin screen
// add_action( 'customize_preview_init' , array( 'Themewich_Customize' , 'live_preview' ) );