<?php

namespace SEOAIC;

use Exception;
use SEOAIC\repositories\LeadAddonRepository;
use SeoaicAjaxValidation;
use WP_Query;

class SeoaicLeadsAddon
{
    private $seoaic;

    const LEADS_ADDON_FIELD = 'leads_addon_settings';
    const LEAD_LOADED_STATUS = 'loaded';
    const LEAD_INIT_STATUS = 'initiated';
    const LEAD_CAPTURED_STATUS = 'captured';

    private $leadAddonRepository;

    public function __construct($seoaic) {
        $this->seoaic = $seoaic;
        $this->leadAddonRepository = new LeadAddonRepository();

        add_action('wp_ajax_seoaic_settings_leads_addon_form_save', [$this, 'leadsAddonFormSave']);
        add_action('wp_ajax_seoaic_get_lead_forms', [$this, 'getLeadForms']);
        add_action('wp_ajax_seoaic_add_lead_form_to_post', [$this, 'addLeadFormToPost']);
    }

    public static function getSettings()
    {
        global $SEOAIC_OPTIONS;

        $settings = !empty($SEOAIC_OPTIONS[SeoaicLeadsAddon::LEADS_ADDON_FIELD]) ? $SEOAIC_OPTIONS[SeoaicLeadsAddon::LEADS_ADDON_FIELD] : [];
        $bg                 = !empty($settings['bg']) ? $settings['bg'] : '#fff';
        $botMsgBg           = !empty($settings['bot_msg_bg']) ? $settings['bot_msg_bg'] : '#fff';
        $userMsgBg          = !empty($settings['user_msg_bg']) ? $settings['user_msg_bg'] : '#fff';
        $botMsgColor        = !empty($settings['bot_msg_color']) ? $settings['bot_msg_color'] : '#100717';
        $userMsgColor       = !empty($settings['user_msg_color']) ? $settings['user_msg_color'] : '#100717';
        $botFontsize        = !empty($settings['bot_fontsize']) ? $settings['bot_fontsize'] : '13';
        $userFontsize       = !empty($settings['user_fontsize']) ? $settings['user_fontsize'] : '13';
        $borderRadius       = !empty($settings['border_radius']) ? $settings['border_radius'] : '0';
        $boxBorderWidth     = !empty($settings['box_border_width']) ? $settings['box_border_width'] : '0';
        $boxBorderColor     = !empty($settings['box_border_color']) ? $settings['box_border_color'] : '#000';
        $boxShadow          = !empty($settings['box_add_shadow']) ? $settings['box_add_shadow'] : false;
        $botMsgborderWidth  = !empty($settings['bot_msg_border_width']) ? $settings['bot_msg_border_width'] : '0';
        $botMsgborderColor  = !empty($settings['bot_msg_border_color']) ? $settings['bot_msg_border_color'] : '#000';
        $userMsgBorderWidth = !empty($settings['user_msg_border_width']) ? $settings['user_msg_border_width'] : '0';
        $userMsgBorderColor = !empty($settings['user_msg_border_color']) ? $settings['user_msg_border_color'] : '#000';
        $botMsgIcon         = !empty($settings['bot_msg_icon']) ? $settings['bot_msg_icon'] : '';
        $botIconBorderWidth = !empty($settings['bot_icon_border_width']) ? $settings['bot_icon_border_width'] : '0';
        $botIconBorderColor = !empty($settings['bot_icon_border_color']) ? $settings['bot_icon_border_color'] : '#000';
        $progressHeight     = !empty($settings['progress_height']) ? $settings['progress_height'] : '5';
        $progressColor      = !empty($settings['progress_color']) ? $settings['progress_color'] : '#000';
        $emailType          = !empty($settings['email_type']) ? $settings['email_type'] : 'plain';
        $emailSubject       = !empty($settings['email_subject']) ? $settings['email_subject'] : [];
        $emails             = !empty($settings['emails']) ? $settings['emails'] : [];

        return [
            'bg'                    => $bg,
            'bot_msg_bg'            => $botMsgBg,
            'user_msg_bg'           => $userMsgBg,
            'bot_msg_color'         => $botMsgColor,
            'user_msg_color'        => $userMsgColor,
            'bot_fontsize'          => $botFontsize,
            'user_fontsize'         => $userFontsize,
            'border_radius'         => $borderRadius,
            'box_border_width'      => $boxBorderWidth,
            'box_border_color'      => $boxBorderColor,
            'box_add_shadow'        => $boxShadow,
            'bot_msg_border_width'  => $botMsgborderWidth,
            'bot_msg_border_color'  => $botMsgborderColor,
            'user_msg_border_width' => $userMsgBorderWidth,
            'user_msg_border_color' => $userMsgBorderColor,
            'bot_msg_icon'          => $botMsgIcon,
            'bot_icon_border_width' => $botIconBorderWidth,
            'bot_icon_border_color' => $botIconBorderColor,
            'progress_height'       => $progressHeight,
            'progress_color'        => $progressColor,
            'email_type'            => $emailType,
            'email_subject'         => $emailSubject,
            'emails'                => $emails,
        ];
    }

    public function leadsAddonFormSave()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        $__POST = wp_unslash($_POST);
        $errors = [];

        if (
            empty($__POST['emails'])
            || !is_array($__POST['emails'])
        ) {
            SEOAICAjaxResponse::alert(esc_html__("No emails set", "seoaic"))->wpSend();
        }

        foreach ($__POST['emails'] as $email) {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors[] = '"' . $email . '" ' . esc_html__("must be a valid email", "seoaic");
            }
        }

        if (!empty($errors)) {
            SEOAICAjaxResponse::error(esc_html__('Wrong data:', 'seoaic') . implode('; ', $errors))->wpSend();
        }

        $settings = !empty($SEOAIC_OPTIONS[self::LEADS_ADDON_FIELD]) ? $SEOAIC_OPTIONS[self::LEADS_ADDON_FIELD] : [];

        foreach ($__POST as $key => $value) {
            switch ($key) {
                case 'seoaic_leads_form_bg':
                case 'seoaic_leads_form_bot_msg_bg':
                case 'seoaic_leads_form_user_msg_bg':
                case 'seoaic_leads_form_bot_msg_color':
                case 'seoaic_leads_form_user_msg_color':
                case 'seoaic_leads_form_bot_fontsize':
                case 'seoaic_leads_form_user_fontsize':
                case 'seoaic_leads_form_border_radius':
                case 'seoaic_leads_form_box_border_width':
                case 'seoaic_leads_form_box_border_color':
                case 'seoaic_leads_form_bot_msg_border_width':
                case 'seoaic_leads_form_bot_msg_border_color':
                case 'seoaic_leads_form_user_msg_border_width':
                case 'seoaic_leads_form_user_msg_border_color':
                case 'seoaic_leads_form_bot_msg_icon':
                case 'seoaic_leads_form_bot_icon_border_width':
                case 'seoaic_leads_form_bot_icon_border_color':
                case 'seoaic_leads_form_progress_height':
                case 'seoaic_leads_form_progress_color':
                    $key = str_replace('seoaic_leads_form_', '', $key); // remove unnecessary string
                    $settings[$key] = stripslashes(sanitize_textarea_field($value));
                    break;

                case 'email_type':
                case 'emails':
                    $settings[$key] = $value;
                    break;

                case 'email_subject':
                    $settings[$key] = sanitize_text_field($value);
                    break;
            }
        }

        $settings['box_add_shadow'] = !empty($__POST['seoaic_leads_form_box_add_shadow']) ? 'on' : 'off';

        $SEOAIC_OPTIONS[self::LEADS_ADDON_FIELD] = $settings;
        update_option('seoaic_options', $SEOAIC_OPTIONS);

        SEOAICAjaxResponse::success()->wpSend();
    }

    /**
     * Return array of records grouped by Status field
     * @return array
     */
    public function getStatusGroupedData(): array
    {
        $groupedByStatus = [];
        $data = $this->leadAddonRepository->getAll();

        if (!empty($data)) {
            foreach ($data as $row) {
                if (!isset($groupedByStatus[$row->status])) {
                    $groupedByStatus[$row->status] = [];
                }

                $groupedByStatus[$row->status][] = $row;
            }
        }

        return $groupedByStatus;
    }

    private function filterLastMonthStats(array $array)
    {
        return array_filter($array, function ($item) {
            if (empty($item->date)) {
                return;
            }
            $itemMonth = gmdate("m", strtotime($item->date));

            return $itemMonth == gmdate('m');
        });
    }

    public function makeStatsHTML()
    {
        $data = $this->getStatusGroupedData();
        $loadedAll      = !empty($data[self::LEAD_LOADED_STATUS]) ? $data[self::LEAD_LOADED_STATUS] : [];
        $initiatedAll   = !empty($data[self::LEAD_INIT_STATUS]) ? $data[self::LEAD_INIT_STATUS] : [];
        $capturedAll    = !empty($data[self::LEAD_CAPTURED_STATUS]) ? $data[self::LEAD_CAPTURED_STATUS] : [];
        $loadedTotalCount       = !empty($loadedAll) ? count($loadedAll) : 0;
        $initiatedTotalCount    = !empty($initiatedAll) ? count($initiatedAll) : 0;
        $capturedTotalCount     = !empty($capturedAll) ? count($capturedAll) : 0;

        $loadedLastMonth    = $this->filterLastMonthStats($loadedAll);
        $initiatedLastMonth = $this->filterLastMonthStats($initiatedAll);
        $capturedLastMonth  = $this->filterLastMonthStats($capturedAll);
        $loadedLastMonthCount       = !empty($loadedLastMonth) ? count($loadedLastMonth) : 0;
        $initiatedTLastMonthCount   = !empty($initiatedLastMonth) ? count($initiatedLastMonth) : 0;
        $capturedLastMonthCount     = !empty($capturedLastMonth) ? count($capturedLastMonth) : 0;

        ob_start();
        ?>
        <div class="col number-value">
            <div class="inner">
                <div class="value"><?php echo esc_html($loadedTotalCount);?> / <?php echo esc_html($loadedLastMonthCount);?></div>
                <div class="title"><?php esc_html_e("Interactive forms loaded", "seoaic");?><br>(<?php esc_html_e("total", "seoaic");?> / <?php esc_html_e("this month");?>)</div>
            </div>
        </div>
        <div class="col number-value">
            <div class="inner">
                <div class="value"><?php echo esc_html($initiatedTotalCount);?> / <?php echo esc_html($initiatedTLastMonthCount);?></div>
                <div class="title"><?php esc_html_e("Discussions initiated", "seoaic");?><br>(<?php esc_html_e("total", "seoaic");?> / <?php esc_html_e("this month");?>)</div>
            </div>
        </div>
        <div class="col number-value">
            <div class="inner">
                <div class="value"><?php echo esc_html($capturedTotalCount);?> / <?php echo esc_html($capturedLastMonthCount);?></div>
                <div class="title">
                    <?php esc_html_e("Leads captured", "seoaic");?>
                    <a href="#"
                        class="seoaic-dashboard-ms-view-link modal-button"
                        title="<?php esc_attr_e("View captured leads", "seoaic");?>"
                        data-modal="#dashboard-captured-leads"
                    ></a><br>(<?php esc_html_e("total", "seoaic");?> / <?php esc_html_e("this month");?>)
                </div>
            </div>
        </div>

        <?php
        $html = ob_get_clean();

        return $html;
    }

    public function makeLeadsTableHTML($return = false)
    {
        $data = $this->getStatusGroupedData();
        $capturedRows = !empty($data[self::LEAD_CAPTURED_STATUS]) ? $data[self::LEAD_CAPTURED_STATUS] : [];
        usort($capturedRows, function ($a, $b) {
            return ($a->date > $b->date) ? -1 : 1;
        });

        $html = '';

        if ($return) {
            ob_start();
        }
        ?>
        <div class="table">
            <div class="body">
                <div class="table-row">
                    <div class="table-col table-heading">
                        <h3><?php esc_html_e("Conversation Summary", "seoaic");?></h3>
                    </div>
                    <div class="table-col table-heading">
                        <h3><?php esc_html_e("Page", "seoaic");?></h3>
                    </div>
                    <div class="table-col table-heading flexitem">
                        <h3><?php esc_html_e("Date", "seoaic");?></h3>
                    </div>
                </div>
                <?php
                if (!empty($capturedRows)) {
                    foreach ($capturedRows as $row) {
                        $data = json_decode($row->data);
                        $timestamp = strtotime($row->date);
                        $date = wp_date('Y-m-d', $timestamp);
                        $time = wp_date('H:i:s', $timestamp);
                        ?>
                        <div class="table-row">
                            <div class="table-col text-start d-flex flex-direction-column">
                                <?php
                                if (
                                    !empty($data)
                                    && is_array($data)
                                ) {
                                    foreach ($data as $i => $step) {
                                        if (is_string($step->answer)) {
                                            $answer = str_replace('; ', '<br>', $step->answer);

                                        } else if (is_array($step->answer)) {
                                            $answer = implode('<br>', array_map(
                                                function ($item) {
                                                    return $item->field . ': ' . $item->value;
                                                },
                                                $step->answer
                                            ));
                                        }
                                        ?>
                                        <div>
                                            <div class="seoaic-dashboard-ms-step-question">
                                                <span class="seoaic-dashboard-ms-step-number"><?php echo esc_html($i+1);?></span><span><?php echo esc_html($step->question);?></span>
                                            </div>
                                            <div class="seoaic-dashboard-ms-step-answer">
                                                <span><?php echo wp_kses($answer, [
                                                    'br' => [],
                                                ]);?></span>
                                            </div>
                                        </div>
                                        <?php
                                    }
                                }
                                ?>
                            </div>
                            <div class="table-col">
                                <a href="<?php echo esc_attr($row->page_url);?>" target="_blank"><span class="dashicons dashicons-external text-decoration-none"></span><?php echo esc_html($row->page_title);?></a>
                            </div>
                            <div class="table-col flexitem">
                                <?php echo esc_html($date);?>
                                <br>
                                <?php echo esc_html($time);?>
                            </div>
                        </div>
                        <?php
                    }
                }
                ?>
            </div>
        </div>
        <?php

        if ($return) {
            $html = ob_get_clean();

            return $html;
        }
    }

    public function sendLeadEmail(int $leadID): void
    {
        try {
            $lead = $this->leadAddonRepository->getById($leadID);
            $settings = SeoaicLeadsAddon::getSettings();
            $data = [
                'data' => [
                    'content_type'  => $settings['email_type'],
                    'emails'        => $settings['emails'],
                    'page'          => [
                        "title" => $lead->pageTitle,
                        "url"   => $lead->pageUrl,
                    ],
                    'results'       => json_decode($lead->data),
                ]
            ];

            if (!empty($settings['email_subject'])) {
                $data['data']['subject'] = $settings['email_subject'];
            }

            $resp = $this->seoaic->curl->initWithReturn('/api/lead/send-result', $data, true, true);
            // error_log('resp '.print_r($resp, true));
        } catch (Exception $e) {

        }
    }

    public function makeProperStepsData(array $steps)
    {
        $stepsCount = count($steps);
        foreach ($steps as $i => &$step) {
            switch ($step['type']) {
                case 'text':
                    if (
                        empty($step['autostep'])
                        && !empty($step['buttons'][0])
                    ) {
                        $step['autostep'] = $step['buttons'][0]['step'];
                        $step['buttons'] = [];
                    }
                    break;

                case 'multi':
                    if (
                        !empty($step['formItems'])
                        && is_array($step['formItems'])
                    ) {
                        $formItems = $step['formItems'];

                        foreach ($formItems as $i => $formItemText) {
                            if (is_string($formItemText)) {
                                $step['formItems'][$i] = [
                                    "type" => "checkbox",
                                    "text" => $formItemText,
                                ];
                            }
                        }
                    }
                    break;

                case 'textfield':
                    if (
                        !empty($step['formItems'])
                        && is_array($step['formItems'])
                    ) {
                        $formItems = $step['formItems'];

                        foreach ($formItems as $i => $formItemText) {
                            if (is_string($formItemText)) {
                                $step['formItems'][$i] = [
                                    "type" => "textfield",
                                    "placeholder" => $formItemText,
                                ];
                            }
                        }
                    }
                    break;

                case 'single':
                    if (
                        !empty($step['formItems'])
                        && is_array($step['formItems'])
                    ) {
                        $nextStepId = !empty($step['buttons'][0]['step']) ? $step['buttons'][0]['step'] : '#' . (intval($step['id']) + 1);
                        $step['buttons'] = [];
                        $formItems = $step['formItems'];

                        foreach ($formItems as $i => $formItemText) {
                            if (is_string($formItemText)) {
                                $step['buttons'][$i] = [
                                    "text" => $formItemText,
                                    "step" => $nextStepId,
                                ];
                            }
                        }
                    }
                    break;

                case 'contact_fields':
                    if (
                        !empty($step['formItems'])
                        && is_array($step['formItems'])
                    ) {
                        $formItems = $step['formItems'];
                    }

                    foreach ($formItems as $i => $formItemText) {
                        if (is_string($formItemText)) {
                            $step['formItems'][$i] = [
                                "type" => "text",
                                "text" => $formItemText,
                            ];
                        }
                    }

                    if ($i+1 == $stepsCount) {
                        // add finish button
                        if (empty($step['buttons'])) {
                            $step['buttons'] = [
                                'text' => esc_html__('Submit', 'seoaic'),
                                'step' => "#finish#"
                            ];

                        // fix finish button
                        } else if (empty($step['buttons'][0]['step'])) {
                            $step['buttons'][0]['step'] = "#finish#";
                        }
                    }
                    break;
            }
        }

        return $steps;
    }

    public function makeShortcodeFromAIResponse(array $steps)
    {
        $steps = $this->makeProperStepsData($steps);
        $json = htmlentities(json_encode($steps, JSON_UNESCAPED_UNICODE), ENT_NOQUOTES|ENT_SUBSTITUTE);
        $shortcodeString = '[' . SeoaicShortcodes::MULTISTEP_FORM_SHORTCODE . ' position="undefined"]' . $json . '[/' . SeoaicShortcodes::MULTISTEP_FORM_SHORTCODE . ']';
        $output = '<!-- wp:seoaic/multistep-lead-block {"steps":' . $json . '} -->' . $shortcodeString . '<!-- /wp:seoaic/multistep-lead-block -->';

        return $output;
    }

    public function exportLeads($data)
    {
        header("Content-type: text/csv");
        $leads = $this->leadAddonRepository->getCaptured();
        usort($leads, function ($a, $b) {
            return ($a->date > $b->date) ? -1 : 1;
        });
        $fp = fopen('php://output', 'w');

        fputcsv($fp, [
            "Date",
            "Lead Name",
            "Lead Email",
            "Phone",
            "Contact method",
            "Other fields",
            "Page title",
            "Page URL",
            "Questions / Answers",
        ]);

        if (!empty($leads)) {
            foreach ($leads as $lead) {
                $data = json_decode($lead->data);
                $name = $email = $phone = $contactMethod = '';
                $qa = [];
                $otherFields = [];


                foreach ($data as $step) {
                    if ("contact_fields" == $step->type) {
                        $fields = $step->answer;

                        foreach ($fields as $field) {
                            switch ($field->field) {
                                case "Name":
                                    $name = $field->value;
                                    break;
                                case "Email":
                                    $email = $field->value;
                                    break;
                                case "Phone Number":
                                    $phone = $field->value;
                                    break;
                                case "Preferred Contact Method":
                                    $contactMethod = $field->value;
                                    break;
                                default:
                                    $otherFields[] = $field;
                            }
                        }
                    } else {
                        $qa[] = $step;
                    }
                }

                $qaData = implode("\r\n", array_map(function($item) {
                    return $item->question . ": " . $item->answer;
                }, $qa));
                $otherFieldsData = implode("\r\n", array_map(function($item) {
                    return $item->field . ": " . $item->value;
                }, $otherFields));

                fputcsv($fp, [
                    $lead->date,
                    $name,
                    $email,
                    $phone,
                    $contactMethod,
                    $otherFieldsData,
                    $lead->page_title,
                    $lead->page_url,
                    $qaData,
                ]);
            }

            fclose($fp);
        }

        exit();
    }

    public function getLeadForms()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $__REQUEST = wp_unslash($_REQUEST);
        $perPage = 10;
        $page = !empty($__REQUEST['page']) ? intval($__REQUEST['page']) : 1;
        $offset = ($page - 1) * $perPage;

        $args = [
            'post_type'         => 'wp_block',
            'post_status'       => 'any',
            'posts_per_page'    => $perPage,
            'paged'             => $page,
            'offset'            => $offset,
            'skip_hiding'       => true,
            'lang'              => '',
            'ignore_sticky_posts' => true,
            'tax_query'         => [
                [
                    'taxonomy'  => 'wp_pattern_category',
                    'field'     => 'slug',
                    'terms'     => 'leads-forms',
                ],
            ],
        ];
        if (!empty($__REQUEST['search'])) {
            $args['s'] = $__REQUEST['search'];
        }

        $query = new WP_Query($args);

        SEOAICAjaxResponse::success()->addFields([
            'total_count'   => $query->found_posts,
            'data'          => array_map(function ($post) {
                return [
                    'id'    => $post->ID,
                    'text'  => $post->post_title,
                ];
            }, $query->get_posts()),
        ])->wpSend();
    }

    public function addLeadFormToPost()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        try {
            $__REQUEST = wp_unslash($_REQUEST);

            if (empty($__REQUEST['post-mass-edit'])) {
                throw new Exception(esc_html__('No posts selected', 'seoaic'));
            }
            if (empty($__REQUEST['seoaic_lead_form'])) {
                throw new Exception(esc_html__('No lead form selected', 'seoaic'));
            }

            $postIDs = is_array($__REQUEST['post-mass-edit']) ? $__REQUEST['post-mass-edit'] : [$__REQUEST['post-mass-edit']];
            $postIDs = array_filter($postIDs, function ($id) {
                return is_numeric($id);
            });
            $return = [];

            if (empty($postIDs)) {
                throw new Exception(esc_html__('No posts selected', 'seoaic'));
            }

            if (!$leadForm = get_post($__REQUEST['seoaic_lead_form'])) {
                throw new Exception(esc_html__('Lead form not found', 'seoaic'));
            }

            $args = [
                'post_type'     => seoaic_get_post_types(),
                'post_status'   => 'any',
                'posts_per_page' => -1,
                'skip_hiding'   => true,
                'lang'          => '',
                'post__in'      => $postIDs,
            ];
            $query = new WP_Query($args);

            if (!$query->found_posts) {
                throw new Exception(esc_html__('Posts not found', 'seoaic'));
            }

            foreach ($query->posts as $post) {
                $result = wp_update_post([
                    'ID'           => $post->ID,
                    'post_content' => $post->post_content . '<br><br>' . $leadForm->post_content,
                ]);

                if (
                    $result
                    && !is_wp_error($result)
                ) {
                    $return[] = [
                        'id'            => $post->ID,
                        'title'         => $post->post_title,
                        'admin_url'     => get_edit_post_link($post),
                    ];
                }
            }

            SEOAICAjaxResponse::success()->addFields([
                'content' => [
                    'message'   => esc_html__("Posts updated successfully!", "seoaic"),
                    'posts'     => $return,
                ],
            ])->wpSend();

        } catch (Exception $e) {
            SEOAICAjaxResponse::alert($e->getMessage())->wpSend();
        }
    }
}
