<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) exit;

class Rdg_Blocks_Posts_Ajax extends Rdg_Blocks_Base
{
    protected $block_name = BLOCK_RDG_POSTS_AJAX;
    private $block_folder_name = 'rdg-posts-ajax';
    protected $block_title = 'RDG Posts Ajax';
    private $block_description = 'This block is a group of selectors to offer at user the option for selecting between sports and league when search for a post';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'post', 'ajax'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_config = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'RDG Posts Ajax';
    protected $config_menu_title = 'Posts Ajax';

    public function init() {
        $this->register_block();
        add_action('acf/init', [$this, 'register_config_menu'], 20);
        add_action('acf/init', [$this, 'register_fields'], 20);
    }

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            acf_register_block_type([
                'name' => $this->block_name,
                'title' => __($this->block_title),
                'description' => __($this->block_description),
                'category' => $this->block_category,
                'icon' => $this->block_icon,
                'keywords' => $this->block_keywords,
                'mode' => $this->block_mode,
                'render_template' => RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php",
                'enqueue_style' => $rdg_helpers->webpack('rdg_posts_ajax.css'),
                'enqueue_assets' => function(){
                    wp_register_script('rdg_posts_ajax_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-posts-ajax/assets/js/rdg-posts-ajax.js', array('jquery'), '1', true);
                    wp_enqueue_script('rdg_posts_ajax_script');
                    wp_localize_script('rdg_posts_ajax_script','rdg_posts_ajax_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                },
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-posts-ajax-template-preview.jpg",
                        ),
                    ),
                ),
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

    public function register_fields() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_posts_ajax_block_sdf4334r',
                'title' => 'Block_rdg_posts_ajax',
                'fields' => array(
                    array(
                        'key' => 'field_6452da16325a5',
                        'label' => 'Sport Type',
                        'name' => 'sport_type',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'default' => 'Default',
                            'redirect' => 'Redirect',
                        ),
                        'default_value' => 'default',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_6452d88db27f4',
                        'label' => 'Default Sport',
                        'name' => 'sport',
                        'aria-label' => '',
                        'type' => 'taxonomy',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'taxonomy' => 'category',
                        'add_term' => 1,
                        'save_terms' => 0,
                        'load_terms' => 0,
                        'return_format' => 'id',
                        'field_type' => 'select',
                        'allow_null' => 1,
                        'multiple' => 0,
                    ),
                    array(
                        'key' => 'field_6452d900b27f5',
                        'label' => 'Default League',
                        'name' => 'league',
                        'aria-label' => '',
                        'type' => 'taxonomy',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'taxonomy' => 'category',
                        'add_term' => 1,
                        'save_terms' => 0,
                        'load_terms' => 0,
                        'return_format' => 'id',
                        'field_type' => 'select',
                        'allow_null' => 1,
                        'multiple' => 0,
                    ),
                    array(
                        'key' => 'field_6452d918b27f6',
                        'label' => 'Quantity',
                        'name' => 'quantity',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => 1,
                        'max' => 12,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-posts-ajax',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function register_config_menu() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'configuration_posts_ajax_block_9832br3s2b7r3s289hn3s2',
                'title' => 'Block configuration',
                'fields' => array(
                    array(
                        'key' => 'field_6452dd654953b',
                        'label' => 'Sports Categories',
                        'name' => 'posts_ajax_sports_categories',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'pagination' => 0,
                        'min' => 0,
                        'max' => 0,
                        'collapsed' => '',
                        'button_label' => 'Add Row',
                        'rows_per_page' => 20,
                        'sub_fields' => array(
                            array(
                                'key' => 'field_6452dd8f4953c',
                                'label' => 'Sport Category',
                                'name' => 'category',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '30',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => $this->get_posts_ajax_sports(),
                                'default_value' => false,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 1,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_6452dd654953b',
                            ),
                            array(
                                'key' => 'field_6452dde24953d',
                                'label' => 'Redirect Type',
                                'name' => 'type',
                                'aria-label' => '',
                                'type' => 'radio',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '30',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => array(
                                    'post' => 'Posts',
                                    'page' => 'Pages',
                                    'link' => 'External',
                                ),
                                'default_value' => 'post',
                                'return_format' => 'value',
                                'allow_null' => 0,
                                'other_choice' => 0,
                                'layout' => 'horizontal',
                                'save_other_choice' => 0,
                                'parent_repeater' => 'field_6452dd654953b',
                            ),
                            array(
                                'key' => 'field_6452e098f6993',
                                'label' => 'Posts',
                                'name' => 'posts',
                                'aria-label' => '',
                                'type' => 'post_object',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_6452dde24953d',
                                            'operator' => '==',
                                            'value' => 'post',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '40',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'post_type' => array(
                                    0 => 'post',
                                ),
                                'taxonomy' => '',
                                'return_format' => 'object',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 1,
                                'parent_repeater' => 'field_6452dd654953b',
                            ),
                            array(
                                'key' => 'field_6452e0b7f6994',
                                'label' => 'Pages',
                                'name' => 'pages',
                                'aria-label' => '',
                                'type' => 'post_object',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_6452dde24953d',
                                            'operator' => '==',
                                            'value' => 'page',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '40',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'post_type' => array(
                                    0 => 'page',
                                ),
                                'taxonomy' => '',
                                'return_format' => 'object',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 1,
                                'parent_repeater' => 'field_6452dd654953b',
                            ),
                            array(
                                'key' => 'field_6452e0c7f6995',
                                'label' => 'URL',
                                'name' => 'url',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_6452dde24953d',
                                            'operator' => '==',
                                            'value' => 'link',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '40',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'parent_repeater' => 'field_6452dd654953b',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-posts-ajax',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function get_posts_ajax_sports() {
        $categories = [];
        $sports = posts_ajax_get_sports();

        foreach ($sports as $sport) {
            $categories[$sport->term_id] = $sport->name;
        }

        return $categories;
    }

    public function get_redirect_url($sport_id, $routers = []) {
        if (is_array($routers) && count($routers) == 0) {
            return $sport_id;
        }

        if (isset($routers[$sport_id])) {
            if (!empty($routers[$sport_id])) {
                return $routers[$sport_id];
            }

            return $sport_id;
        }

        return $sport_id;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-posts-ajax-select-after','slug' => 'color-posts-ajax-select-after','color' => '#ffffff'],
            ['name' => 'color-posts-ajax-select-after-bg','slug' => 'color-posts-ajax-select-after-bg','color' => '#0160ac'],
            ['name' => 'color-posts-ajax-select','slug' => 'color-posts-ajax-select','color' => '#3a96e0'],
            ['name' => 'color-posts-ajax-select-bg','slug' => 'color-posts-ajax-select-bg','color' => '#ffffff'],
            ['name' => 'color-posts-ajax-message-bg','slug' => 'color-posts-ajax-message-bg','color' => '#f79e9e'],
            ['name' => 'color-posts-ajax-message-border','slug' => 'color-posts-ajax-message-border','color' => '#891010'],
            ['name' => 'color-posts-ajax-message-span','slug' => 'color-posts-ajax-message-span','color' => '#891010'],
            ['name' => 'color-posts-ajax-footer-hover','slug' => 'color-posts-ajax-footer-hover','color' => '#0160ac'],
            ['name' => 'color-posts-ajax-item-meta','slug' => 'color-posts-ajax-item-meta','color' => '#b2b2be'],
            ['name' => 'color-posts-ajax-item-description','slug' => 'color-posts-ajax-item-description','color' => '#111111'],
            
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-posts-ajax .items .item footer .meta',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-posts-ajax .items .item footer .footer-title',
                'fontWeight' => '800',
                'fontSize' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-posts-ajax .items .item footer .footer-description',
                'fontWeight' => '500',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-posts-ajax .items .item footer a',
                'fontWeight' => '600',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-posts-ajax .filter .categories .select select, .rdg-posts-ajax .filter .categories .select select option',
                'fontWeight' => '700',
            ],
        ];
    }
}

add_action('wp_ajax_nopriv_load_posts_ajax','get_posts_ajax_data');
add_action('wp_ajax_load_posts_ajax','get_posts_ajax_data');

function get_posts_ajax_data() {
    $items = $_POST['items'];
    $category = $_POST['category'];
    $block_id = $_POST['block_id'];

    $data = posts_ajax_get_elements([
        'quantity' => $items,
        'category_sport' => $category,
    ], 1);

    $paged = 1;
    $num_pages = intval($data->found_posts / $items);
    $posts = $data->posts;

    if (($data->found_posts % $items) != 0) {
        $num_pages++;
    }
    
    require 'partials/posts.php';

    echo '<div class="posts-ajax-pagination" data-block_id="'.$block_id.'">';
    posts_ajax_pagination($paged, $num_pages);
    echo '</div>';

    wp_die();
}

add_action('wp_ajax_nopriv_load_options_league','get_options_league');
add_action('wp_ajax_load_options_league','get_options_league');

function get_options_league() {
    $category = $_POST['category'];

    $sports = get_categories([
        'orderby' => 'name',
        'order' => 'ASC',
        'parent' => $category,
        'meta_query' => [
            [
                'key' => 'sbf_category_type',
                'value' => 'league',
                'compare' => '=',
            ]
        ]
    ]);

    echo '<option value="0">By League</option>';
    foreach ($sports as $sport) {
        echo '<option value="'.$sport->term_id.'">'.$sport->name.'</option>';
    };

    wp_die();
}

add_action('wp_ajax_nopriv_load_posts_filters','get_posts_ajax_data_filters');
add_action('wp_ajax_load_posts_filters','get_posts_ajax_data_filters');

function get_posts_ajax_data_filters() {
    $items = $_POST['items'];
    $category_sport = $_POST['category_sport'];
    $category_league = $_POST['category_league'];
    $block_id = $_POST['block_id'];

    $data = posts_ajax_get_elements([
        'quantity' => $items,
        'category_sport' => $category_sport,
        'category_league' => $category_league,
    ], 1);

    $paged = 1;
    $num_pages = intval($data->found_posts / $items);
    $posts = $data->posts;

    if (($data->found_posts % $items) != 0) {
        $num_pages++;
    }
    
    require 'partials/posts.php';

    echo '<div class="posts-ajax-pagination" data-block_id="'.$block_id.'">';
    posts_ajax_pagination($paged, $num_pages);
    echo '</div>';

    wp_die();
}

add_action('wp_ajax_nopriv_load_ajax_paginator','posts_ajax_get_paginator');
add_action('wp_ajax_load_ajax_paginator','posts_ajax_get_paginator');

function posts_ajax_get_paginator() {
    $items = $_POST['items'];
    $category_sport = $_POST['category_sport'];
    $category_league = $_POST['category_league'];
    $page = (int) $_POST['page'];
    $block_id = $_POST['block_id'];

    $data = posts_ajax_get_elements([
        'quantity' => $items,
        'category_sport' => $category_sport,
        'category_league' => $category_league,
    ], $page);

    $num_pages = intval($data->found_posts / $items);
    $posts = $data->posts;

    if (($data->found_posts % $items) != 0) {
        $num_pages++;
    }
    
    require 'partials/posts.php';

    echo '<div class="posts-ajax-pagination" data-block_id="'.$block_id.'">';
    posts_ajax_pagination($page, $num_pages);
    echo '</div>';

    wp_die();
}

function posts_ajax_get_elements($fields, $paged) {
    $get_quantity = $fields['quantity'];
    $quantity = $get_quantity ? $get_quantity : 1;

    $args = [
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => $quantity,
        'paged' => $paged
    ];

    if (isset($fields['category_league']) && $fields['category_league'] != 0) {
        $args['category__and'] = [$fields['category_sport'], $fields['category_league']];
    } else {
        $args['category__in'] = $fields['category_sport'];
    }

    $elements = (new WP_Query($args));
    wp_reset_postdata();

    return $elements;
}

function posts_ajax_get_image($image_id) {
    $post_thumbnail_id = get_post_thumbnail_id($image_id);

    if (empty($post_thumbnail_id)) {
        return '';
    }

    $attachment = wp_get_attachment_image_src($post_thumbnail_id, 'posts-list');

    return $attachment[0];
}

function posts_ajax_pagination($current, $total)
{
    $big = 999999999; // need an unlikely integer

    $pagination =  paginate_links([
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '/page/%#%',
        'current' => (int) $current,
        'total' =>  (int) $total,
        'type' => 'array' 
    ]);

    echo '<nav><ul class="pagination">';

    foreach ($pagination ?? array() as $element) {
        $dom = new DomDocument();
        $dom->loadHTML($element);
        $page = '';

        foreach($dom->getElementsByTagName('a') as $a) {
            $parts = array_filter(explode('/', $a->getAttribute('href')), 'strlen');
            $page = $parts[count($parts)];
        }

        if (strpos($page, '=')) {
            $page = explode('=', $page)[1];
        }

        echo '<li class="page-item ">' . str_replace('class="', 'data-page="'.$page.'" class="page-link ', $element) . '</li>';
    }

    echo '</ul></nav>';
}

function posts_ajax_get_sports($type = 'sport', $parent_id = null) {
    $query = [];

    if ($type == 'sport') {
        $query = [
            'orderby' => 'name',
            'order' => 'ASC',
            'meta_query' => [
                [
                    'key' => 'sbf_category_type',
                    'value' => $type,
                    'compare' => '=',
                ]
            ]
        ];
    } elseif ($type == 'league') {
        $query = [
            'orderby' => 'name',
            'order' => 'ASC',
            'parent' => $parent_id,
            'meta_query' => [
                [
                    'key' => 'sbf_category_type',
                    'value' => $type,
                    'compare' => '=',
                ]
            ]
        ];
    }

    if (is_array($query) && count($query) > 0) {
        return get_categories($query);
    }


    return $query;
}

$rdg_posts_ajax_class = new Rdg_Blocks_Posts_Ajax();
$rdg_posts_ajax_class->init();

return $rdg_posts_ajax_class;
