<?php

// -------------------------------------------
// fp_wp_simply_good_iga
define( 'THEME_ACTIONS_DIR',    plugin_dir_path( __FILE__ ) . 'functions/actions/' );
define( 'THEME_SHORTCODE_DIR',  plugin_dir_path( __FILE__ ) . 'functions/shortcodes/' );

require_once( THEME_ACTIONS_DIR . 'actions.php' );
require_once( THEME_SHORTCODE_DIR . 'shortcodes.php' );

add_action('after_setup_theme', 'fp_wp_simply_good_iga_setup');
function fp_wp_simply_good_iga_setup()
{
    load_theme_textdomain('fp_wp_simply_good_iga', get_template_directory() . '/languages');
    add_theme_support('automatic-feed-links');
    add_theme_support('post-thumbnails');
    global $content_width;
    if (!isset($content_width))
        $content_width = 640;
    register_nav_menus(array(
        'additional-menu' => __( 'Header | Additional Menu', 'fp_wp_simply_good_iga' )
        ,'header-menu' => __( 'Header | Top Menu', 'fp_wp_simply_good_iga' )
		,'main-menu' => __('NAV: Main Menu', 'fp_wp_simply_good_iga')
		,'off-canvas-menu' => __('NAV: Off Canvas/Mobile', 'fp_wp_simply_good_iga')
		,'twoitem-menu' => __('2 Item Menu - New Theme Only', 'fp_wp_simply_good_iga')
        ,'footer-menu-col-1' => __( 'Footer Desktop Menu Col-1', 'fp_wp_simply_good_iga' )
        ,'footer-menu-col-2' => __( 'Footer Desktop Menu Col-2', 'fp_wp_simply_good_iga' )
        ,'footer-menu-col-3' => __( 'Footer Desktop Menu Col-3', 'fp_wp_simply_good_iga' )
		,'footer-menu-col-4' => __( 'Footer Desktop Menu Col-4', 'fp_wp_simply_good_iga' )
		,'footer-menu-copyright' => __( 'Footer Menu Copyright', 'fp_wp_simply_good_iga' )
    ));

    global $theme_logo_image_name;
    global $theme_logo_mobile_image_name;
    global $theme_logo_image_url;
    global $theme_favicon;
    global $theme_header_layout;
    global $theme_footer_copyright;
    global $theme_home_email_icon;
    global $theme_has_physical_store;
    global $theme_has_social_media;
    global $additional_store_links;
    global $theme_breadcrumb_always_displayed;
    global $theme_container_class;

    global $theme_newsletter_title;
    global $theme_newsletter_subtitle;


    if(!isset($theme_container_class)) $theme_container_class = 'container-fluid';
    if(!isset($theme_logo_image_name)) $theme_logo_image_name = 'logo.png';
    if(!isset($theme_logo_mobile_image_name)) $theme_logo_mobile_image_name = 'logo.png';
    if(!isset($theme_logo_image_url)) $theme_logo_image_url = get_stylesheet_directory_uri() . '/resources/images/logo/' . $theme_logo_image_name;

    if(!isset($theme_favicon)) $theme_favicon = '<link rel="shortcut icon" type="image/x-icon" href="' . get_stylesheet_directory_uri() . '/favicon/favicon.ico" />
        <link rel="apple-touch-icon" href="' . get_stylesheet_directory_uri() . '/favicon/apple-touch-icon.png" />
        <link rel="icon" type="image/png" href="' . get_stylesheet_directory_uri() . '/favicon/favicon-32x32.png" sizes="32x32" />
        <link rel="icon" type="image/png" href="' . get_stylesheet_directory_uri() . '/favicon/favicon-16x16.png" sizes="16x16" />';

    if(!isset($additional_store_links)) $additional_store_links = '<div><a href="/recipes" class="">View Recipes</a></div> ';

    if(!isset($theme_footer_copyright)) $theme_footer_copyright = '&copy; ' . date("Y") . ' ' . get_bloginfo('name');

    if(!isset($theme_home_email_icon)) $theme_home_email_icon = 'large-email-icon.png';

    if(!isset($theme_has_physical_store)) $theme_has_physical_store = false;

    if(!isset($theme_has_social_media)) $theme_has_social_media = false;
    if(!isset($theme_breadcrumb_always_displayed)) $theme_breadcrumb_always_displayed = false;

    if(!isset($theme_newsletter_title)) $theme_newsletter_title = 'Sign up for our newsletter';
    if(!isset($theme_newsletter_subtitle)) $theme_newsletter_subtitle = '';
}

add_action('comment_form_before', 'fp_wp_simply_good_iga_enqueue_comment_reply_script');
function fp_wp_simply_good_iga_enqueue_comment_reply_script()
{
    if (get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}

add_filter('the_title', 'fp_wp_simply_good_iga_title');
function fp_wp_simply_good_iga_title($title)
{
    if ($title == '') {
        return '&rarr;';
    } else {
        return $title;
    }
}

add_filter('wp_title', 'fp_wp_simply_good_iga_filter_wp_title');
function fp_wp_simply_good_iga_filter_wp_title($title)
{
    return $title . esc_attr(get_bloginfo('name'));
}

add_action('widgets_init', 'fp_wp_simply_good_iga_widgets_init');
function fp_wp_simply_good_iga_widgets_init()
{
    register_sidebar(array(
        'name' => __('Sidebar Widget Area', 'fp_wp_simply_good_iga'),
        'id' => 'primary-widget-area',
        'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
        'after_widget' => "</li>",
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>'
    ));
}

function fp_wp_simply_good_iga_custom_pings($comment)
{
    $GLOBALS['comment'] = $comment;
    ?>
    <li <?php
    comment_class();
    ?> id="li-comment-<?php
    comment_ID();
    ?>"><?php
        echo comment_author_link();
        ?></li>
    <?php
}

function posts_custom_column_views($column_name, $id){
    if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

add_filter( 'caldera_forms_mailer', 'fp_wp_simply_good_igaaldera_forms_mailer', 100, 3 );
function fp_wp_simply_good_igaaldera_forms_mailer( $mail, $data, $form){
    $contact_store_id = 0;

    foreach ($form as $key => $value) {
        if($key == 'name'){
            $form_name = $value;
            break;
        }
    }

    if($form_name == "Contact Form Customized Send" || $form_name == "We've Got You Covered - Large Parties & Corporate Orders"){
        foreach ($data as $key => $value) {
            if(!empty($value) && strpos($value, 'store_id:') !== false){
                $contact_store_id = substr($value, strpos($value, ":")+1, strlen($value));
                break;
            }
        }

        if(intval($contact_store_id) > 0){
            $send_to_email = get_store_contact_email($contact_store_id);

            if(!empty($send_to_email)) {
                $mail[ 'recipients' ] = explode(',', $send_to_email);
            }
        }
        else $send_to_email = get_store_contact_email('no-store-selected');
    }

    return $mail;
}

function get_store_contact_email($store_id = '') {
    // get email address based on store number
    $send_to_email = '';

    if(intval($store_id)) {
        $posts = get_posts(array(
            'post_type' => 'stores',
            'numberposts' => 1,
            'meta_query' => array(array('key' => 'wpcf-store-id', 'value' => $store_id))
        ));
    }
    else {
        $posts = get_posts(array(
            'post_type' => 'stores',
            'numberposts' => 1,
            'meta_query' => array(array('key' => 'wpcf-store-name', 'value' => $store_id))
        ));
    }

    if (count($posts)) {
        $send_to_email = types_render_field('store-contact-us-send-to-email', array('post_id' => $posts[0]->ID, 'raw' => true));
    }

    if(!$send_to_email) $send_to_email = null;

    return $send_to_email;
}

function wpcf7_before_send($wpcf7) {
    // 5 = contact form id
    if ($wpcf7->id == 5) {
        $submission = WPCF7_Submission::get_instance();
        if($submission) {
            $posted_data = $submission->get_posted_data();
            $store = $posted_data['dropdown-store'];
            $mail = $wpcf7->prop('mail');
            $mail['recipient'] = get_contact_us_email($store);
            $wpcf7->set_properties( array( 'mail' => $mail ) );
        }
    }

    return $wpcf7;
}
//add_action("wpcf7_before_send_mail", "wpcf7_before_send");
add_filter( 'wpcf7_form_elements', 'do_shortcode' );

function get_contact_us_email($store) {
    global $wpdb;
    $contact_us_table = $wpdb->prefix . 'contact_us'; //Good practice
    $getContacts = $wpdb->get_var( "SELECT EmailAddress FROM $contact_us_table WHERE StoreNumber = '" . $store . "'");
    if (!$getContacts) $getContacts = $wpdb->get_var( "SELECT EmailAddress FROM $contact_us_table WHERE StoreNumber = '0'");
    return $getContacts;
}

// THIS GIVES US SOME OPTIONS FOR STYLING THE ADMIN AREA
function fp_wp_simply_good_iga_add_admin_styles() {
    //enqueue_and_version_style("admin-css", "/resources/stylesheets/css/admin_screen.css");
}
add_action('admin_head', 'fp_wp_simply_good_iga_add_admin_styles');

add_filter('get_comments_number', 'fp_wp_simply_good_iga_comments_number');
function fp_wp_simply_good_iga_comments_number($count)
{
    if (!is_admin()) {
        global $id;
        $comments_by_type =& separate_comments(get_comments('status=approve&post_id=' . $id));
        return count($comments_by_type['comment']);
    } else {
        return $count;
    }
}

function register_menus() {
    register_nav_menus(
        array(
        )
    );
}
add_action( 'init', 'register_menus' );

function numeric_posts_nav() {

    if( is_singular() )
        return;

    global $wp_query;

    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;

    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );

    /** Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;

    /** Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }

    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }

    echo '<div class="navigation-pages"><ul>' . "\n";

    /** Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '<li>%s</li>' . "\n", get_previous_posts_link('<span class="fp-icon-caret-left"></span>') );

    /** Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';

        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

        if ( ! in_array( 2, $links ) )
            echo '<li>…</li>';
    }

    /** Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }

    /** Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '<li>…</li>' . "\n";

        $class = $paged == $max ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }

    /** Next Post Link */
    if ( get_next_posts_link() )
        printf( '<li>%s</li>' . "\n", get_next_posts_link('<span class="fp-icon-caret-right"></span>') );

    echo '</ul></div><div class="navigation-pagecount"><strong>' . $paged . '</strong> of ' . $max . ' Pages</div>' . "\n";
}

/* Prevent timyMCE from stripping span tags when switching from visual to text tabs */
function override_mce_options($initArray) {
    $opts = '*[*]';
    $initArray['valid_elements'] = $opts;
    $initArray['extended_valid_elements'] = $opts;
    return $initArray;
}
add_filter('tiny_mce_before_init', 'override_mce_options');

// Replaces the excerpt "more" text by a link
function new_excerpt_more($more) {
    global $post;
    return ' <a class="moretag" href="'. get_permalink($post->ID) . '">Read more</a>';
}

function get_id_by_slug($page_slug) {
    $page = get_page_by_path($page_slug);
    if ($page) {
        return $page->ID;
    } else {
        return null;
    }
}

/**
 * Displays breadcrumb, dependant on parent page
 *
 * @param bool Whether to return or echo the trail. (optional)
 * @param bool Whether to allow hyperlinks in the trail or not. (optional)
 * @param bool Whether to reverse the output or not. (optional)
 */
function display_bc($parentVal) {
    global $breadcrumb_navxt;

    if ($breadcrumb_navxt !== null && $parentVal != 0 && $_GET['intent'] != 'in_app') {
        return $breadcrumb_navxt->display_list(false, true, false);
    }
}

// Customize WordPress Visual Editor
add_editor_style();

function fp_starts_with($haystack, $needle) {
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

function fp_ends_with($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}

function fp_trim_left($str, $prefix){
    if (fp_starts_with($str, $prefix)) {
        $str = substr($str, strlen($prefix));
    }
    return $str;
}

function fp_trim_right($str, $suffix){
    if (fp_ends_with($str, $suffix)) {
        $str = substr($str, 0, strlen($str) - strlen($suffix));
    }
    return $str;
}

function fp_get_theme_version() {
    return wp_get_theme()->get('Version');
}

function fp_markdown_to_html($value) {
    $value = preg_replace_callback('/(^|[^\\n])\\n(?!\\n)/', function($match) {
        $match = $match[0];
        if (!trim($match)) return $match;
        $match = rtrim($match);
        return substr($match, 0, strlen($match)) . "  \n";
    }, $value);

    if(!($value && function_exists('wpmarkdown_markdown_to_html'))) return $value;
    return wpmarkdown_markdown_to_html($value);
}

global $fp_selected_store;
$fp_selected_store = array('id' => '', 'group_id' => get_store_group());

function get_store_group_meta($post_id) {
    $meta = get_post_meta($post_id, 'wpcf-store-group', true);
    $store_groups = array();
    if($meta != null) {
        foreach ($meta as $item) {
            if(count($item)) array_push($store_groups, $item[0]);
        }
    }

    return $store_groups;
}

function get_store_group($store_id = '') {
    // get store group based on selected store id
    $group_id = '';

    if($store_id) {
        $posts = get_posts(array(
            'post_type' => 'stores',
            'numberposts' => 1,
            'meta_query' => array(array('key' => 'wpcf-store-id', 'value' => $store_id))
        ));

        if (count($posts)) {
            $group_id =  implode(',', get_store_group_meta($posts[0]->ID));
//            echo '<pre>' . print_r(types_render_field('store-group', array('post_id' => $posts[0]->ID, 'raw' => true)))  . '</pre>';
//            echo '<pre>' . $group_id . '</pre>';
        }

        if($group_id) $group_id .= ',';
        $group_id .= '2000';
    }
    else $group_id = '1000';
//    echo '<pre>' . $group_id . '</pre>';
    return $group_id;
}

function get_post_by_store_group($store_id, $post_type) {
    return @get_posts_by_store_group($store_id, $post_type, 1)[0];
}

//returns posts sorted asc by group id
function get_posts_by_store_group($store_id, $post_type, $limit = -1) {
    $value = [];

    if(empty($post_type)) return $value;

    $storeGroupIds = explode(',', get_store_group($store_id));
    $hashedStoreGroupIds = [];
    foreach ($storeGroupIds as $groupId) {
        $hashedStoreGroupIds[$groupId] = 1;
    }

//    echo '<pre>' . print_r(get_store_group($store_id)) . '</pre>';
//    echo '<pre>' . print_r($storeGroupIds) . '</pre>';

    $args = array(
        'post_type' => $post_type,
        'numberposts' => -1,
        'meta_query' => array(array('key' => 'wpcf-store-group'))
    );

    if(isset($GLOBALS['is_local'])) {
        $args['post_status'] = array('draft', 'publish');
    }

    $posts = get_posts($args);

//    echo '<pre>' . print_r($store_id) . '</pre>';

    $sortedPosts = [];
    foreach ($posts as $post) {
//        echo '<pre>' . implode(',', get_post_meta($post->ID, 'wpcf-store-group', true)) . '</pre>';
//        echo '<pre>' . print_r(get_store_group_meta($post->ID)) . '</pre>';
        $postGroupIds = get_store_group_meta($post->ID);
        sort($postGroupIds);
        $sortedPost = null;

        foreach ($postGroupIds as $groupId) {
            if ($hashedStoreGroupIds[$groupId]) {
                $sortedPost = array(
                    group_id => $groupId,
                    post => $post
                );
                break;
            }
        }

        if($sortedPost) {
            array_push($sortedPosts, $sortedPost);
//            echo '<pre>' . $sortedPost['group_id'] . ', ' . $sortedPost['post']->ID . '</pre>';
        }
    }

    usort($sortedPosts, function ($a, $b) {
        $a_group_id = $a['group_id'];
        $b_group_id = $b['group_id'];

        if ($a_group_id == $b_group_id) return 0;
        return ($a_group_id < $b_group_id) ? -1 : 1;
    });

    foreach ($sortedPosts as $sortedPost) {
        array_push($value, $sortedPost['post']);

        if($limit > 0 && $limit == count($value)) {
            break;
        }
    }

    return $value;
}

function get_stores() {
    $value = [];

    $args = array(
        'post_type' => 'stores',
        'numberposts' => -1,
        'meta_query' => array(array('key' => 'wpcf-store-group'))
    );

    if(isset($GLOBALS['is_local'])) {
        $args['post_status'] = array('draft', 'publish');
    }

    $posts = get_posts($args);

    foreach ($posts as $post) {
        $group_id = get_store_group_meta($post->ID);
        $store = array(
            ID => $post->ID,
            post_title => $post->post_title
        );
        if(count($group_id)) $store['group_id'] = implode(',', $group_id);

        array_push($value, $store);
    }

    return $value;
}

//=================================================================
/**
 * Used by hook: 'customize_preview_init'
 * 
 * @see add_action('customize_preview_init',$func)
 */
function mytheme_customizer_live_preview()
{
    wp_enqueue_script( 
          'mytheme-themecustomizer',            //Give the script an ID
          get_template_directory_uri().'customizer-iga.js',//Point to file
          array( 'jquery','customize-preview' ),    //Define dependencies
          '',                       //Define a version (optional) 
          true                      //Put script in footer?
    );
}
add_action( 'customize_preview_init', 'mytheme_customizer_live_preview' );


// moved to actions.php
//=================================================================
// function enqueue_mobile_off_canvas_nav() {
//     wp_enqueue_script( 
// 		'off-canvas-menu', 
// 		get_template_directory_uri().'/resources/vendor/off-canvas/hc-offcanvas-nav.js', 
// 		array( 'jquery','customize-preview' ),    //Define dependencies
//           '',                       //Define a version (optional) 
//           false 
// 	);
// }
// add_action( 'wp_enqueue_scripts', 'enqueue_mobile_off_canvas_nav' );

//=================================================================
function mytheme_add_editor_styles() {
    add_editor_style( 'style.css' );
}
add_action( 'admin_init', 'mytheme_add_editor_styles' );

include('customizer.php');  //Load In the Customizer PHP Doc

if (is_admin()) {
    include_once(ABSPATH.'wp-admin/includes/plugin.php');
    if (!is_plugin_active('types/wpcf.php') && is_plugin_active('soliloquy/soliloquy.php')) return;

    // Add Additional Meta Boxes to Soliloquy Slides
    add_action('soliloquy_metabox_scripts', 'fp_soliloquy_custom_fields_scripts');
    add_action('print_media_templates', 'fp_soliloquy_custom_fields_meta_settings', 10, 3);
    add_filter('soliloquy_ajax_save_meta', 'fp_soliloquy_custom_fields_save_metaboxes', 10, 4);

    function fp_soliloquy_custom_fields_scripts() {
        enqueue_and_version_script('soliloquy-custom-fields-media-edit', '/resources/scripts/soliloquy-custom-fields-media-edit.js', true);
    }

    function fp_soliloquy_custom_fields_meta_settings() {
        $storeGroup = wpcf_admin_fields_get_field('store-group');
        if ($storeGroup != null && $storeGroup['data'] != null) {
            $title = $storeGroup['name'];
            $options = $storeGroup['data']['options'];
            //                echo "<div>" . print_r($storeGroup, true) . "</div>";
            //                echo "<div>" . print_r($options, true) . "</div>";

            //            echo "<div>types_render_field: " . types_render_field("store-group", array(post_id=>$post_id)) . "</div>";
            //            echo "<div>types_render_termmeta: " . types_render_termmeta("store-group", array(post_id=>$post_id)) . "</div>";
            //            echo "<div>" . print_r(types_render_group(442)) . "</div>";
            ?>
            <script type="text/html" id="tmpl-soliloquy-meta-editor-custom-fields">
                <div class="setting">
                    <span class="name"><?php esc_html_e($title, 'soliloquy-custom-fields'); ?></span>
                    <?php
                    foreach ($options as $option) {
                        $key = "custom_fields_meta_store_group_" . $option['set_value'];
                        ?>
                        <label>
                            <input type="checkbox" name="<?= $key; ?>"
                                   data-soliloquy-meta="<?= $key; ?>"
                                   value="<?= $option['set_value']; ?>"
                            <# if ( data['<?= $key; ?>'] == '1' ) { #> checked <# } #>/>
                                <span class="check-label"
                                      style="text-align:left;"><?= $option['title']; ?></span>
                                    <div style="clear:both"></div>
                        </label>
                    <?php } ?>
                </div>
            </script>
            <?php
        }
    }

    function fp_soliloquy_custom_fields_save_metaboxes($settings, $meta, $attach_id, $post_id) {
        $storeGroup = wpcf_admin_fields_get_field('store-group');
        if ($storeGroup != null && $storeGroup['data'] != null) {
            $options = $storeGroup['data']['options'];
            foreach ($options as $option) {
                $key = "custom_fields_meta_store_group_" . $option['set_value'];
                $settings['slider'][$attach_id][$key] = isset($meta[$key]) && $meta[$key] ? 1 : 0;
            }
        }
        return $settings;
    }
}

add_filter('soliloquy_pre_data', 'fp_soliloquy_pre_data', 10, 2);
function fp_soliloquy_pre_data($data, $slider_id) {
    global $wp;
    $shortcode = Soliloquy_Shortcode::get_instance();
    //home-page XHR requests do not get the Solioquy pre data filter
    if (!$shortcode->is_ajax_request() || fp_starts_with($wp->request, 'home-page/')) return $data;

    global $fp_selected_store;

    $storeGroupIds = explode(',', $fp_selected_store['group_id']);

    foreach($data['slider'] as $key => $slide) {
        foreach ($storeGroupIds as $groupId) {
            $isInGroup = ($slide['custom_fields_meta_store_group_' . $groupId] == 1);
            if ($isInGroup) {
                break;
            }
        }

        if(!$isInGroup) {
            unset($data['slider'][$key]);
        }
    }
    return $data;
}


add_filter('soliloquy_output', 'fp_soliloquy_slider_init_ajax', 1000, 2);
function fp_soliloquy_slider_init_ajax($slider, $data) {
    $shortcode = Soliloquy_Shortcode::get_instance();
    if(!$shortcode->is_ajax_request()) return $slider;
    $js = $shortcode->slider_init_single($data, true);
    $slider .= '<script>' . $js . '</script>';

    return $slider;
}

function typesFilePath() {
    $typesFilePath = WP_PLUGIN_DIR . "/types/embedded/frontend.php";
    if (!is_file($typesFilePath)) {
        $typesFilePath = WP_PLUGIN_DIR . "/types/library/toolset/types/embedded/frontend.php";
        if (!is_file($typesFilePath)) return;
    }
}
if(is_admin()) typesFilePath();

//force posts to be distributed using status published
add_filter('dt_allow_as_draft_distribute', '__return_false');

//enable pushing change of post_status
add_filter('dt_distribute_post_status', '__return_true');

