<?php

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

class Rdg_Blocks_Top_Cappers extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_TOP_CAPPERS;
    private $block_folder_name = 'rdg-top-cappers';
    protected $block_title = 'RDG Top Cappers';
    private $block_description = 'The block is a dynamic table with the info of the top general cappers, it allow to define if the info is manual or from an API, the date and the items included on it';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'top', 'capper', 'api'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = true;
    protected $is_config = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'RDG Top Cappers';
    protected $config_menu_title = 'Top Cappers';
    protected $interval_field = 'top_cappers_interval';

    public function init() {
        $this->register_block();
        add_action('acf/init', [$this, 'register_fields'], 20);
        add_action('acf/init', [$this, 'register_config_menu'], 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_top_cappers.css'),
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-top-cappers-template-preview.jpg",
                        ),
                    ),
                ),
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
                'render_callback' => function($block) use ($rdg_helpers) {
                    global $wp_query;
                    $loop = $wp_query->in_the_loop;
                    $template_path = RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php";

                    if ($loop) {
                        include $template_path;
                        return;
                    }

                    $trace_config = $rdg_helpers->getBacktraceConfig();
                    $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $trace_config['max_trace']);
                    $trace_valid_admin = $rdg_helpers->checkExistsTraceFunction($traces, $trace_config['max_trace'], $trace_config['functions']);

                    if (is_admin() && !$trace_valid_admin) {
                        include $template_path;
                        return;
                    }
                },
            ]);
        }
    }

    public function register_fields() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_top_cappers_block_adadasd',
                'title' => 'Block_rdg_top_cappers',
                'fields' => array(
                    array(
                        'key' => 'field_6478e3f451995',
                        'label' => 'Display Block',
                        'name' => 'display_block',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'full-width' => 'Full width',
                            'none' => 'Content',
                        ),
                        'default_value' => 'content full-width',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_6478ebf55ee3f',
                        'label' => 'Source',
                        'name' => 'source',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'manual' => 'Manual',
                            'api' => 'API',
                        ),
                        'default_value' => 'manual',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_63d06d571be30',
                        'label' => 'Cappers',
                        'name' => 'cappers',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_6478ebf55ee3f',
                                    'operator' => '==',
                                    'value' => 'manual',
                                ),
                            ),
                        ),
                        '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_63d06d571fa34',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63d06d571be30',
                            ),
                            array(
                                'key' => 'field_63d0731d3f98f',
                                'label' => 'Logo',
                                'name' => 'logo',
                                'aria-label' => '',
                                'type' => 'image',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'library' => 'all',
                                'min_width' => '',
                                'min_height' => '',
                                'min_size' => '',
                                'max_width' => '',
                                'max_height' => '',
                                'max_size' => '',
                                'mime_types' => '',
                                'preview_size' => 'medium',
                                'parent_repeater' => 'field_63d06d571be30',
                            ),
                            array(
                                'key' => 'field_63d073483f990',
                                'label' => 'Name',
                                'name' => 'name',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63d06d571be30',
                            ),
                            array(
                                'key' => 'field_63d073653f991',
                                'label' => 'Score',
                                'name' => 'score',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63d06d571be30',
                            ),
                            array(
                                'key' => 'field_63d06d5723561',
                                'label' => 'More Cappers',
                                'name' => 'more_cappers',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'block',
                                'min' => 0,
                                'max' => 0,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_63d06d5735b32',
                                        'label' => 'Name',
                                        'name' => 'name',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 1,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_63d06d5723561',
                                    ),
                                    array(
                                        'key' => 'field_63d06d5739735',
                                        'label' => 'Score',
                                        'name' => 'score',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 0,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_63d06d5723561',
                                    ),
                                ),
                                'parent_repeater' => 'field_63d06d571be30',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_64792b19d1b48',
                        'label' => 'Title',
                        'name' => 'title',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_647fcdabff527',
                        'label' => 'Period',
                        'name' => 'period',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_6478ebf55ee3f',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'today' => 'Today',
                            'yesterday' => 'Yesterday',
                            'sevenDays' => 'This Week',
                            'thirtyDays' => 'This Month',
                        ),
                        'default_value' => 'today',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 1,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64792a9a9e65a',
                        'label' => 'Number of items',
                        'name' => 'number_of_items',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_6478ebf55ee3f',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => 1,
                        'max' => 20,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-top-cappers',
                        ),
                    ),
                ),
                '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' => 'api_configuration_top_cappers_block_edf3w4esdf3',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_6389183748737',
                        'label' => 'URL',
                        'name' => 'top_cappers_api_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_638918374c11e',
                        'label' => 'Token',
                        'name' => 'top_cappers_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '45',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_top_cappers_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => $this->interval_field,
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '25',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-top-cappers',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('top_cappers_api_url', 'option');
        $api_token = get_field('top_cappers_api_token', 'option');
        $cache_refresh = get_field('top_cappers_interval', 'option');
        $items = (!empty($items)) ? intval($items) : 10;

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $api_request = $api_url.'?topWinnersToShow='.$items;
        
        $period = '';
        if (isset($attributes['period']) && !empty($attributes['period'])) {
            $period = $attributes['period'];
            $api_request .= '&'.$period.'=true';
        }
        
        $api_request .= '&api_token=' . $api_token;
        
        return [
            'items' => $items,
            'period' => $period,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_request,
        ];
    }

    public function getApiParams() {
        return [
            'period' => 'period'
        ];
    }

    public function get_image($url_image, $attributes = []) {
        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $url_image = $rdgb_helpers->getImageSource($url_image, $attributes);

        return $url_image;
    }

    public function getTitle($period) {
        if ($period == 'today') {
            return 'Today';
        }

        if ($period == 'yesterday') {
            return 'Yesterday ';
        }

        if ($period == 'sevenDays') {
            return 'This Week';
        }

        if ($period == 'thirtyDays') {
            return 'This Month';
        }

        return '';
    }

    public function getFieldsValidate() {
        return [
            //'id_handicapper' => ['required'],
            'handicapper' => ['required', 'notnull'],
            //'win' => ['required'],
            'net' => ['required', 'notnull'],
            'image' => ['required', 'notnull'],
            //'image_type' => ['required'],
            //'handicapper_url' => ['required'],
        ];
    }

    public function getPreSavedData($data, $attributes = [])
    {
        return $data;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'top-cappers-title','slug' => 'top-cappers-title','color' => '#FFFFFF'],
            ['name' => 'top-cappers-title-bg','slug' => 'top-cappers-title-bg','color' => '#0160ac'],
            ['name' => 'top-cappers-title-border','slug' => 'top-cappers-title-border','color' => '#3a96e0'],
            ['name' => 'top-cappers-body','slug' => 'top-cappers-body','color' => '#F1F1F1'],
            ['name' => 'top-cappers-logo-border','slug' => 'top-cappers-logo-border','color' => '#CCC'],
            ['name' => 'top-cappers-name','slug' => 'top-cappers-name','color' => '#111111'],
            ['name' => 'top-cappers-score','slug' => 'top-cappers-score','color' => '#0160ac'],
            ['name' => 'top-cappers-scores','slug' => 'top-cappers-scores','color' => '#0160ac'],
            ['name' => 'top-cappers-names','slug' => 'top-cappers-names','color' => '#111111'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-top-cappers .cappers .capper .capper-header .title',
                'fontWeight' => '700',
                'fontSize' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-top-cappers .cappers .capper .capper-body .name',
                'fontWeight' => '600',
                'fontSize' => '1.5rem',
            ],
            [
                'customSelector' => '.rdg-top-cappers .cappers .capper .capper-body .score',
                'fontWeight' => '700',
                'fontSize' => '1rem',
            ],
        ];
    }
}

$rdg_top_cappers_class = new Rdg_Blocks_Top_Cappers();
$rdg_top_cappers_class->init();

return $rdg_top_cappers_class;
