<?php

require_once AF2_MENU_PARENTS_CLASS;
class Af2Termineventbuilder extends Af2MenuBuilder {

    protected function get_builder_heading() { return array('label' => 'Terminevent-Editor', 'icon' => 'fas fa-edit'); }
    protected function get_builder_template() { return AF2_BUILDER_TEMPLATE_TERMINEVENT; }
    protected function get_close_editor_url() { return admin_url('/admin.php?page='.TERMINEVENT_SLUG ); }

    protected function get_builder_script() { return 'af2_termineventbuilder'; }
    protected function get_builder_style() { return 'af2_termineventbuilder_style'; }
    protected function get_builder_script_object_name() { return 'af2_termineventbuilder_object';  }
    protected function get_builder_script_localize_array() { 
        return array(
            'strings' => array(
                'antwort' => __('Answer text', 'af2_multilanguage'),
                'daily' => __('Daily', 'af2_multilanguage'),
                'mofr' => __('Mon - Fri', 'af2_multilanguage'),
                'saso' => __('Sat - Sun', 'af2_multilanguage'),
                'monday' => __('Monday', 'af2_multilanguage'),
                'tuseday' => __('Tuesday', 'af2_multilanguage'),
                'wednesday' => __('Wednesday', 'af2_multilanguage'),
                'thursday' => __('Thursday', 'af2_multilanguage'),
                'friday' => __('Friday', 'af2_multilanguage'),
                'saturday' => __('Saturday', 'af2_multilanguage'),
                'sunday' => __('Sunday', 'af2_multilanguage'),
                'von' => __('from', 'af2_multilanguage'),
                'bis' => __('to', 'af2_multilanguage'),
                'hours' => __('Hour/s', 'af2_multilanguage'),
                'minutes' => __('Minute/s', 'af2_multilanguage'),
                'days' => __('Day/s', 'af2_multilanguage'),
            )
        );
    }

    protected function get_builder_sidebar_edit_() { return array('label' => 'Settings'); }
    protected function get_builder_sidebar_edit_elements_() {
        require_once AF2_MENU_TERMINEVENTBUILDER_ELEMENTS_PATH;
        return get_termineventbuilder_elements();
    }

    protected function get_af2_builder_custom_contents_() {
        $post_content = unserialize(urldecode($this->post));
        $url = $this->get_cronofy_url();
        $cronofy_token_data = isset($post_content['cronofy_token_data']) ? $post_content['cronofy_token_data'] : null;
        
        $urlparts = parse_url(home_url());
        $domain = $urlparts['host'];
        $key = get_option('af2_license_key');

        $buttonText = __('Please contact support', 'af2_multilanguage');
        $buttonLink = 'https://www.funnelforms.io/supportticket-erstellen';
        $calendar_type = '/';
        $calendar_name = __('No calendar connected!', 'af2_multilanguage');
        $calendar_image = plugins_url( "/res/images/red.png", AF2_PLUGIN );
        $buttonIcon = 'fas fa-user-headset';

        if(!isset($cronofy_token_data) || empty($cronofy_token_data) ) {
            $curl_response = $this->af2_cronofy_curl_exec('cronofy/v1/getLoginUrl', [], array("origin_domain"=>$url));
            
            $curl_resp_arr = json_decode($curl_response, true);
            if($curl_resp_arr != null && $curl_resp_arr['error'] == 0 && $curl_resp_arr['autherror'] == 0) {
                $buttonLink = $curl_resp_arr['content'];
                $buttonText = __('Add connection', 'af2_multilanguage');
                $buttonIcon = 'fas fa-plus';
            }

            // Return for the case that we have to login or Error logging in
            return array(
                'calendar_image' => $calendar_image,
                'calendar_name' => $calendar_name,
                'calendar_type' => $calendar_type == 'Live_connect' ? 'Outlook.com' : $calendar_type,
                'buttonLink' => $buttonLink,
                'buttonText' => $buttonText,
                'buttonIcon' => $buttonIcon,
            );
        }

        $curl_response = $this->af2_cronofy_curl_exec('cronofy/v1/listCalendars', [], array("token"=>af_base64UrlEncode(json_encode($cronofy_token_data))));

        $curl_resp_arr = json_decode($curl_response, true);

        if($curl_resp_arr != null && $curl_resp_arr['error'] == 0 && $curl_resp_arr['autherror'] == 0) {
            if(isset($curl_resp_arr['token'])) {
                $_post = get_post($_GET['id']);

                $_post_title_ = $_post->post_title;
                $_post_content_ = unserialize(urldecode($_post->post_content));
                $_post_content_['cronofy_token_data']['access_token'] = $curl_resp_arr['token']['access_token'];
                $_post_content_['cronofy_token_data']['refresh_token'] = $curl_resp_arr['token']['refresh_token'];
                
                wp_update_post(array('ID' => $_GET['id'], 'post_status' => 'privat', 'post_title' => $_post_title_, 'post_content' => urlencode(serialize($_post_content_))));
                $post_content['cronofy_token_data'] = $_post_content_['cronofy_token_data'];
                $cronofy_token_data = $post_content['cronofy_token_data'];
            }

            $calendar_type = ucfirst($cronofy_token_data['linking_profile']['provider_name']);
            $calendar_image = plugins_url( "/res/images/success_standard.png", AF2_PLUGIN );
            $calendar_name = __('Calendar connected!', 'af2_multilanguage');
            $buttonText = __('Disconnect', 'af2_multilanguage');
            $buttonIcon = 'fas fa-times';
            $buttonLink = 'https://member.funnelforms.io/wp-json/cronofy/v1/revoke?license_key='.$key.'&domain='.$domain.'&origin='.$url.'&token='.af_base64UrlEncode(json_encode($cronofy_token_data));

            // GET CALENDARS
            $calendars = $curl_resp_arr['content']['calendars'];

            $calendarList = array();

            $i = 0;
            foreach($calendars as $calendar) {
                //if($calendar['provider_name'] == $cronofy_token_data['linking_profile']['provider_name']) {
                    array_push($calendarList, $calendar);
                //}

                if($i == 0) {
                    if(!isset($post_content['calendar_typ']) || empty($post_content['calendar_typ'])) {
                        $_post = get_post($_GET['id']);

                        $_post_title_ = $_post->post_title;
                        $_post_content_ = unserialize(urldecode($_post->post_content));
                        $_post_content_['calendar_typ'] = $calendar['calendar_id'];
                        $_post_content_['calendar_conflict'] = isset($_post_content_['calendar_conflict']) ? $_post_content_['calendar_conflict'] : array();
                        
                        wp_update_post(array('ID' => $_GET['id'], 'post_status' => 'privat', 'post_title' => $_post_title_, 'post_content' => urlencode(serialize($_post_content_))));
                        $post_content['calendar_typ'] = $_post_content_['calendar_typ'];
                    }
                }
                $i = 1;
            }

            // Return for the case that we have already a connected calendar
            return array(
                'calendar_image' => $calendar_image,
                'calendar_name' => $calendar_name,
                'calendar_type' => $calendar_type == 'Live_connect' ? 'Outlook.com' : $calendar_type,
                'buttonLink' => $buttonLink,
                'buttonText' => $buttonText,
                'buttonIcon' => $buttonIcon,
                'calendarList' => $calendarList,
            );
        } 
        
        $_post = get_post($_GET['id']);

        $_post_title_ = $_post->post_title;
        $_post_content_ = unserialize(urldecode($_post->post_content));
        $_post_content_['cronofy_token_data'] = null;
        $cronofy_token_data = null;
        $_post_content_['calendar_conflict'] = null;
        $_post_content_['calendar_typ'] = null;
        

        wp_update_post(array('ID' => $_GET['id'], 'post_status' => 'privat', 'post_title' => $_post_title_, 'post_content' => urlencode(serialize($_post_content_))));
        
        $curl_response = $this->af2_cronofy_curl_exec('cronofy/v1/getLoginUrl', [], array("origin_domain"=>$url));

        $curl_resp_arr = json_decode($curl_response, true);
        $buttonText = __('Please contact support', 'af2_multilanguage');
        $buttonIcon = 'fas fa-user-headset';
        $buttonLink = 'https://www.funnelforms.io/supportticket-erstellen';
        $calendar_type = '/';
        $calendar_name = __('No calendar connected!', 'af2_multilanguage');
        $calendar_image = plugins_url( "/res/red.png", AF2_PLUGIN );
        

        if($curl_response != null && $curl_response['error'] == 0 && $curl_response['autherror'] == 0) {
            $buttonLink = $curl_resp_arr['content'];
            $buttonText = __('Add connection', 'af2_multilanguage');
            $buttonIcon = 'fas fa-plus';
        }
        
        // Return for the error case or connecting a new calendar
        return array(
            'calendar_image' => $calendar_image,
            'calendar_name' => $calendar_name,
            'calendar_type' => $calendar_type == 'Live_connect' ? 'Outlook.com' : $calendar_type,
            'buttonLink' => $buttonLink,
            'buttonText' => $buttonText,
            'buttonIcon' => $buttonIcon,
        );
    }

    private function get_cronofy_url() {
        if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')   
            $url = "https://";   
        else  
            $url = "http://";   
        // Append the host(domain name, ip) to the URL.   
        $url.= $_SERVER['HTTP_HOST'];   
        
        // Append the requested resource location to the URL   
        $url.= $_SERVER['PHP_SELF'].'?page=af2_termineventbuilder&action=load&id='.$_GET['id'];  
        
        return af_base64UrlEncode($url);
    }

    
   
    private function af2_cronofy_curl_exec($route = 'cronofy/v1/', $headers = array(), $url_args = array()){
        $baseurl='https://member.funnelforms.io/wp-json/';
        
        $urlparts = parse_url(home_url());
        $domain = $urlparts['host'];

        $query_args = array_merge( array(
            "license_key" => get_option('af2_license_key'),
            "domain" => $domain
        ), $url_args );

        $request_url = add_query_arg( $query_args, $baseurl.$route );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $resp = curl_exec($ch);

        curl_close($ch);
        return $resp;
    }

    public function do_request_handling() {
        if(!isset($_GET['id'])) return;

        $post = get_post($_GET['id']);

        $post_content = unserialize(urldecode(get_post_field( 'post_content', $post )));
        $this->post = urlencode(serialize($post_content));

        if(!isset($_GET['revoke']) && !isset($_GET['accessToken'])) return;

        if(isset($_GET['revoke']) && $_GET['revoke'] == true) {
            $post_content['cronofy_token_data'] = null;
            $post_content['calendar_conflict'] = null;
            $post_content['calendar_typ'] = null;
            
            wp_update_post( array(
                'ID' => $_GET['id'], 
                'post_status' => 'privat',  
                'post_content' => urlencode(serialize($post_content))
            ));
        }

        if(isset($_GET['accessToken']) && $_GET['accessToken']) {
            $post_content['cronofy_token_data'] = json_decode(af_base64UrlDecode($_GET['accessToken']), true);

            wp_update_post( array(
                'ID' => $_GET['id'], 
                'post_status' => 'privat',
                'post_content' => urlencode(serialize($post_content))
            ));          
        }

        $this->post = urlencode(serialize($post_content));
    }

    public static function save_function($content) {
        $own_content = $content;
        $echo_content = array();


        if(!isset($own_content['title']) || trim($own_content['title']) == '') {
            array_push($echo_content, array('label' => __('No title specified!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#af2_terminevent_backend_heading'));
        }
        if(!isset($own_content['cronofy_token_data']) || empty($own_content['cronofy_token_data'])) {
            array_push($echo_content, array('label' => __('No calendar connected!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#calendar.custom_builder_content_card'));
        }

        if(isset($own_content['dauer']) && is_array($own_content['dauer'])) {
            foreach($own_content['dauer'] as $dauer) {
                if(intval($dauer['std']) < 0 || intval($dauer['std']) > 100) {
                    array_push($echo_content, array('label' => __('The hours of the duration must be classified between 0 and 100!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#time.custom_builder_content_card'));
                }
                if(intval($dauer['min']) < 0 || intval($dauer['min']) > 59) {
                    array_push($echo_content, array('label' => __('The minutes of the duration must be classified between 0 and 59!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#time.custom_builder_content_card'));
                }
                if(intval($dauer['min']) == 0 && intval($dauer['std']) == 0) {
                    array_push($echo_content, array('label' => __('The duration can not be 0!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#time.custom_builder_content_card'));
                }
            }
        }
        if(isset($own_content['reminder']) && is_array($own_content['reminder'])) {
            foreach($own_content['reminder'] as $reminder) {
                if($reminder['unit'] == 'minutes') {
                    if(intval($reminder['number']) < 1 || intval($reminder['number']) > 59) {
                        array_push($echo_content, array('label' => __('The minutes of reminders must be classified between 1 and 59!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#reminder.custom_builder_content_card'));
                    }
                }
                if($reminder['unit'] == 'hours') {
                    if(intval($reminder['number']) < 1 || intval($reminder['number']) > 23) {
                        array_push($echo_content, array('label' => __('The hours of reminders must be classified between 1 and 23!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#reminder.custom_builder_content_card'));
                    }
                }
                if($reminder['unit'] == 'days') {
                    if(intval($reminder['number']) < 1 || intval($reminder['number']) > 7) {
                        array_push($echo_content, array('label' => __('The days of reminders must be classified between 1 and 7!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#reminder.custom_builder_content_card'));
                    }
                }
            }
        }

        if(isset($own_content['datumsbereich']) && $own_content['datumsbereich'] == 'daterange_future') {
            if($own_content['daterange_future_unit'] == 'day') {
                if(intval($own_content['daterange_future_number']) < 1 || intval($own_content['daterange_future_number']) > 6) {
                    array_push($echo_content, array('label' => __('The days of the daterange must be classified between 1 and 6!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#date.custom_builder_content_card'));
                }
            }
            if($own_content['daterange_future_unit'] == 'week') {
                if(intval($own_content['daterange_future_number']) < 1 || intval($own_content['daterange_future_number']) > 3) {
                    array_push($echo_content, array('label' => __('The weeks of the daterange must be classified between 1 and 3!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#date.custom_builder_content_card'));
                }
            }
            if($own_content['daterange_future_unit'] == 'month') {
                if(intval($own_content['daterange_future_number']) < 1 || intval($own_content['daterange_future_number']) > 12) {
                    array_push($echo_content, array('label' => __('The month of the daterange must be classified between 1 and 12!', 'af2_multilanguage'), 'type' => 'af2_error', 'error_object' => '#date.custom_builder_content_card'));
                }
            }
        }
        
        
        array_push($echo_content, array('label' => __('Saved successfully!', 'af2_multilanguage'), 'type' => 'af2_success'));

        

        $own_content['error'] = false;

        foreach( $echo_content as $content ) {
            if($content['type'] == 'af2_error') {
                $own_content['error'] = true;
                break;
            }
        }

        echo json_encode($echo_content);
        return $own_content;
    }

    protected function load_resources() {
        parent::load_resources();

        require_once AF2_RESOURCE_HANDLER_PATH;
        af2_load_daterangepicker_resources();
    }
}