<?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';
    private $block_title = 'RDG Posts Ajax';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'post', 'ajax'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = false;
    protected $is_config = true;
    protected $config_page_title = 'RDG Posts Ajax';
    protected $config_menu_title = 'Posts Ajax';
    protected $config_menu_order = 7;

    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')]);
                },
                '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;
    }
}

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 ($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;
