<?php

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


class Rdg_Blocks_Handicappers_Filter extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = '';
    private $block_folder_name = '';
    protected $block_title = 'RDG Handicappers Filter';
    private $block_description = 'Displays a grid of handicapper cards only, without sport or package navigation.';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'handicapper', 'filter', '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 Handicappers Filter';
    protected $config_menu_title = 'Handicappers Filter';
    protected $interval_field = 'handicappers_filter_interval';

    public function __construct() {
        $this->block_name = BLOCK_RDG_HANDICAPPERS_FILTER;
        $this->block_folder_name = BLOCK_RDG_HANDICAPPERS_FILTER;
    }

    public function init() {
        $this->register_block();
        add_action('acf/init', [$this, 'register_config_menu'], 20);
        add_action('acf/init', [$this, 'register_fields'], 20);
        add_filter('acf/load_field/key=key_handicappers_filter_duration', [$this, 'loadDurationFieldChoices'], 10, 1);
    }

    public function loadDurationFieldChoices($field) {
        $field['choices'] = $this->getHandicappersFilterDateRange();
        return $field;
    }

    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_handicappers_filter.css'),
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-handicappers-hub-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() {
        $sports_all = $this->getSports();
        $sports = (isset($sports_all['all_sports']) && is_array($sports_all['all_sports'])) ? $sports_all['all_sports'] : [];
        $handicappers = $this->getHandicappersChoicesForSelect();

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_handicappers_filter_form',
                'title' => 'Block_rdg_handicappers_filter',
                'fields' => array(
                    array(
                        'key' => 'key_handicappers_filter_mode',
                        'label' => 'Mode',
                        'name' => 'handicappers_filter_mode',
                        'type' => 'radio',
                        'choices' => array(
                            'exclude' => 'Exclude (show all except selected)',
                            'include' => 'Include (only selected)',
                        ),
                        'default_value' => 'exclude',
                        'return_format' => 'value',
                        'layout' => 'horizontal',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_handicappers',
                        'label' => 'Handicappers',
                        'name' => 'handicappers_filter_handicappers',
                        'type' => 'select',
                        'instructions' => 'Exclude: these will not be shown. Include: only these will be shown. Multiple selection.',
                        'choices' => $handicappers,
                        'return_format' => 'value',
                        'multiple' => 1,
                        'allow_null' => 1,
                        'ui' => 1,
                        'ajax' => 0,
                        'default_value' => '',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_sport',
                        'label' => 'Sports',
                        'name' => 'handicappers_filter_sport',
                        'type' => 'select',
                        'instructions' => 'Default: all.',
                        'choices' => ['0' => 'All Sports'] + $sports,
                        'default_value' => '0',
                        'return_format' => 'value',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_package',
                        'label' => 'Packages',
                        'name' => 'handicappers_filter_package',
                        'type' => 'select',
                        'instructions' => 'Default: all.',
                        'choices' => $this->getHandicappersHubPackages(),
                        'default_value' => '0',
                        'return_format' => 'value',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_duration',
                        'label' => 'Date Range',
                        'name' => 'handicappers_filter_duration',
                        'type' => 'select',
                        'instructions' => 'Options configured in the block options page.',
                        'choices' => $this->getHandicappersFilterDateRange(),
                        'default_value' => '365',
                        'return_format' => 'value',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_number_of_items',
                        'label' => 'Number of Items',
                        'name' => 'number_of_items',
                        'type' => 'number',
                        'default_value' => 8,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-handicappers-filter',
                        ),
                    ),
                ),
            ));

        endif;
    }

    public function register_config_menu() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'api_configuration_handicappers_filter',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_handicappers_filter_api_url',
                        'label' => 'URL',
                        'name' => 'handicappers_filter_api_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'handicappers_filter_interval',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_api_token',
                        'label' => 'Token',
                        'name' => 'handicappers_filter_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_handicappers_filter_date_range',
                        'label' => 'Date Range',
                        'name' => 'handicappers_filter_date_range',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        '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' => 'key_handicappers_filter_date_range_value',
                                'label' => 'Value',
                                'name' => 'value',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_handicappers_filter_date_range',
                            ),
                            array(
                                'key' => 'key_handicappers_filter_date_range_title',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_handicappers_filter_date_range',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'key_handicappers_filter_packages',
                        'label' => 'Packages',
                        'name' => 'handicappers_filter_packages',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        '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' => 'key_handicappers_filter_package_value',
                                'label' => 'Value',
                                'name' => 'value',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_handicappers_filter_packages',
                            ),
                            array(
                                'key' => 'key_handicappers_filter_package_title',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_handicappers_filter_packages',
                            ),
                            array(
                                'key' => 'key_handicappers_filter_package_url',
                                'label' => 'Package URL',
                                'name' => 'url',
                                'aria-label' => '',
                                'type' => 'url',
                                'instructions' => 'Include a URL for the package or leave blank to use the API URL',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '100',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'placeholder' => 'https://example.com/package',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_handicappers_filter_packages',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-handicappers-filter',
                        ),
                    ),
                ),
                '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('handicappers_filter_api_url', 'option');
        $api_token = get_field('handicappers_filter_api_token', 'option');
        $cache_refresh = get_field('handicappers_filter_interval', 'option');
        

        $items = (!empty($items)) ? intval($items) : 10;
        $package = (isset($attributes['package']) && !empty($attributes['package'])) ? $attributes['package'] : null;
        $duration = (isset($attributes['duration']) && !empty($attributes['duration'])) ? $attributes['duration'] : 365;
        $capper_exclude = (!empty($attributes['capper_exclude'])) ? $attributes['capper_exclude'] : [];
        
        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $api_url .= '?limit='.$items;

        $sport = null;
        if (isset($attributes['sport']) && !empty($attributes['sport'])) {
            $sport = $attributes['sport'];
            $api_url .= '&hierarchy='.$sport;
        }

        if (!empty($package)) {
            $api_url .= '&group='.$package;
        }

        $mode = isset($attributes['mode']) ? $attributes['mode'] : 'exclude';
        $handicappers_string = '';
        if ($mode === 'exclude' && !empty($capper_exclude)) {
            $handicappers_string = is_array($capper_exclude) ? implode(',', array_map('strval', array_filter($capper_exclude))) : $capper_exclude;
            if (!empty($handicappers_string)) {
                $api_url .= '&exclude='.$handicappers_string;
            }
        }

        $api_url .= '&dateRange='.$duration;
        $api_request = $api_url.'&api_token='.$api_token;

        $request = [
            'items' => $items,
            'package' => $package,
            'duration' => $duration,
            'sport' => $sport,
            'capper_exclude' => $handicappers_string,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_request,
        ];

        return $request;
    }

    public function getApiParams() {
        return [
            'package' => 'handicappers_filter_package',
            'duration' => 'handicappers_filter_duration',
            'mode' => 'handicappers_filter_mode',
            '_to_transform_' => [
                [
                    'key' => 'sport',
                    'function' => 'getSportID',
                    'params' => ['handicappers_filter_sport'],
                ],
                [
                    'key' => 'capper_exclude',
                    'function' => 'getHandicappersListFromField',
                    'params' => ['handicappers_filter_handicappers'],
                ],
            ],
        ];
    }

    public function getHandicappersListFromField($value) {
        if (is_array($value) && count($value) > 0) {
            return implode(',', array_map('strval', array_filter($value)));
        }
        if (is_string($value) && trim($value) !== '') {
            return $value;
        }
        return '';
    }

    public function getSportID($sport = 0) {
        return preg_replace('/\D/', '', $sport);
    }

    public function getResourcesAjax($request) {
        $data = new StdClass();
        $data->json = '';
        $data->message = '';

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $handicappers_filter = $rdgb_helpers->getApiDataAjax($this->block_name, $request);

        if (!empty($handicappers_filter->message)) {
            $data->message = $handicappers_filter->message;
        
            return $data;
        }

        $data->json = $handicappers_filter->json;

        return $data;
    }

    public function getFieldsValidate() {
        return [
            'name' => ['required', 'notnull'],
            'image' => ['required', 'notnull'],
            'bio' => ['required', 'notnull'],
        ];
    }

    public function getHandicappersHubDateRange() {
        return $this->getHandicappersFilterDateRange();
    }

    public function getHandicappersFilterDateRange() {
        $date_range = [];
        $ranges = get_field('handicappers_filter_date_range', 'option');

        if (is_array($ranges) && count($ranges) > 0) {
            foreach ($ranges as $range) {
                $date_range[$range['value']] = $range['title'];
            }
        }
        if (empty($date_range)) {
            $date_range['365'] = '365 days';
        }

        return $date_range;
    }

    public function getHandicappersHubPackages() {
        $packages_list = ['0' => 'Premium'];
        $packages = get_field('handicappers_filter_packages', 'option');

        if (is_array($packages) && count($packages) > 0) {
            foreach ($packages as $package) {
                $packages_list[$package['value']] = $package['title'];
            }
        }

        return $packages_list;
    }

    /**
     * Gets the packages with their configured URLs.
     *
     * @return array Associative array with 'value' => ['title' => string, 'url' => string|null]
     */
    public function getHandicappersHubPackagesWithUrls() {
        $packages_data = [];
        $packages = get_field('handicappers_filter_packages', 'option');

        if (is_array($packages) && count($packages) > 0) {
            foreach ($packages as $package) {
                $packages_data[$package['value']] = [
                    'title' => $package['title'],
                    'url' => !empty($package['url']) ? esc_url($package['url']) : null,
                ];
            }
        }

        return $packages_data;
    }

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

        return $url_image;
    }

    public function getHandicappersChoicesForSelect() {
        return (function_exists('shMappingHandicappers')) ? shMappingHandicappers() : [];
    }

    public function loadHandicappersFieldChoices($field) {
        $field['choices'] = $this->getHandicappersChoicesForSelect();
        return $field;
    }

    public function loadSportsFieldChoices($field) {
        $all = $this->getSports();
        $field['choices'] = ['0' => 'All Sports'] + (isset($all['all_sports']) ? $all['all_sports'] : []);
        return $field;
    }

    public function getSports($default_sports = []) {
        $sports_new = [];
        $default_sports_new = [];
        $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

        if (is_array($sports) && count($sports) > 0) {
            foreach ($sports as $key => $sport) {
                if (in_array(strtolower($sport), $default_sports)) {
                    $default_sports_new[$this->getSportID($key)] = strtoupper($sport);
                } else {
                    $sports_new[$this->getSportID($key)] = strtoupper($sport);
                }
            }
        }

        asort($sports_new);

        return [
            'default_sports' => $default_sports_new,
            'all_sports' => $sports_new,
        ];
    }

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

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-rdg-handicappers-filter-header','slug' => 'color-rdg-handicappers-filter-header','color' => '#03467d'],
            ['name' => 'color-rdg-handicappers-filter-header-hover','slug' => 'color-rdg-handicappers-filter-header-hover','color' => '#e11414'],
            ['name' => 'color-rdg-handicappers-filter-bg','slug' => 'color-rdg-handicappers-filter-bg','color' => '#ffffff'],
            ['name' => 'color-rdg-handicappers-filter-border','slug' => 'color-rdg-handicappers-filter-border','color' => '#EEF4FC'],
            ['name' => 'color-rdg-handicappers-filter-shadow','slug' => 'color-rdg-handicappers-filter-shadow','color' => '#F3F3F3'],
            ['name' => 'color-rdg-handicappers-filter-line','slug' => 'color-rdg-handicappers-filter-line','color' => '#67748e66'],
            ['name' => 'color-rdg-handicappers-filter-stats','slug' => 'color-rdg-handicappers-filter-stats','color' => '#878787'],
            ['name' => 'color-rdg-handicappers-filter-btn','slug' => 'color-rdg-handicappers-filter-btn','color' => '#03467d'],
            ['name' => 'color-rdg-handicappers-filter-btn-hover','slug' => 'color-rdg-handicappers-filter-btn-hover','color' => '#3a96e0'],
            ['name' => 'color-rdg-handicappers-filter-btn-default','slug' => 'color-rdg-handicappers-filter-btn-default','color' => '#E9ECEF'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-header .header-content', 'lineHeight' => '1.2rem'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-header .header-name', 'fontSize' => '1.06rem', 'fontWeight' => '700'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-header .header-package', 'fontSize' => '0.95rem', 'fontWeight' => '400'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-header .header-stats', 'fontSize' => '0.75rem', 'fontWeight' => '400'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-header .header-stats .success, .rdg-handicappers-filter .handicapper .handicapper-header .header-stats .danger', 'fontWeight' => '700'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .body-content', 'fontSize' => '0.95rem', 'fontWeight' => '400'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-footer .button-picks', 'fontSize' => '1.3rem', 'margin' => '10px 0px'],
            ['customSelector' => '.rdg-handicappers-filter .handicapper .handicapper-footer .footer-button', 'lineHeight' => '1rem'],
        ];
    }
}

$rdg_handicappers_filter_class = new Rdg_Blocks_Handicappers_Filter();
$rdg_handicappers_filter_class->init();

return $rdg_handicappers_filter_class;
