<?php

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

/**
 * HELPER COMMENT START
 * 
 * This class is used to bring your plugin to life. 
 * All the other registered classed bring features which are
 * controlled and managed by this class.
 * 
 * Within the add_hooks() function, you can register all of 
 * your WordPress related actions and filters as followed:
 * 
 * add_action( 'my_action_hook_to_call', array( $this, 'the_action_hook_callback', 10, 1 ) );
 * or
 * add_filter( 'my_filter_hook_to_call', array( $this, 'the_filter_hook_callback', 10, 1 ) );
 * or
 * add_shortcode( 'my_shortcode_tag', array( $this, 'the_shortcode_callback', 10 ) );
 * 
 * Once added, you can create the callback function, within this class, as followed: 
 * 
 * public function the_action_hook_callback( $some_variable ){}
 * or
 * public function the_filter_hook_callback( $some_variable ){}
 * or
 * public function the_shortcode_callback( $attributes = array(), $content = '' ){}
 * 
 * 
 * HELPER COMMENT END
 */

/**
 * Class Sh_Handicappers_Run
 *
 * Thats where we bring the plugin to life
 *
 * @package		SHHANDICAP
 * @subpackage	Classes/Sh_Handicappers_Run
 * @author		IT
 * @since		1.0.0
 */
class Sh_Handicappers_Run {

    /**
     * Our Sh_Handicappers_Run constructor 
     * to run the plugin logic.
     *
     * @since 1.0.0
     */
    function __construct() {
        $this->add_hooks();
    }

    /**
     * ######################
     * ###
     * #### WORDPRESS HOOKS
     * ###
     * ######################
     */

    /**
     * Registers all WordPress and plugin related hooks
     *
     * @access	private
     * @since	1.0.0
     * @return	void
     */
    private function add_hooks() {
        add_action('wp_enqueue_scripts', [$this, 'enqueue_backend_scripts_and_styles'], 20);
        add_action('admin_menu', [$this, 'register_shh_menu'], 20);
        add_action('acf/init', [$this, 'generate_form_sportshub_handicappers'], 20);
        add_action('acf/init', [$this, 'generate_form_sportshub_handicappers_contents'], 20);
        add_action('acf/init', [$this, 'generate_form_sportshub_handicappers_bio'], 20);
        add_action('acf/save_post', [$this, 'save_options_sportshub_handicappers']);
        add_shortcode('my_shortcode_tag', array($this, 'add_shortcode_callback'));
        add_filter('cron_schedules', [$this,'shh_add_cron_interval']);
        add_action('shh_cron_event', [$this, 'shh_cron_function']);
        register_activation_hook(SHHANDICAP_PLUGIN_FILE, array($this, 'activation_hook_callback'));
        register_deactivation_hook(SHHANDICAP_PLUGIN_FILE, [$this, 'deactivation_hook_callback']);
        add_filter('acf/load_value/name=shh_reset_last_run', [$this, 'load_field_shh_reset_last_run'], 10, 3);
    
        if (get_option('shh_status') == 1) {
            add_action('init', [$this, 'add_custom_post_type'], 10);
        }

        add_filter( 'single_template', [$this, 'handicapper_template'] );
    }

    public  function handicapper_template($single_template) {
        global $post;
        $shh = Sh_Handicappers::instance();
    
        if ($post->post_type == $shh->get_slug(false)) {
            $single_template = SHHANDICAP_PLUGIN_DIR . 'templates/handicapper.php';
        }

        return $single_template;
    }


    public function load_field_shh_reset_last_run($value) {
        if ($value == 'reset') {
            update_field('shh_reset_last_run', 'default');
        }

        return 'default';
    }

    public function add_shortcode_callback($attr = array(), $content = '') {

        $content .= ' this content is added by the add_shortcode_callback() function';

        return $content;
    }

    public function enqueue_backend_scripts_and_styles() {
        $helpers = New Sh_Handicappers_Helpers;
        wp_enqueue_style('shhandicap-backend-styles', $helpers->webpack('shh_base_style.css'), array(), SHHANDICAP_VERSION, 'all' );
        wp_enqueue_script('shhandicap-backend-scripts', SHHANDICAP_PLUGIN_URL . 'assets/js/backend-scripts.js', [], SHHANDICAP_VERSION, false);
    }

    public function register_shh_menu() {
        acf_add_options_page([
            'page_title'    => __('Sports Hub Handicappers Settings'),
            'menu_title'    => __('Sports Hub Handicappers'),
            'menu_slug'     => SHHANDICAP_NAME_SLUG,
            'capability'    => 'edit_posts',
            'icon_url'      => 'dashicons-games',
            'redirect'      => true,
        ]);

        acf_add_options_page([
            'page_title'  => __('Sports Hub Handicappers Settings'),
            'menu_title'  => __('Handicappers Settings'),
            'parent_slug' => SHHANDICAP_NAME_SLUG,
        ]);

        acf_add_options_page([
            'page_title'  => __('Sports Hub Handicappers Contents'),
            'menu_title'  => __('Handicappers Contents'),
            'parent_slug' => SHHANDICAP_NAME_SLUG,
        ]);
    }


    public function add_custom_post_type() {
        $labels = [
            'name'               => __('Handicappers', 'sportshub-handicappers'),
            'singular_name'      => __('Handicapper', 'sportshub-handicappers'),
            'all_items'          => __('All Handicappers', 'sportshub-handicappers'),
            'search_items'       => __('Search Handicappers', 'sportshub-handicappers'),
            'not_found_in_trash' => __('No handicappers found in Trash.', 'sportshub-handicappers'),
            'not_found'          => __('No handicappers found.', 'sportshub-handicappers'),
        ];

        $supports = [
            'title',
            'editor',
            'author',
            'thumbnail',
            'excerpt',
            'custom-fields',
            'revisions',
            'page-attributes'
        ];
         
        $args = [
            'labels'            => $labels,
            'supports'          => $supports,
            'public'            => true,
            'has_archive'       => true,
            'show_in_rest'      => true,
            'hierarchical'      => true,
            'capability_type'   => 'post',
            'taxonomies' => ['category'],
        ];

        $shh = Sh_Handicappers::instance();

        register_post_type($shh->get_slug(false), $args);
    }

    public function shh_add_cron_interval($schedules) {
        if(!array_key_exists("daily", $schedules)) {
            $schedules['daily'] = array(
                'interval' => 60 * 60 * 24,
                'display'  => __('Every Day'),
            );
        }

        if(!array_key_exists("twicedaily", $schedules)) {
            $schedules['twicedaily'] = array(
                'interval' => 60 * 60 * 24 / 2,
                'display'  => __('Every 12 hours'),
            );
        }
        
        if(!array_key_exists("sixhourly", $schedules)) {
            $schedules['sixhourly'] = array(
                'interval' => 60 * 60 * 6,
                'display'  => __('Every Six Hours'),
            );
        }

        if(!array_key_exists("threehourly", $schedules)) {
            $schedules['threehourly'] = array(
                'interval' => 60 * 60 * 3,
                'display'  => __('Every Three Hour'),
            );
        }

        if(!array_key_exists("hourly", $schedules)) {
            $schedules['hourly'] = array(
                'interval' => 60 * 60,
                'display'  => __('Every Hour'),
            );
        }

        return $schedules;
    }

    public function shh_cron_function() {
        // Call the WP-CLI command
        $command = 'wp sh_handicappers pull';
        $output = shell_exec($command);
    }

    /**
     * ####################
     * ### Activation/Deactivation hooks
     * ####################
     */
     
     public function activation_hook_callback() {
        if (!wp_next_scheduled('shh_cron_event')) {
            wp_schedule_event(time(), 'daily', 'shh_cron_event');
            update_option('shh_cron_time', 'daily');
        }
    }

    public function deactivation_hook_callback() {
        wp_clear_scheduled_hook('shh_cron_event');
    }

    public function generate_form_sportshub_handicappers() {
        $helpers = New Sh_Handicappers_Helpers;
        $helpers->setRedisGroup(REDIS_GROUP_SHHANDICAP);

        if(function_exists('acf_add_local_field_group')):
            acf_add_local_field_group( array(
                'key' => 'group_654429b6638be',
                'title' => 'SH Handicappers Settings',
                'fields' => array(
                    array(
                        'key' => 'field_65458ca8a734b',
                        'label' => 'Status',
                        'name' => 'shh_status',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '25',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'inactive' => 'Inactive',
                            'active' => 'Active',
                        ),
                        'default_value' => 'inactive',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_65458d2459766',
                        'label' => 'Cronjob Runtime',
                        'name' => 'shh_cron_time',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '25',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'daily' => 'Every Day',
                            'twicedaily' => 'Every 12 hours',
                            'sixhourly' => 'Every Six Hours',
                            'threehourly' => 'Every Three Hour',
                            'hourly' => 'Every Hour',
                        ),
                        'default_value' => 'daily',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_654590268d1b8',
                        'label' => 'Logs Lifetime Days',
                        'name' => 'shh_logs_lifetime',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '25',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 15,
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65c96bea5819b',
                        'label' => 'Last Handicappers Pull Datetime',
                        'name' => 'shh_last_run_message',
                        'aria-label' => '',
                        'type' => 'message',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '25',
                            'class' => '',
                            'id' => '',
                        ),
                        'message' => get_option('shh_last_run', 'never'),
                        'new_lines' => 'wpautop',
                        'esc_html' => 0,
                    ),
                    array(
                        'key' => 'field_654590c274558',
                        'label' => 'Handicaper Post Title',
                        'name' => 'shh_post_title',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '33',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '[HANDICAPPERNAME] Profile at SportHub',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_654429b682fe3',
                        'label' => 'Handicappers Data Url',
                        'name' => 'shh_data_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '33',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65458ad5865ab',
                        'label' => 'Handicappers Summary Url',
                        'name' => 'shh_summary_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '34',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65458b061ffd9',
                        'label' => 'Handicappers Picks Url',
                        'name' => 'shh_picks_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '33',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_66379b8cb5xxa',
                        'label' => 'Sports URL',
                        'name' => 'shh_sports_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '33',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65458b8cb5cca',
                        'label' => 'API Token',
                        'name' => 'shh_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '34',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'shh_field_696ec0e1bb72a',
                        'label' => 'Reset Last Run',
                        'name' => 'shh_reset_last_run',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '75',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'default' => 'Default',
                            'reset' => 'Reset',
                        ),
                        'default_value' => '',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-handicappers-settings',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            endif;    
    }

    public function generate_form_sportshub_handicappers_contents() {
        $helpers = New Sh_Handicappers_Helpers;
        $helpers->setRedisGroup(REDIS_GROUP_SHHANDICAP);

        if(function_exists('acf_add_local_field_group')):
            acf_add_local_field_group( array(
                'key' => 'group_655529b6683fe',
                'title' => 'SH Handicappers Content',
                'fields' => array(
                    array(
                        'key' => 'field_654591a83b3f5',
                        'label' => 'Handicappers',
                        'name' => 'sh_handicappers',
                        '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_654591c93b3f6',
                                'label' => 'Handicapper',
                                'name' => 'shh_handicapper',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => $helpers->getHadicappersOptions(),
                                'default_value' => null,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_654591a83b3f5',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-handicappers-contents',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            endif;    
    }

    public function save_options_sportshub_handicappers() {       
        try {
            $option = (isset($_GET['page'])) ? $_GET['page'] : null;

            if (!empty($option) && $option == 'acf-options-handicappers-settings' && isset($_POST['acf']) && is_array($_POST['acf']) && count($_POST['acf']) > 0) {
                global $shh;

                $cpt_status = current($_POST['acf']);
                $cron = next($_POST['acf']);
                $log = next($_POST['acf']);
                $title = next($_POST['acf']);
                $data = next($_POST['acf']);
                $summary = next($_POST['acf']);
                $picks = next($_POST['acf']);
                $sports = next($_POST['acf']);   
                $token = next($_POST['acf']);                
                $reset = next($_POST['acf']);
                $set_option_status = (!empty($cpt_status) && $cpt_status == 'active') ? true : false;                            

                update_option('shh_slug', $shh->get_slug(false));
                update_option('shh_status', $set_option_status, true);
                $title = (!empty($title)) ? $title : '';
                update_option('shh_post_placeholder', $title, true);
                $original_cron = get_option('shh_cron_time');
                
                if ((!empty($cron)) && ($original_cron != $cron)) {
                    wp_clear_scheduled_hook('shh_cron_event');
                    wp_schedule_event(time(), $cron, 'shh_cron_event');
                }

                update_option('shh_cron_time', $cron);

                if (!empty($reset) && $reset == 'reset') {
                    delete_option('shh_last_run');
                }
            }
        } catch (\Exception $exception) {
            error_log(print_r([
                'message' => $exception->getMessage(),
                'option' => $option,
            ], true));
        }
    }

    public function generate_form_sportshub_handicappers_bio() {
        if(function_exists('acf_add_local_field_group')):
            global $shh;
            $shh = (!empty($shh)) ? $shh : Sh_Handicappers::instance();

            acf_add_local_field_group( array(
                'key' => 'group_65663bb71b04c',
                'title' => 'Sports Hub Handicappers',
                'fields' => array(
                    array(
                        'key' => 'field_65663bb7004a6',
                        'label' => 'Handicapper Bio',
                        'name' => 'handicapper_bio',
                        'aria-label' => '',
                        'type' => 'textarea',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'default_value' => '',
                        'acfe_textarea_code' => 0,
                        'maxlength' => '',
                        'rows' => '',
                        'placeholder' => 'Enter biography',
                        'new_lines' => '',
                    ),
                    array(
                        'key' => 'field_65cd2bf777da9',
                        'label' => 'Handicappers Name',
                        'name' => 'handicappers_name',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'post_type',
                            'operator' => '==',
                            'value' => $shh->get_slug(false),
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'left',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
                'acfe_autosync' => '',
                'acfe_form' => 0,
                'acfe_display_title' => '',
                'acfe_meta' => '',
                'acfe_note' => '',
            ) );

        endif;    
    }
}