<?php

if (!defined('ABSPATH')) {
    exit();
}
add_action('wp_ajax_milo_admin_custom_sidebars', 'milo_admin_custom_sidebars');
add_action('wp_ajax_nopriv_milo_admin_custom_sidebars', 'milo_admin_custom_sidebars');

function milo_admin_custom_sidebars() {

    if (!is_admin()){
        die(esc_html__( 'Access denied!', 'dakota-theme' ));
    }
    
    if( ! wp_verify_nonce( $_REQUEST['milo_widget_form_nonce'], 'milo_widget_form_ajax' ) ){
         exit();
    }

    $title = $_REQUEST["title"];
    $description = $_REQUEST["description"];

    $option_name = 'milo-sidebars-custom';
    if (trim($title) != '' && trim($description) != '') {
        if (get_option($option_name) == false) {
            $sidebars_array = array();
            $current_count = 0;
            $check = 0;
        } else {
            $check = 0;
            $sidebars_array = get_option($option_name);
            $current_count = count($sidebars_array);

            for ($i = 0; $i < $current_count; $i = $i + 2) {

                if (sanitize_title_with_dashes($sidebars_array[$i]) == sanitize_title_with_dashes($title)) {
                    $check = 1;
                }
            }
        }

        if ($check == 0) {
            $sidebars_array[$current_count] = esc_html($title);
            $current_count++;
            $sidebars_array[$current_count] = esc_html($description);

            update_option($option_name, $sidebars_array);
            $result = 'created';
        } else {
            $result = esc_html__('A sidebar with this name already exists', 'dakota-theme');
        }
    } else if (trim($title) == '') {
        $result = esc_html__('Please specify a title', 'dakota-theme');
    } else {
        $result = esc_html__('Please specify a description', 'dakota-theme');
    }
    // Verifies the HTTP request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // Encodes and provides the response output
        echo json_encode($result);
    } else {
        header("Location: " . $_SERVER["HTTP_REFERER"]);
    }

    die();
}

add_action('wp_ajax_milo_remove_sidebar', 'milo_remove_sidebar');
add_action('wp_ajax_nopriv_milo_remove_sidebar', 'milo_remove_sidebar');

function milo_remove_sidebar() {

    if (!is_admin()){
        die(esc_html__( 'Access denied!', 'dakota-theme' ));
    }
    
    if( ! wp_verify_nonce( $_REQUEST['milo_widget_form_nonce'], 'milo_widget_form_ajax' ) ){
         exit();
    }
    
    $sidebar_id = $_REQUEST["sidebar_id"];
    $parts = explode('-', $sidebar_id);
    $last = count($parts) - 1;
    unset($parts[$last]);
    $sidebar_check = implode('-', $parts);
    $removed_sidebar = 0;

    $option_name = 'milo-sidebars-custom';
    if (get_option($option_name) !== false) {
        $sidebars_array = get_option($option_name);
        $count = count($sidebars_array);

        for ($i = 0; $i < $count; $i = $i + 2) {

            if (sanitize_title_with_dashes($sidebars_array[$i]) == sanitize_text_field($sidebar_check)) {
                unset($sidebars_array[$i]);
                $removed_sidebar = $i + 1;
                unset($sidebars_array[$removed_sidebar]);
            }
        }

        $sidebars_array = array_values($sidebars_array);
        update_option('milo-sidebars-custom', $sidebars_array);
    }

    // Verifies the HTTP request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // Encodes and provides the response output
        if ($removed_sidebar != 0) {
            $result['sidebar_id'] = $sidebar_id;
            echo json_encode($result);
        }
    } else {
        header("Location: " . $_SERVER["HTTP_REFERER"]);
    }

    die();
}

add_action('wp_ajax_milo_portfolio_gallery', 'milo_portfolio_gallery');
add_action('wp_ajax_nopriv_milo_portfolio_gallery', 'milo_portfolio_gallery');

// Provides the response results for load more classic portfolio with pagination
function milo_portfolio_gallery() {

    /*
     * Verifies if the ajax call was made fom the portfolio load more button, 
     * based on the WordPress generated nonce of the request
     */
    if (!wp_verify_nonce($_REQUEST['nonce'], 'milo_custom_posts_isotope_nonce')) {
        exit();
    }
    
   if( ! wp_verify_nonce( $_REQUEST['milo_ajax_call_nonce'], 'milo_portfolio_ajax' ) ){
         exit();
    }

    $type = $_REQUEST['custom_post_type'];
    $count_page = $_REQUEST['count_page'];
    $count_total = $_REQUEST['count_total'];
    $count_increment = $_REQUEST['count_increment'];
    $milo_style = $_REQUEST['style'];
    $milo_visit = $_REQUEST['visit'];
    $img_size = $_REQUEST['img_size'];
    $milo_selection = $_REQUEST['selection'];

    // Determines the elements for the current page
    if ($count_page == '0') {
        $posts_start = $count_total - $count_increment;
    } else {
        $posts_start = $count_page - 1;
        $posts_start = $posts_start * $count_increment;
    }

    if ($milo_selection != 'all') {
        $args = array(
            'post_type' => $type,
            'post_status' => 'publish',
            'tax_query' => array(
                array(
                    'taxonomy' => 'portfolio_categories',
                    'field' => 'id',
                    'terms' => array($milo_selection)
                )
            ),
            'offset' => $posts_start,
            'posts_per_page' => $count_increment,
            'ignore_sticky_posts' => 1);
    } else {
        $args = array(
            'post_type' => $type,
            'post_status' => 'publish',
            'offset' => $posts_start,
            'posts_per_page' => $count_increment,
            'ignore_sticky_posts' => 1);
    }

    $loop = new WP_Query($args);

    if ($count_total >= $loop->found_posts) {
        $result['load_end'] = 1;
    }

    $output = '';

    while ($loop->have_posts()) {

        $terms_class = 'isotope-item';
        $loop->the_post();
        $post_id = get_the_ID();

        $post_categories = get_the_terms($post_id, 'portfolio_categories');

        if (has_post_thumbnail($post_id)) {
            $thumbnail_id = get_post_thumbnail_id();

            $image_data = wp_get_attachment_image_src($thumbnail_id, $img_size);

            $image_url = esc_url($image_data[0]);

            $image_data_full = wp_get_attachment_image_src($thumbnail_id, 'full');

            $image_url_full = esc_url($image_data_full[0]);
        } else {
            $image_url = $image_url_full = get_template_directory_uri() . '/layouts/images/default/testimonial_none.png';
        }

        $post_title = esc_html(get_the_title($post_id));

        $post_link = esc_url(get_post_permalink($post_id));

        $terms_list = '';
        if (!empty($post_categories)) {
            foreach ($post_categories as $category) {
                $terms_class.=" categ-" . esc_attr($category->slug);
                $term_link = get_term_link($category->slug, 'portfolio_categories');
                $terms_list.="<a href='{$term_link}'>{$category->name}</a> ";
            }
        }

        if ($milo_style == '5') {

            if (!empty($post_categories)) {
                foreach ($post_categories as $category) {
                    $terms_class.=" categ-" . esc_attr($category->slug);
                    $term_link = get_term_link($category->slug, 'portfolio_categories');
                    $terms_list.="<a href='{$term_link}'>{$category->name}</a> ";
                }
            }

            $milo_visit = esc_html($milo_visit);
            $post_excerpt = apply_filters('the_content', get_the_excerpt());

            $output.="<div class='{$terms_class}'><div class='portfolio-item portfolio-classic'>
                    <div class='portfolio-item-thumbnail'><img src='{$image_url}' alt=''><div class='portfolio-item-hover'>
                    <a class='fancybox zoom-action' data-fancybox-group='portfolio' href='{$image_url_full}'><i class='mt-icon-expand2'></i></a>
                    </div></div><div class='portfolio-item-details'><h6><a href='{$post_link}'>{$post_title}</a></h6><p>{$terms_list}<p><p>{$post_excerpt}</p>
                    <a class='btn btn-default' href='{$post_link}'>{$milo_visit}</a></div></div></div>";
        } else {
            if (!empty($post_categories)) {
                foreach ($post_categories as $category) {
                    $terms_class.=" categ-" . esc_attr($category->slug);
                }
            }

            $output.= "<div class='{$terms_class}'><div class='portfolio-item'>
		<div class='portfolio-item-thumbnail'><img src='{$image_url}' alt=''><div class='portfolio-item-hover'>";
            if ($milo_style == '1' || $milo_style == '3') {
                $output.= "<a class='fancybox zoom-action' data-fancybox-group='portfolio' href='{$image_url_full}'><i class='mt-icon-expand2'></i></a>
                    </div></div></div></div>";
            } else if ($milo_style == '2' || $milo_style == '4') {
                $output.= "<a class='fancybox zoom-action' data-fancybox-group='portfolio' href='{$image_url_full}'><i class='mt-icon-expand2'></i></a>
                    </div></div><div class='portfolio-item-details'><h6><a href='{$post_link}'>{$post_title}</a></h6></div></div></div>";
            }
        }
    }

    wp_reset_postdata();

    $result['list_elements'] = $output;

    // Verifies the HTTP request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // Encodes and provides the response output
        echo json_encode($result);
    } else {
        header("Location: " . $_SERVER["HTTP_REFERER"]);
    }

    die();
}
