<?php

require_once AF2_MENU_PARENTS_CLASS;
class Af2Leads extends Af2MenuTable {

    protected function get_heading() { return 'Leads'; }
    protected function get_menu_action_button_delete_posts_() { return true; }
    protected function get_post_type_constant() { return REQUEST_POST_TYPE; }
    protected function get_posts() { return $this->Admin->af2_get_posts($this->post_type_constant, array(), 'DESC', true); }
    protected function get_table_builder_load_array_() { return array( 'page' => LEADS_DETAILS_SLUG, 'id_label' => 'ID'); }
    protected function get_menu_hook_inline_search_() { return false; }
    protected function get_menu_hook_inline_checkbox_() { 
        return array( 
            'id' => 'af2_show_uncomplete',
            'active' => false,
            'label'  => __('Save incomplete entries', 'af2_multilanguage')
        );
    }
    protected function get_menu_hook_inline_button_form_() { 
        $form_id = isset($_GET['form_id']) ? $_GET['form_id'] : 'all';
        return array( 
            'icon' => 'fas fa-download', 
            'label' => __('Export CSV file', 'af2_multilanguage'),  
            'id' => 'af2_export_csv', 
            'id_label' => 'form_id',
            'id_value' => $form_id,
            'bonus_label' => 'af2_lead_download',
            'bonus_value' => 'true',
            'bonus_labels' => ['form_ids', 'include_draft'],
            'bonus_values' => ['all', 'false'],
        );
    }
    protected function get_menu_hook_extra_title_() { 

        $title = isset($_GET['form_id']) ? $_GET['form_id'] : 'all';
        if($title == 'all') {
            $title = __('All forms', 'af2_multilanguage');
        }
        else {
            require_once AF2_MISC_FUNCTIONS_PATH;
            $post = get_post( $title );
            $post_content = af2_get_post_content($post);
            $title = isset($post_content['name']) && !empty($post_content['name']) ? $post_content['name'] : 'Formulartitel';
        }
        

        return array( 'label' => __('Form title', 'af2_multilanguage'), 'value' => $title); 
    }
    protected function get_menu_functions_select_() { 

        $posts = $this->Admin->af2_get_posts(FORMULAR_POST_TYPE);

        $all_forms = array();

        require_once AF2_MISC_FUNCTIONS_PATH;
        foreach($posts as $post) {
            $id = get_post_field( 'ID', $post );
            
            $post_content = af2_get_post_content($post);

            // remove warnigns
            $title = isset($post_content['name']) && !empty($post_content['name']) ? $post_content['name'] : __('Form title', 'af2_multilanguage');

            array_push($all_forms, array('value' => $id, 'label' => $title));
        }

        return array( 
            'title' => __('Select form:', 'af2_multilanguage'),
            'id' => 'form_id_chooser',
            'getattribute' => 'form_id',
            'link' => admin_url('/admin.php?page='.LEADS_SLUG),
            'selected' => isset($_GET['form_id']) ? $_GET['form_id'] : 'all',
            'all_label' => __('All forms', 'af2_multilanguage'),
            'options' => $all_forms,
        ); 
    }
    
    protected function get_table_columns() {
        return array(
            array( 'lable' => 'ID', 'translate' => false, 'highlight' => true,                  'width' => '110px', 'flex' => '',  'max-width' => '', 'min-width' => '', 'button' => false, 'uid' => true, 'url' => true),
            array( 'lable' => 'Date / Time', 'translate' => false, 'highlight' => false,    'width' => '230px', 'flex' => '',  'max-width' => '', 'min-width' => '', 'button' => false, 'uid' => false, 'url' => true),
            array( 'lable' => 'Name', 'translate' => true, 'highlight' => false,                'width' => '',      'flex' => '1', 'max-width' => '', 'min-width' => '', 'button' => false, 'uid' => false),
            array( 'lable' => 'E-mail', 'translate' => false, 'highlight' => false,             'width' => '',      'flex' => '1', 'max-width' => '', 'min-width' => '', 'button' => false, 'uid' => false),
            array( 'lable' => 'Phone', 'translate' => false, 'highlight' => false,            'width' => '',      'flex' => '1', 'max-width' => '', 'min-width' => '', 'button' => false, 'uid' => false),
            array( 'lable' => 'Details', 'translate' => true, 'highlight' => false,             'width' => '160px', 'flex' => '',  'max-width' => '', 'min-width' => '', 'button' => true, 'url' => true, 'buttonclass' => 'primary', 'uid' => false),
            array( 'lable' => 'post_status', 'hidden' => true, 'translate' => false, 'highlight' => false,  'width' => '160px', 'flex' => '',  'max-width' => '', 'min-width' => '', 'button' => false, 'uid' => false),
        ); 
    }
    protected function edit_posts_for_table($posts) {
        $form_id = isset($_GET['form_id']) ? $_GET['form_id'] : 'all';

        $leads = $this->af2_process_leads($posts, $form_id);
            
        $new_posts = array();

        foreach($leads as $lead) {
            $new_post = array();
            $new_post['ID'] = $lead['_id'];
            $new_post['Date / Time'] = $lead['_date'];
            $new_post['Name'] = $lead['_name'];
            $new_post['E-mail'] = $lead['_mail'];
            $new_post['Phone'] = $lead['_phone'];
            $new_post['Details'] = $lead['_details'];
            $new_post['post_status'] = $lead['_post_status'];

            array_push($new_posts, $new_post);
        }

        return $new_posts;
    }

    private function af2_process_leads($posts, $form_id, $detailed = false) {
        $new_posts = array();
        if(!is_array($form_id)) {
            $form_id = [$form_id];
        }

        require_once AF2_MISC_FUNCTIONS_PATH;
        foreach($posts as $post) {

            $post_content = af2_get_post_content($post);

            // remove warnigns
            
            $name = '-';
            $email = '-';
            $phone = '-';

            if(isset($post_content['contact_form'])) {
                foreach($post_content['contact_form'] as $answer) {
                    if(isset($answer['typ']) && $answer['typ'] == 'text_type_name' && $name == '-') $name = $answer['input'];
                    if(isset($answer['typ']) && $answer['typ'] == 'text_type_phone' && $phone == '-') $phone = $answer['input'];
                    if(isset($answer['typ']) && $answer['typ'] == 'text_type_mail' && $email == '-') $email = $answer['input'];
                }    
            }

            
            
            $new_post = array();
            $new_post['_id'] = get_post_field('ID', $post );
            $new_post['_date'] = get_post_field('post_date', $post);
            $new_post['_name'] = $name;
            $new_post['_mail'] = $email;
            $new_post['_phone'] = $phone;
            $new_post['_details'] = 'Details';
            $new_post['_post_status'] = get_post_field('post_status', $post);


            if( $detailed ) {
                $form_questions = array();
                $form_fields = array();
                $form_analytics = array();

                if(isset( $post_content['questions'] ) && is_array( $post_content['questions'] )) {
                    foreach( $post_content['questions'] as $field ) {
                        if(!is_array($field)) continue;
                        $new_field = array( 'label' => $field['frage'], 'value' => $field['antwort'], 'id' => $field['frage'] );
                        array_push($form_questions, $new_field);
                    }
                }

                if(isset( $post_content['contact_form'] ) && is_array( $post_content['contact_form'] )) {
                    foreach( $post_content['contact_form'] as $field ) {
                        if(!is_array($field)) continue;
                        $id = $field['id'];
                        $label = isset($field['label']) && !empty($field['label']) ? $field['label'] : $field['id'];
                        $new_field = array( 'label' => $label, 'value' => $field['input'], 'id' => $id );
                        array_push($form_fields, $new_field);
                    }
                }
        
                if(isset( $post_content['analyticsData'] ) && is_array( $post_content['analyticsData'] )) {
                    foreach( $post_content['analyticsData'] as $field ) {
                        if(!is_array($field)) continue;
                        $label = $field['id'];
                        if($label == 'queryString') $label = __('Received URL parameters', 'af2_multilanguage');
                        if($label == 'url') $label = __('URL on which the form was submitted', 'af2_multilanguage');
                        $new_field = array( 'label' => $label, 'value' => $field['value'], 'id' => $field['id'] );
                        array_push($form_analytics, $new_field);
                    }
                }

                $detailed_array = array_merge($form_analytics, $form_fields, $form_questions);

                foreach( $detailed_array as $detail ) {
                    $new_post[$detail['id']] = $detail['value'];
                }

                $new_post['_af2_detailed'] = $detailed_array;
            }

            if(
                in_array('all',$form_id ) ||
                (isset($post_content['form_id']) && in_array($post_content['form_id'], $form_id)) ||
                (in_array($post->ID, $form_id))
            ) {
                array_push($new_posts, $new_post);
            }
        }

        return $new_posts;
    }

    public function do_request_handling() {
        if(isset($_POST['af2_lead_download'])) {
            require_once AF2_MENU_AJAX_LEADS;
            $ajax_leads = new Af2AjaxLeads();

            $drafts = (isset($_POST['include_draft']) && $_POST['include_draft'] == 'true') ? true : false;

            $form_id = isset($_POST['form_id']) ? $_POST['form_id'] : 'all';
            $form_ids = (isset($_POST['form_ids']) && $_POST['form_ids'] !== 'all') ? explode(",", $_POST['form_ids']) : $form_id;

            $posts = $this->Admin->af2_get_posts(REQUEST_POST_TYPE, array(), 'DESC', true);
            $lead_list = $this->af2_process_leads($posts, $form_ids, true);
            $ajax_leads->af2_handle_leads_export($lead_list);
        }
    }

    protected function load_resources() {
        wp_enqueue_script('af2_leads');

        parent::load_resources();
    }
}
