<?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');

    add_theme_support( 'post-thumbnails' );

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

    add_editor_style([
        '/assets/css/styles-main-page.min.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_style('bootstrap', '//cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css', null, null);
    wp_enqueue_script('bootstrap', '//cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js', null, null, true);

    wp_enqueue_style('splide', '//cdn.jsdelivr.net/npm/@splidejs/splide@4.1.3/dist/css/splide.min.css', null, null);
    wp_enqueue_script('splide-auto-scroll', 'https://cdn.jsdelivr.net/npm/@splidejs/splide-extension-auto-scroll@0.5.3/dist/js/splide-extension-auto-scroll.min.js', null, null, true);
    wp_enqueue_script('splide', '//cdn.jsdelivr.net/npm/@splidejs/splide@4.1.3/dist/js/splide.min.js', null, null, true);

    // wp_enqueue_script('lawcarta-js', get_theme_file_uri('/assets/js/faqSearch.js'), ['custom-jquery'], null, true);
    // wp_enqueue_style('lawcarta-libs', get_theme_file_uri('/assets/css/libs.min.css'), [], '100');

    wp_enqueue_style('lawcarta-style-colors', get_theme_file_uri('/assets/css/colors.css'), null, '1');
    wp_enqueue_style('lawcarta-style-index', get_theme_file_uri('/assets/css/styles-main-page.min.css'), null, '142');

    // if(is_front_page()){
    //     wp_enqueue_style('lawcarta-style-index', get_theme_file_uri('/assets/css/main-page.min.css'),['lawcarta-libs'], '101');
    // }else{
    //     wp_enqueue_style('lawcarta-style-index', get_theme_file_uri('/assets/css/main-page.min.css'),['lawcarta-libs'], '101');
    //     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;
});

function get_canonocal_url() {
    $uri = explode('?', $_SERVER['REQUEST_URI']);
    if (isset($uri[1])) {
        parse_str($uri[1], $params);
        if (isset($params['lctc'])) {
            unset($params['lctc']);
        }
        $uri[0] .= '?' . http_build_query($params);
    }
    return home_url( $uri[0] );
}

/**
 * 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 (is_countable($taxonomies) && 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;
    }
    $parts = explode(' ', trim($_POST['search_text']));

    $likeConditions = [];
    foreach($parts as $part){

        $likeConditions [] =  $wpdb->posts . '.post_title LIKE \'%' . trim(esc_sql( $part )) . '%\' ';
        $likeConditions [] =  $wpdb->posts . '.post_content LIKE \'%' . trim(esc_sql( $part )) . '%\' ';

    }

    $where .= ' AND (
                      '.implode(' OR ', $likeConditions) .'
                    )';

    return $where;
}

function get_lawcarta_url(){
    $urlParts = parse_url(home_url());
    $scheme = isset($urlParts['scheme']) ? $urlParts['scheme'] . '://' : '';

    $baseTemplate = basename( get_page_template() );

    $host = isset($urlParts['host']) ? $urlParts['host'] : '';
    if (defined('LAWCARTA_SUBDOMAIN')) {
        $hostParts = explode('.', $host);
        if (count($hostParts) === 3) {
            $wp_sub_domain = array_shift($hostParts);
        }
        if (!empty(LAWCARTA_SUBDOMAIN)) {
            array_unshift($hostParts, LAWCARTA_SUBDOMAIN);
        }
        $host = implode('.', $hostParts);
        //Fix for staging env because of it use same domain carta.live for both lawcarta/livecarta

        if (isset($wp_sub_domain)) {
            if(LAWCARTA_ENVIRONMENT_NAME == 'staging' && $wp_sub_domain == 'staging-live'){
                $host = str_replace('staging-law', 'staging-live',$host);
            }
            //Temporary fix for new prod env because of it use same domain carta.live for both lawcarta/livecarta
            if(LAWCARTA_ENVIRONMENT_NAME == 'prod' && $wp_sub_domain == 'prod-live'){
                $host = str_replace('prod-law', 'prod-live',$host);
            }
            //Temporary fix for new prod env because of it use same domain carta.live for both lawcarta/livecarta
            if(LAWCARTA_ENVIRONMENT_NAME == 'prod' && $wp_sub_domain == ''){
                $host = str_replace('app-law', 'app',$host);
            }
        }
    }

    $port = isset($urlParts['port']) ? $urlParts['port'] : '';
    if (defined('LAWCARTA_PORT')) {
        $port = LAWCARTA_PORT;
    }
    if (!empty($port)) {
        $port = ':' . $port;
    }

    return  "$scheme$host$port";
}

function get_lawcarta_ga_config(){

    $res = '';
    if(wp_get_theme() == 'LawCarta'){
        $res =  LAWCARTA_GA_CONFIG;
    }elseif(wp_get_theme() == 'LiveCarta'){
        $res =  LIVECARTA_GA_CONFIG;
    }
    return $res;
}

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

/* Register template redirect action callback */
add_action('template_redirect', 'meks_remove_wp_archives');

/* Remove archives */
function meks_remove_wp_archives(){
    //If we are on category or tag or date or author archive
    if( is_category() || is_tag() || is_date() || is_author() ) {
        global $wp_query;
        $wp_query->set_404(); //set to 404 not found page
    }
}

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if ($item->current){
        $classes[] = 'active ';
    }
    return $classes;
}

function add_custom_class($classes=array(), $menu_item=false) {
    //todo: detect blog post page
    if ( !is_page() && 'blog' == strtolower($menu_item->title) &&
        !in_array( 'active', $classes ) ) {
        $classes[] = 'active';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class', 100, 2);

/**
 * Add Disallow for some file types.
 * Add "Disallow: /wp-login.php/\n".
 * Remove "Allow: /wp-admin/admin-ajax.php\n".
 * Calculate and add a "Sitemap:" link.
 */
add_filter( 'robots_txt', function( $output, $public ) {
    /**
     * If "Search engine visibility" is disabled,
     * strongly tell all robots to go away.
     */
    if ( '0' == $public || LAWCARTA_ENVIRONMENT_NAME != 'prod') {
        $output = "User-agent: *\nDisallow: /\nDisallow: /*\nDisallow: /*?\n";
    } else {
        /**
         * Disallow some file types
         */
        foreach( array( 'jpeg','jpg','gif','png','mp4','webm','woff','woff2','ttf','eot' ) as $ext ) {
            $output .= "Disallow: /*.{$ext}$\n";
        }

        /**
         * Get site path.
         */
        $site_url = parse_url( site_url() );
        $path     = ( ! empty( $site_url['path'] ) ) ? $site_url['path'] : '';

        /**
         * Add new disallow.
         */
        $output .= "Disallow: $path/wp-login.php\n";

        /**
         * Remove line that allows robots to access AJAX interface.
         */
        $robots = preg_replace( '/Allow: [^\0\s]*\/wp-admin\/admin-ajax\.php\n/', '', $output );

        /**
         * If no error occurred, replace $output with modified value.
         */
        if ( ! is_null( robots ) ) {
            $output = $robots;
        }

        /**
         * Remove line Sitemap.
         */
        $robots = preg_replace( '/Sitemap: [^\0\s]*\n/', '', $output );

        /**
         * If no error occurred, replace $output with modified value.
         */
        if ( ! is_null( robots ) ) {
            $output = $robots;
        }

        /**
         * Calculate and add a "Sitemap:" link.
         * Modify as needed.
         */
        $output .= "Sitemap: {$site_url['scheme']}://{$site_url[ 'host' ]}/wp-sitemap.xml\n";
    }

    return $output;

}, 99, 2 );  // Priority 99, Number of Arguments 2.

function mark_redirected_user(){

    if(
        isset($_GET['law'])
        && $_GET['law'] == 1
        && ((isset($_COOKIE['cookie_level']) &&(strpos($_COOKIE['cookie_level'], '2') !== false)) || LC_ALLOW_COOKIE_POPUP == false)
    ){
        $cookieDomain = (LAWCARTA_ENVIRONMENT_NAME == 'local') ? 'livecarta.loc' : 'livecarta.com';
        setcookie('law_'.LAWCARTA_ENVIRONMENT_NAME, 1,0,"/", $cookieDomain);
    }
}
add_action( "template_redirect", "mark_redirected_user" );

function old_post_url_redirect(){
    global $wp;
    $parts = explode('/',$wp->request);
    if(
        $parts
        && count($parts) == 4
        && is_numeric($parts[0])
        && is_numeric($parts[1])
        && is_numeric($parts[2])
    ){
        wp_redirect( home_url( $parts[3] ), 301 );
    }
}
add_action( "template_redirect", "old_post_url_redirect" );

/**
 * Add custom validation for CF7 form fields
 */
function is_business_email($email){
    if(
            preg_match('/@gmail.com/i', $email) ||
            preg_match('/@hotmail.com/i', $email) ||
            preg_match('/@outlook.com/i', $email) ||
            preg_match('/@yahoo.com/i', $email) ||
            preg_match('/@protonmail.com/i', $email) ||
            preg_match('/@icloud.com/i', $email) ||
            preg_match('/@me.com/i', $email) ||
            preg_match('/@aol.com/i', $email) ||
            preg_match('/@mail.com/i', $email) ||
            preg_match('/@tutanota.com/i', $email) ||
            preg_match('/@tuta.com/i', $email) ||
            preg_match('/@live.com/i', $email) ||
            preg_match('/@msn.com/i', $email) ||
            preg_match('/@inbox.com/i', $email)
    ){
        return false; // It's a publicly available email address
    }else{
        return true; // It's probably a company email address
    }
}
function custom_email_company_validation_filter( $result, $tag ) {
    if ( 'company-email' == $tag->name ) {
        $the_value = isset( $_POST['company-email'] ) ? trim( $_POST['company-email'] ) : '';
        if (!is_business_email($the_value)) {
            $result->invalidate($tag, "This form only accepts business emails. Please provide your work address.");
        }
    }
    
    return $result;
}

add_filter( 'wpcf7_validate_email*', 'custom_email_company_validation_filter', 20, 2 );