<?php

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

class Rdg_Blocks_Injury_Report extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_INJURY_REPORT;
    private $block_folder_name = BLOCK_RDG_INJURY_REPORT;
    protected $block_title = 'RDG Injury Report';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'injury', 'report'];
    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 Injury Report';
    protected $config_menu_title = 'Injury Report';
    protected $is_pre_saved = true;

    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_injury_report.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_injury_report_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-injury-report/assets/js/rdg-injury-report.js', array('jquery'), '1', true);
                    wp_enqueue_script('rdg_injury_report_script');
                    wp_localize_script('rdg_injury_report_script','rdg_injury_report_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                    wp_localize_script('rdg_injury_report_script','rdg_blocks',['cache_dir' => CACHE_MAINTENANCE_FOLDER_URI]);
                },
                '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_injury_report_block_23432rsadfsd',
                'title' => 'Block_rdg_injury_report',
                'fields' => array(
                    array(
                        'key' => 'key_rdg_injury_report_leagues',
                        'label' => 'Leagues',
                        'name' => 'rdg_injury_report_leagues',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => '',
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'class' => 'rdg_injury_report_leagues',
                    ),
                    array(
                        'key' => 'key_rdg_injury_report_teams',
                        'label' => 'Teams',
                        'name' => 'rdg_injury_report_teams',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => '',
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_injury_report_season',
                        'label' => 'Season',
                        'name' => 'rdg_injury_report_season',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => [
                            'current' => 'Current Season',
                            'last' => 'Last Season',
                        ],
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_injury_report_items_per_page',
                        'label' => 'Items per page',
                        'name' => 'rdg_injury_report_items_per_page',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 10,
                        'min' => 1,
                        'max' => 20,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-injury-report',
                        ),
                    ),
                ),
                '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_injury_report_block_dfwefwef',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_injury_report_api_url',
                        'label' => 'URL',
                        'name' => 'injury_report_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_injury_report_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'injury_report_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_injury_report_api_token',
                        'label' => 'Token',
                        'name' => 'injury_report_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-injury-report',
                        ),
                    ),
                ),
                '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('injury_report_api_url', 'option');
        $api_token = get_field('injury_report_api_token', 'option');
        $cache_refresh = get_field('injury_report_interval', 'option');

        $items = 0;
        $team = (isset($attributes['team']) && !empty($attributes['team'])) ? $attributes['team'] : null;
        $season = (isset($attributes['season']) && !empty($attributes['season'])) ? $attributes['season'] : null;

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $api_url .= '?key='.$api_token;

        if (!empty($team)) {
            $api_url .= '&team_id='.$team;
        }

        if (!empty($season)) {
            $api_url .= '&season_id='.$season;
        }

        $request = [
            'items' => $items,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_url,
        ];

        return $request;
    }

    public function getApiParams() {
        return [
            'league' => 'rdg_injury_report_leagues',
            'team' => 'rdg_injury_report_teams',
            '_to_transform_' => [
                'key' => 'season',
                'function' => 'getSeason',
                'params' => ['rdg_injury_report_leagues', 'rdg_injury_report_season'],
            ],
        ];
    }

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

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $injury_report = $rdgb_helpers->getApiData($this->block_name, $cache_file, $request);

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

        $data->json = $injury_report->json;

        return $data;
    }

    public function getFieldsValidate() {
        return [];
    }

    public function getSeason($league, $select)
    {
        $seasons = (function_exists('shMappingSeasonsDirect')) ? shMappingSeasonsDirect($league) : [];

        if (!is_array($seasons) && count($seasons) == 0) {
            return null;
        }

        arsort($seasons);

        if ($select == 'current') {
            return key($seasons);
        }

        if ($select == 'last') {
            next($seasons);
            
            return key($seasons);
        }

        return null;
    }

    public function getColorsToloadGeneratePress()
    {
        return [
            ['name' => 'color-rdg-injury-report-pagination','slug' => 'color-rdg-injury-report-pagination','color' => '#111111'],
            ['name' => 'color-rdg-injury-report-pagination-border','slug' => 'color-rdg-injury-report-pagination-border','color' => '#E5E5E5'],
            ['name' => 'color-rdg-injury-report-pagination-border-active','slug' => 'color-rdg-injury-report-pagination-border-active','color' => '#88c0f9'],
            ['name' => 'color-rdg-injury-report-pagination-bg','slug' => 'color-rdg-injury-report-pagination-bg','color' => '#F6F7F8'],
            ['name' => 'color-rdg-injury-report-pagination-hover','slug' => 'color-rdg-injury-report-pagination-hover','color' => '#f75858'],
            ['name' => 'color-rdg-injury-report-pagination-hover-c','slug' => 'color-rdg-injury-report-pagination-hover-c','color' => '#ffffff'],
            ['name' => 'color-rdg-injury-report-injury','slug' => 'color-rdg-injury-report-injury','color' => '#111111'],
            ['name' => 'color-rdg-injury-report-injury-odd','slug' => 'color-rdg-injury-report-injury-odd','color' => '#ffffff'],
            ['name' => 'color-rdg-injury-report-injury-even','slug' => 'color-rdg-injury-report-injury-even','color' => '#F6F7F8'],
        ];
    }

    public function getStylesToloadGeneratePress()
    {
        return [
            [
                'customSelector' => '.rdg-injury-report .filter input, .rdg-injury-report .filter select',
                'fontSize' => '0.9rem',
                'lineHeight' => '1rem',
                'textTransform' => 'uppercase',
                'fontWeight' => '400',
            ],
            [
                'customSelector' => '.rdg-injury-report .results a',
                'fontSize' => '0.75rem',
                'textTransform' => 'uppercase',
                'fontWeight' => '400',
                'textDecoration' => 'none',
            ],
            [
                'customSelector' => '.rdg-injury-report .injuries .injury',
                'fontSize' => '0.9rem',
                'lineHeight' => '1.125rem',
            ],
            [
                'customSelector' => '.rdg-injury-report .pagination-result a, .rdg-injury-report .pagination-result span',
                'fontSize' => '0.8125rem',
                'fontSizeTablet' => '0.75rem',
                'fontWeight' => '600',
                'textTransform' => 'uppercase',
                'lineHeight' => '1rem',
                'textDecoration' => 'none',
            ],
            [
                'customSelector' => '.rdg-injury-report .message',
                'fontSize' => '1.2rem',
                'fontWeight' => '700',
            ],
        ];
    }

    public function getPreSavedData($data)
    {
        $pre_saved_data = [];
        $rdg_helpers = new Rdg_Blocks_Helpers();
        $players = (function_exists('shMappingTeamPlayers')) ? shMappingTeamPlayers() : [];

        if (isset($data[0]['data-content'][0][0]['injuries']) && is_array($data[0]['data-content'][0][0]['injuries']) 
            && count($data[0]['data-content'][0][0]['injuries']) > 0 && is_array($players) && count($players) > 0) {
            $injuries = $data[0]['data-content'][0][0]['injuries'];

            foreach ($injuries as $injury) {
                $pre_saved_data[0]['data-content'][0][0]['injuries'][] = [
                    'id' => $injury['id'],
                    'source_id' => $injury['source_id'],
                    'player_id' => $rdg_helpers->getPlayerName($injury['player_id'], $players),
                    'location' => $injury['location'],
                    'start_date' => $injury['start_date'],
                    'status' => $injury['status'],
                    'display_status' => $injury['display_status'],
                    'note' => $injury['note'],
                    'team_id' => $injury['team_id'],
                    'season_id' => $injury['season_id'],
                ];
            }
        }

        return $pre_saved_data;
    }

    public function getSearchOptions($block_name, $post_id, $block_id) {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
        $cache_file = $rdgb->helpers->getCacheName($block_name, $post_id, $block_id, true);

        $locations = [];
        $status = [];
        $display_status = [];

        if (file_exists($cache_file)) {
            $cache_content = file_get_contents($cache_file);
            $unserialized_content = json_decode($cache_content, true);
            
            if (isset($unserialized_content[0]['data-content'][0][0]['injuries']) && is_array($unserialized_content[0]['data-content'][0][0]['injuries'])) {
                $injuries = $unserialized_content[0]['data-content'][0][0]['injuries'];

                if (is_array($injuries) && count($injuries) > 0) {
                    foreach ($injuries as $injury) {
                        if (!in_array($injury['location'], $locations)) {
                            $locations[$injury['location']] = sprintf('<option value="%1$s">%2$s</option>', strtolower($injury['location']), ucfirst(strtolower($injury['location'])));
                        }

                        if (!in_array($injury['status'], $status)) {
                            $status[$injury['status']] = sprintf('<option value="%1$s">%2$s</option>', strtolower($injury['status']), ucfirst(strtolower($injury['status'])));
                        }

                        if (!in_array($injury['display_status'], $display_status)) {
                            $clear_display = trim(str_replace(["\r", "\n", "\t"], '', $injury['display_status']));
                            $display_status[$clear_display] = sprintf('<option value="%1$s">%2$s</option>', strtolower($clear_display), ucfirst(strtolower($clear_display)));
                        }
                    }

                    sort($locations);
                    sort($status);
                    sort($display_status);
                }
            }
        }

        return [
            'locations' => implode('', $locations),
            'status' => implode('', $status),
            'display_status' => implode('', $display_status),
        ];
    }
}

add_action('wp_ajax_nopriv_load_teams_sports','get_teams_sports');
add_action('wp_ajax_load_teams_sports','get_teams_sports');

function get_teams_sports() {
    $league = $_POST['league'];
    $teams = (function_exists('shMappingTeamsLeagueDirect')) ? shMappingTeamsLeagueDirect($league) : [];

    if (is_array($teams) && count($teams) > 0) {
        echo '<option value="">Select Option</option>';
        foreach ($teams as $id => $team) {
            echo '<option value="'.$id.'">'.$team.'</option>';
        }
    }

    wp_die();
}

$rdg_injury_report_class = new Rdg_Blocks_Injury_Report();
$rdg_injury_report_class->init();

return $rdg_injury_report_class;
