<?php
require 'inc/menu-item-custom-fields.php';

/**
 * Setup WordPress
 */
add_action('after_setup_theme', function () {
    /*
	 * Let WordPress manage the document title.
	 * By adding theme support, we declare that this theme does not use a
	 * hard-coded <title> tag in the document head, and expect WordPress to
	 * provide it for us.
	 */
    add_theme_support('title-tag');

    register_nav_menus([
        'top' => __('Top Menu', 'lawcarta'),
        'bottom' => __('Bottom Menu', 'lawcarta'),
        'social' => __( 'Social Links Menu', 'lawcarta' ),
    ]);

    add_editor_style([
        lawcarta_fonts_url(),
        'assets/css/style.min.css',
        'assets/css/newcss.min.css',
        'assets/css/custom.css',
        'assets/css/livecarta.css'
    ]);
});

/**
 * Setup title
 */
add_filter('document_title_separator', function () {
    return '|';
});

add_filter('document_title_parts', function ($title) {
    unset($title['tagline']);
    return $title;
}, 10, 1);

/**
 * Enqueue scripts and styles.
 */
function lawcarta_fonts_url() {
    $font_families = [
        'Open Sans:300,400,600,700',
        'PT Serif:400,700',
    ];
    $query_args = [
        'family' => urlencode(implode('|', $font_families)),
    ];
    $fonts_url = add_query_arg($query_args, 'https://fonts.googleapis.com/css');
    return esc_url_raw($fonts_url);
}

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('lawcarta-fonts', lawcarta_fonts_url(), array(), null);

    wp_enqueue_script('custom-jquery', '//code.jquery.com/jquery-2.2.4.min.js', [], null, true);

    wp_enqueue_style('bootstrap', '//stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', ['lawcarta-fonts'], null);
    wp_enqueue_script('bootstrap', '//stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', ['custom-jquery'], null, true);

    wp_enqueue_style('jquery-ui', '//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css', ['bootstrap'], null);
    wp_enqueue_script('jquery-ui', '//code.jquery.com/ui/1.12.1/jquery-ui.min.js', ['custom-jquery'], null, true);
    wp_enqueue_script('lawcarta-js', get_theme_file_uri('/assets/js/faqSearch.js'), ['custom-jquery'], null, true);

    wp_enqueue_style('lawcarta-external-style', get_theme_file_uri('/assets/css/style.min.css'), ['jquery-ui']);
    wp_enqueue_style('lawcarta-newcss', get_theme_file_uri('/assets/css/newcss.min.css'), ['lawcarta-external-style']);
    wp_enqueue_style('lawcarta-custom', get_theme_file_uri('/assets/css/custom.css'), ['lawcarta-newcss']);
    wp_enqueue_style('lawcarta-style', get_stylesheet_uri(), ['lawcarta-custom']);
});

/**
 * Filter Menu Item Class
 */
add_filter('wp_setup_nav_menu_item', function ($menu_item)
{
    $meta = LawCarta_Menu_Item_Custom_Fields::getMeta($menu_item);
    $menu_item->meta = $meta;

    $menu_item->meta['type'] = $menu_item->object;
    if ($menu_item->object == 'page') {
        $menu_item->meta['slug'] = get_post_field( 'post_name', $menu_item->object_id );
    } else if ($menu_item->object == 'media_category') {
        $menu_item->meta['slug'] = get_term_field( 'slug', $menu_item->object_id );
    }

    return $menu_item;
});

/**
 * Setup Admin Portal
 */
function lawcarta_company_field_cb() {
    $setting = get_option('lawcarta_company');
    $setting = isset( $setting ) ? esc_attr( $setting ) : '';
    echo '<input type="text" name="lawcarta_company" value="' . $setting . '">';
}

add_action('admin_init', function () {
    register_setting('general', 'lawcarta_company', [
        'type' => 'string',
    ]);

    add_settings_field(
        'lawcarta_company_field',
        __('Company Name', 'lawcarta'),
        'lawcarta_company_field_cb',
        'general'
    );
});

/**
 * Setup TinyMCE
 */
add_filter('tiny_mce_before_init', function ($settings) {
    $opts = '*[*]';
    $settings['valid_elements'] = $opts;
    $settings['extended_valid_elements'] = $opts;
    $settings['valid_children']="+a[div|p|ul|ol|li|h1|h2|h3|h4|h5|h5|h6]";
    return $settings;
});

function enableSearchQuery()
{
    return !empty($_POST['search_text']);
}

function getFaqPosts($args) {
    if (enableSearchQuery()) {
        // WP magic
        add_filter( 'posts_where', 'my_filter_post_where' );
    }
    $posts = get_posts($args);
    if (enableSearchQuery()) {
        remove_filter( 'posts_where', 'my_filter_post_where' );
    }
    return $posts;
}

function getFaaTaxonomyIds()
{
    if (!enableSearchQuery())
    {
        return false;
    }

    $posts = getFaqPosts([
        'post_type' => 'fac_category_answer',
        'suppress_filters' => false,
        'numberposts' => -1,
    ]);
    if (count($posts) == 0) {
        return [];
    }
    $tIds = [];
    foreach ($posts as $post) {
        $taxonomies = get_the_terms($post, 'fac_category_type');
        if (count($taxonomies) > 0) {
            foreach ($taxonomies as $taxonomy) {
                if (!in_array($taxonomy->term_id, $tIds)) {
                    $tIds[] = $taxonomy->term_id;
                }
            }
        }
    }
    return $tIds;
}

function my_filter_post_where( $where) {
    global $wpdb;
    if (!enableSearchQuery()) {
        return $where;
    }
    $where .= ' AND (
                      ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $_POST['search_text'] ) . '%\' OR
                      ' . $wpdb->posts . '.post_content LIKE \'%' . esc_sql( $_POST['search_text'] ) . '%\' 
                    )';

    return $where;
}
