<?php

function af2_app_get_forms()
{
    if( get_option( 'af2_license_stat' ) != 'Die Domain ist aktiviert!' )
    {
        echo 'Domain not activated';
        die();
    }

    if(!app_do_auth()) return array('af2_error' => true);

    return get_app_forms_data();
}
function af2_app_get_dashboard_data()
{
//    if( get_option( 'af2_license_stat' ) != 'Die Domain ist aktiviert!' )
//    {
//        echo 'Domain not activated';
//        die();
//    }
//
//    if(!app_do_auth()) return array('af2_error' => true);

    return get_app_dashboard_data();
}
function af2_app_get_all_leads()
{
    if( get_option( 'af2_license_stat' ) != 'Die Domain ist aktiviert!' )
    {
        echo 'Domain not activated';
        die();
    }

    if( !isset( $_GET['form_id'] ) )
    {
        echo 'Parameters missing';
        die();
    }

    if(!app_do_auth()) return array('af2_error' => true);

    return get_app_all_leads($_GET['form_id']);
}
function af2_app_get_lead()
{
    if( get_option( 'af2_license_stat' ) != 'Die Domain ist aktiviert!' )
    {
        echo 'Domain not activated';
        die();
    }

    if( !isset( $_GET['lead_id'] ) )
    {
        echo 'Parameters missing';
        die();
    }

    if(!app_do_auth()) return array('af2_error' => true);

    return get_app_lead($_GET['lead_id']);
}

function get_app_lead($lead_id) {
    $post = get_post($lead_id);

    $lead_details_array = array();

    $post_content = unserialize( urldecode( get_post_field( 'post_content', $post ) ) );

    $name = null;
    $email = null;
    $phone = null;

    if(isset($post_content['questions']) && is_array($post_content['questions'])) {
        foreach( $post_content['questions'] as $field ) {
            $label = $field['frage'];

            $value = $field['antwort'];
            if( is_array( $field['antwort'] ) ) {
                $value = '';
                $i = 0;
                for ($i=0; $i < sizeof($field['antwort']); $i++) { 
                    $value .= $field['antwort'][$i];
                    if($i < sizeof($field['antwort'])-1) $value .= ', ';
                }
            }
            $new_field = array( 'label' => $label, 'value' => $value );
            array_push($lead_details_array, $new_field);
        }
    }

    if(isset($post_content['contact_form']) && is_array($post_content['contact_form'])) {
        foreach( $post_content['contact_form'] as $field ) {
            if(isset($field['typ']) && $field['typ'] == 'text_type_name' && $name == null) { $name = $field['input']; continue; }
            if(isset($field['typ']) && $field['typ'] == 'text_type_phone' && $phone == null) { $phone = $field['input']; continue; }
            if(isset($field['typ']) && $field['typ'] == 'text_type_mail' && $email == null) { $email = $field['input']; continue; }
            $label = isset($field['label']) && !empty($field['label']) ? $field['label'] : $field['id'];
            $new_field = array( 'label' => $label, 'value' => $field['input'] );
            array_push($lead_details_array, $new_field);
        }
    }

    if(!isset($post_content['questions']) && !isset($post_content['contact_form']) && !isset($post_content['analyticsData'])) {
        foreach($post_content as $field) {
            $label = isset($field['title']) && !empty($field['title']) ? $field['title'] : $field['id'];
            $value = is_array($field['answer']) ? '---' : $field['answer'];

            $new_field = array( 'label' => $label, 'value' => $value );
            array_push($lead_details_array, $new_field);
        }
    }

    $ret = array('lead_details' => $lead_details_array, 'contact_data' => array('name' => $name, 'email' => $email, 'phone' => $phone) );


    return $ret;
}

function get_app_all_leads($form_id) {
    require_once AF2_ADMIN_HELPER_PATH;
    $Admin = new Af2AdminHelper();
    $posts = $Admin->af2_get_posts(REQUEST_POST_TYPE, array(), 'DESC', false);

    $all_leads = array();
    foreach($posts as $post) { 
        $post_content = af2_get_post_content($post);

        // remove warnigns
        
        $name = null;
        $email = null;
        $phone = null;

        if(isset($post_content['contact_form'])) {
            foreach($post_content['contact_form'] as $answer) {
                if(isset($answer['typ']) && $answer['typ'] == 'text_type_name' && $name == null) $name = $answer['input'];
                if(isset($answer['typ']) && $answer['typ'] == 'text_type_phone' && $phone == null) $phone = $answer['input'];
                if(isset($answer['typ']) && $answer['typ'] == 'text_type_mail' && $email == null) $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;

        if($form_id == 'all' || (isset($post_content['form_id']) && $form_id == $post_content['form_id'])) array_push($all_leads, $new_post);
    }

    return $all_leads;
}

function get_app_dashboard_data()
{
    $Admin = new Af2AdminHelper();
    $year = filter_var( $_GET['year'], FILTER_SANITIZE_NUMBER_INT );
    $month = filter_var( $_GET['month'], FILTER_SANITIZE_NUMBER_INT );
    $month += 1;

    $impression_data = unserialize(get_option('af2_impressions_data'));
    $impression_count = isset($impression_data[$year][intval($month)]) ? $impression_data[$year][ intval($month) ] : 0;

    // Difference
    if($year == date('Y') && $month == date('m')) {
        $impression_count = get_option('af2_impressions');
    }

    // Reset
    $args = array('year' => $year, 'monthnum' => $month);
    $result = $Admin->af2_get_posts('af2_request', $args);

    $newArray = array();

    foreach($result as $res) {
        require_once AF2_MISC_FUNCTIONS_PATH;
        $content = af2_get_post_content($res);
        if($content['dashboard_relevant'] != 'not') array_push($newArray, $res);
    }

    $result = $newArray;

    $response = array();
    $labels = array();

    $total_month_days = cal_days_in_month(0, $month, $year);

    foreach ($result as $post) {
        $pDate = $post->post_date;
        $onlydate = date('d', strtotime($pDate));
        if( isset($response[$onlydate]) ){
            $response[$onlydate] += 1;
        }
        else{
            $response[$onlydate] = 1;
        }
    }

    for ($i=1; $i <= $total_month_days; $i++) {
        $index = $i < 10 ? "0".$i : $i;
        if( !isset( $response[$index] )){
            $response[$i] = 0;
        }else if($i < 10 ){
            $response[$i] = $response[$index];
            unset($response[$index]);
        }
        $temp_date = $i.'-'.$month.'-'.$year;
        $temp_time = strtotime($temp_date);
        $temp_month=date_i18n('d-F',$temp_time);
        $labels[] = __($temp_month);
    }
    ksort($response);

    $date_obj   = DateTime::createFromFormat('!m', $month);
    $month_name = $date_obj->format('F');

    $lead_count = array_sum($response);
    $conversionrate = $impression_count != 0 && $lead_count != 0 ? round((($lead_count / $impression_count) * 100), 2).'%' : '-';
    $impressionfactor = $impression_count != 0 && $lead_count != 0 ? round(($impression_count / $lead_count), 2) : '-';

    return array(
        'impressions' => $impression_count,
        'leads' => $lead_count,
        'conversionrate' => $conversionrate,
        'impressionfactor' => $impressionfactor
    );

    die();

    require_once AF2_ADMIN_HELPER_PATH;
    $Admin = new Af2AdminHelper();
    $impression_count = intval(get_option('af2_impressions'));

    $year = filter_var( $_GET['year'], FILTER_SANITIZE_NUMBER_INT );
    $month = filter_var( $_GET['month'], FILTER_SANITIZE_NUMBER_INT );

    // Get reset time for filtering
    $reset_dashboard_date_array = $Admin->convert_datestring_to_array(get_option('af2_reset_dashboard_date'));

    $leads_current_month = $impression_count > 0 ?
    $Admin->af2_get_posts( REQUEST_POST_TYPE, array(
            'date_query' => array(
                array(
                    'year' => intval($reset_dashboard_date_array['year']),
                    'month' => intval($reset_dashboard_date_array['month']),
                ),
            )
        )
    ) : array();


    $impression_data = unserialize(get_option('af2_impressions_data'));
    $impression_count = isset($impression_data[$year][intval($month)]) ? $impression_data[$year][ intval($month) ] : 0;

    $lead_count = sizeof($leads_current_month);
    $conversionrate = $impression_count != 0 && $lead_count != 0 ? round((($lead_count / $impression_count) * 100), 2).'%' : '-';
    $impressionfactor = $impression_count != 0 && $lead_count != 0 ? round(($impression_count / $lead_count), 2) : '-';

    return array(
        'impressions' => $impression_count,
        'leads' => $lead_count,
        'conversionrate' => $conversionrate,
        'impressionfactor' => $impressionfactor
    );
}

function get_app_forms_data() {
    require_once AF2_MISC_FUNCTIONS_PATH;
    require_once AF2_ADMIN_HELPER_PATH;

    $slug = 'af2_formular';

    $posts = get_posts([
        'post_type' => $slug,
        'post_status' => 'privat',
        'numberposts' => -1,
        'order'    => 'ASC'
    ]);

    $forms = '{"array":[';

    $i = 0;
    foreach( $posts as $post )
    {
        $name = '';
        $id = get_post_field('ID', $post );

        $pos = af2_get_post_content($post);
        $pos = json_decode(json_encode($pos));

        if( $pos->error != true )
        {
            if( $i > 0 )
            {
                $forms .= ',';
            }
            $name = $pos->name;
            $json = '{"id":"'.$id.'","name":"'.$name.'"}';
            $forms .= $json;

            $i++;
        }
    }

    $forms .= ']}';

    $dat = json_decode( $forms )->array;

    return $dat;
}

function app_do_auth() {
    $reg_code = get_option('af2_registered_app_code');
    $code = $_GET['af2_unique_key'];

    if($reg_code != $code) return false;
    if(get_option('af2_license_stat') != 'Die Domain ist aktiviert!') return false;
    return true;
}

function af2_register_qr() {
    if(get_option('af2_registered_app_code') != '') return array('af2_error' => 1);

    
    $newCode = $_GET['val_code'];
    $device_name = $_GET['device_name'];
    $fcm_key = $_GET['fcm_key'];

    if($newCode == get_option('app_code')) {
        update_option('af2_registered_app_code', $newCode);
        update_option('af2_registered_app_device', $device_name);
        update_option('af2_registered_app_fcm', $fcm_key);

        $urlparts = parse_url(home_url());
        $domain = $urlparts['host'];

        $baseurl = 'https://member.funnelforms.io/wp-json/af2/app/v2/notification_token';
        $data = "token=".$fcm_key."&domain=".$domain;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $baseurl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_exec($ch);
        curl_close($ch);

        af2_update_app_data();
        return array('af2_error' => 0, 'af2_key' => $newCode);
    }
    else {
        
        af2_update_app_data();

        return array('af2_error' => 1);
    }
    
}

function af2_update_app_data() {
    if(get_option('af2_license_stat') == 'Die Domain ist aktiviert!') {
        $randomNum = substr(str_shuffle("012345678901234567890123456789012345678901234567890123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmopqrstuvwxyzsdjafkleiwopvnjkdvncyfeiawojkldsmvcxy"), 0, 32);
        update_option('app_code', $randomNum);

        $valcode = get_option('app_code');
        $prefix = str_replace("wp-admin/", "", get_admin_url());
        $qrlink = $prefix.'wp-json/af2/app/v2/register_qr?val_code='.$valcode;

        update_option('app_qr_code', 'https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl='.$qrlink.'&choe=UTF-8');
    }
    else {
        update_option('app_code', '');
        update_option('app_qr_code', '');
    }
}

add_action('rest_api_init', function() {


    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Methods: GET' );
        header( 'Access-Control-Allow-Credentials: true' );
        header( 'Access-Control-Expose-Headers: Link', false );
        return $value;
    } );

    register_rest_route('af2/app/v2', 'forms', [
        'methods' => 'GET',
        'callback' => 'af2_app_get_forms',
        'permission_callback' => '__return_true'
    ]);
    register_rest_route('af2/app/v2', 'dashboard_data', [
        'methods' => 'GET',
        'callback' => 'af2_app_get_dashboard_data',
        'permission_callback' => '__return_true'
    ]);
    register_rest_route('af2/app/v2', 'all_leads', [
        'methods' => 'GET',
        'callback' => 'af2_app_get_all_leads',
        'permission_callback' => '__return_true'
    ]);
    register_rest_route('af2/app/v2', 'lead', [
        'methods' => 'GET',
        'callback' => 'af2_app_get_lead',
        'permission_callback' => '__return_true'
    ]);
    register_rest_route('af2/app/v2', 'register_qr', [
        'methods' => 'GET',
        'callback' => 'af2_register_qr',
        'permission_callback' => '__return_true'
    ]);
});
