<?php

# REQUIRED: Could not find the comment-reply script enqueued.
function newborn_enqueue_comments_reply() {
  if( get_option( 'thread_comments' ) ) {
    wp_enqueue_script( 'comment-reply' );
  }
}
add_action( 'comment_form_before', 'newborn_enqueue_comments_reply' );

# Fix for card.portfolio TODO
function fix_for_cardportfolio($classes) {
  if( is_search() ) {
    $index = array_search('portfolio', $classes);
    if ($index !== FALSE)
      array_splice($classes, $index, 1);
  }
  return $classes;
}
add_filter( 'post_class', 'fix_for_cardportfolio' );


# Loading scripts in admin
function load_scripts() {
  wp_enqueue_script('kob-admin-requires-jquery',    "https://code.jquery.com/jquery-1.12.4.min.js", false );
  wp_enqueue_script('kob-admin-requires-jquery-ui', "https://code.jquery.com/ui/1.12.1/jquery-ui.min.js", false );
  wp_enqueue_style('kob-admin-requires-fa', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css');
}
add_action( 'admin_enqueue_scripts', 'load_scripts' );


# Theme initialization
function themeInit() {
  register_nav_menu('primary-menu',   __('Primary Menu', 'reddy'));
  register_nav_menu('secondary-menu', __('Secondary Menu', 'reddy'));
}
add_action('init', 'themeInit');


# Theme supports
function afterSetup() {
  add_theme_support( 'post-thumbnails' );
  add_theme_support( 'post-formats', array( 'post', 'audio', 'video') );
  add_theme_support( 'html5', array(
    'search-form',
    'comment-form',
    'comment-list',
    'gallery',
    'caption',
  ) );
  add_theme_support( 'title-tag' );
  add_theme_support( 'automatic-feed-links' );
}
add_action( 'after_setup_theme', 'afterSetup' );


if ( ! isset( $content_width ) ) {
	$content_width = 600;
}


# Process contact form submission
function process_contact() {
  try {
    if ( empty($_POST) || !wp_verify_nonce( $_POST['security-code-here'], 'contact' ) )
      throw new Exception('Security code error');
    if ( !isset($_REQUEST['contact_name']) || $_REQUEST['contact_name'] == '' )
      throw new Exception('Name is not set'); //echo json_decode((object)array('status' => 'fail', 'error' => 'Some of the fields are not '))
    if ( !isset($_REQUEST['contact_message']) || $_REQUEST['contact_message'] == '' )
      throw new Exception('Message is not set'); //echo json_decode((object)array('status' => 'fail', 'error' => 'Some of the fields are not '))
    if ( !isset($_REQUEST['contact_email']) || $_REQUEST['contact_email'] == '' )
      throw new Exception('Email is not set'); //echo json_decode((object)array('status' => 'fail', 'error' => 'Some of the fields are not '))
    $contact = get_kob_object( 'contact_settings' );
    $to = $contact->contact_many->contact_form->value;
    if ( !$to || $contact->contact_many->contact_form->flag == false )
      $to = get_option('admin_email');
    $form_name    = $_REQUEST['contact_name'];
    $form_email   = $_REQUEST['contact_email'];
    $form_message = $_REQUEST['contact_message'];
    $subject = 'Contact Form submitted';
    $text  = $form_message;
    $text .= "\n" . 'From ' . $form_name . ' (' . $form_email . ')';
    $text .= "\n" . 'This letter was generated by robot, please do not answer this';
    $send_result = wp_mail( $to, $subject, $text );
    if( !$send_result )
      throw new Exception('Error while sending message');
    echo json_encode((object)array('status' => 'ok', 'text' => 'Form submitted successfully'));
  } catch (Exception $e) {
    echo json_encode((object)array('status' => 'fail', 'text' => $e->getMessage()));
  }
  wp_die();
}
add_action('wp_ajax_contact', 'process_contact');
add_action('wp_ajax_nopriv_contact', 'process_contact');


# Process subscribe form submission
function process_subscribe() {
  try {
    if ( empty($_POST) || !wp_verify_nonce( $_POST['security-code-here'], 'subscribe' ) )
      throw new Exception('Security code error');
    $prefooter = get_kob_object('prefooter_settings');
    $raw_api_key = $prefooter->prefooter_many->prefooter_columns->content->prefooter_column_subscribe->value->prefooter_column_subscribe_val_subtitle_api_key;
    $api_key_tokens = explode('-', $raw_api_key);
    $list_id = $prefooter->prefooter_many->prefooter_columns->content->prefooter_column_subscribe->value->prefooter_column_subscribe_val_subtitle_api_list;
    $api_key = $api_key_tokens[0]; // '54f86fa9704cfe780c843b03fa19c0aa';
    $dc      = $api_key_tokens[1]; // дата-центр MailChimp
    $email   = $_REQUEST['email'];
    $url     = "https://$dc.api.mailchimp.com/2.0/lists/subscribe.json";
    $request = wp_remote_post( $url, array(
      'body' => json_encode( array(
          'apikey' => $api_key,
          'id' => $list_id,
          'email' => array( 'email' => $email ),
      ) ),
    ) );
    $result = json_decode( wp_remote_retrieve_body( $request ) );
    if ( $result->status == 'error' )
      throw new Exception('Error while subscribing: ' . $result->error);
    echo json_encode((object)array('status' => 'ok', 'text' => 'Successfully subscribed!'));
  } catch (Exception $e) {
    echo json_encode((object)array('status' => 'fail', 'text' => $e->getMessage()));
  }
  wp_die();
}
add_action('wp_ajax_subscribe', 'process_subscribe');
add_action('wp_ajax_nopriv_subscribe', 'process_subscribe');


# Add woocommerce support
function woocommerce_support() {
  add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'woocommerce_support' );


# Add reddy-section to wp admin bar's "customize" button
function customize_toolbar() {
  global $wp_admin_bar;
  $arr = $wp_admin_bar->get_nodes();
  if ( isset( $arr['customize'] ) ) {
    $customize = $arr['customize'];
    if ( is_post_type_archive( 'portfolio' ) )
      $customize->href = admin_url( 'customize.php?reddy-section=section_portfolio&url=' . get_post_type_archive_link( 'portfolio' ) );
    if ( is_page_template( 'templates/slider-page.php' ) )
      $customize->href = admin_url( 'customize.php?reddy-section=section_slider&url=' . get_permalink() );
    if ( is_page_template( 'templates/contact-page.php' ) )
      $customize->href = admin_url( 'customize.php?reddy-section=section_contact&url=' . get_permalink() );
    if ( is_home() )
      $customize->href = admin_url( 'customize.php?reddy-section=section_blog&url=' . home_url('/') );
    if ( is_category() ) {
      $categories = get_the_category();
      $category_id = $categories[0]->cat_ID;
      $customize->href = admin_url( 'customize.php?reddy-section=section_blog&url=' . get_category_link( $category_id ) );
    }
    if ( is_singular( 'portfolio' ) ) {
      $customize->href = admin_url( 'customize.php?reddy-section=section_portfolio&url=' . get_permalink() );
    }
    foreach($arr as $key => $node) {
      if( $node->id == 'customize' )
        $node = $customize;
      $wp_admin_bar->remove_node( $key );
      $wp_admin_bar->add_node( $node );
    }
  }
}
add_action( 'wp_before_admin_bar_render', 'customize_toolbar', 999  );


# Excerpt end to ellipsis
function new_excerpt_more( $more ) {
  return '...';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );


# Excert length to 20
function custom_excerpt_length( $length ) {
  return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );


# Add .img-unwrap to embed p's
function filter_ptags_on_embeds($content) {
  $content = preg_replace('/<p>(\s*)(<ifram e.*\/?>)(\s*)<\/p>/iU', '<p class="embed-unwrap">\2</p>', $content);
  $content = preg_replace('/<p>(\s*)(<iframe.*>.*<\/iframe>)(\s*)<\/p>/iU', '<p class="embed-unwrap">\2</p>', $content);
  $content = preg_replace('/<p>(\s*)(<embed.*>)(\s*)<\/p>/iU', '<p class="embed-unwrap">\2</p>', $content);
  $content = preg_replace('/<p>(\s*)(<embed.*>.*<\/embed>)(\s*)<\/p>/iU', '<p class="embed-unwrap">\2</p>', $content);
  return $content;
}
add_filter('the_content', 'filter_ptags_on_embeds');
