<?php

namespace SEOAIC\rest_api;

use Exception;
use SEOAIC\posts_mass_actions\LeadsFormGenerate;
use SEOAIC\repositories\LeadAddonRepository;
use SEOAIC\resources\Lead;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\SEOAIC_SETTINGS;
use SEOAIC\SeoaicLeadsAddon;
use SEOAIC\traits\MassActionsWorkflow;
use WP_REST_Request;
use WP_REST_Response;

class LeadAddonAPI extends AbstractAPI
{
    use MassActionsWorkflow;

    private $seoaic;
    private $leadAddonRepository;

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


        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/lead', [
                'methods' => 'POST',
                'callback' => [$this, 'createLead'],
                'permission_callback' => [$this, 'validateNonce'],
            ]);
        });

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/lead/(?P<lead_id>\d+)', [
                'methods' => 'PUT',
                'callback' => [$this, 'updateLead'],
                'permission_callback' => [$this, 'validateNonce'],
                'args' => [
                    'lead_id' => [
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ],
                ],
            ]);
        });

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/leads-form/generation-settings', [
                'methods' => 'GET',
                'callback' => [$this, 'getLeadsFormGenerationSettings'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
            ]);
        });

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/leads-form/generate', [
                'methods' => 'POST',
                'callback' => [$this, 'leadsFormGenerate'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ],
                ],
            ]);
        });

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/leads-form/check-status', [
                'methods' => 'GET',
                'callback' => [$this, 'leadsFormCheckStatus'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
            ]);
        });

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/leads-form/reset-post-status', [
                'methods' => 'POST',
                'callback' => [$this, 'leadsFormResetPostStatus'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ],
                ],
            ]);
        });

    }

    public function createLead(WP_REST_Request $request)
    {
        try {
            $body = json_decode($request->get_body());

            $lead = new Lead();
            $lead->status   = SeoaicLeadsAddon::LEAD_LOADED_STATUS;
            $lead->data     = json_encode([]);
            $lead->pageTitle = !empty($body->title) ? sanitize_text_field($body->title) : '';
            $lead->pageUrl  = !empty($body->url) ? sanitize_url($body->url) : '';

            if ($id = $this->leadAddonRepository->create($lead)) {
                return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
                    'id' => $id,
                ]));
            }

        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Error: ", "seoaic") . $e->getMessage()), 400);
        }

        return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Not created", "seoaic")), 400);
    }

    public function updateLead(WP_REST_Request $request)
    {
        global $SEOAIC;

        try {
            $leadID = intval($request->get_param('lead_id'));

            if (empty($leadID)) {
                return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Empty leadID", "seoaic")), 400);
            }

            $lead = $this->leadAddonRepository->getById($leadID);
            if ($lead->id !== $leadID) {
                return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Lead not found", "seoaic")), 400);
            }

            $body = json_decode($request->get_body());
            $result = $this->leadAddonRepository->update($leadID, [
                'status'    => sanitize_text_field($body->status),
                'data'      => json_encode($this->recursiveSanitizeTextField($body->lead_data)),
            ]);

            if (SeoaicLeadsAddon::LEAD_CAPTURED_STATUS == $body->status) {
                $SEOAIC->leadsAddon->sendLeadEmail($leadID);
            }

            if ($result) {
                return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), []));
            }

        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Error: ", "seoaic") . $e->getMessage()), 400);
        }

        return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Not updated", "seoaic")));
    }

    public function getLeadsFormGenerationSettings()
    {
        $getNames = function ($array) {
            return array_map(function ($item) {
                return $item['name'];
            }, $array);
        };
        $goalOptions = LeadsFormGenerate::PRIMARY_GOAL_OPTIONS;

        $data = [
            'services'          => $getNames(SEOAIC_SETTINGS::getCompanyServices()),
            'target_audience'   => $getNames(SEOAIC_SETTINGS::getTargetAudience()),
            'primary_goal'      => array_map(function ($key, $value) {
                return [
                    'value' => $key,
                    'label' => $value,
                ];
            }, array_keys($goalOptions), array_values($goalOptions)),
            'leads_form_prompt' => SEOAIC_SETTINGS::getLeadsFormGoalPromptDefault(),
        ];

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), $data));
    }

    public function leadsFormGenerate(WP_REST_Request $request)
    {
        try {
            $instance = new LeadsFormGenerate($this->seoaic);
            $instance->isAPI = true;
            $preparedData = $instance->prepareDataFromAPIRequest($request);
        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Error: ", "seoaic") . $e->getMessage()));
        }

        // $this->postsMassActionStop($instance, false);
        $result = $this->postsMassActionRun($instance, $preparedData);

        return new WP_REST_Response($result);
    }

    public function leadsFormCheckStatus(WP_REST_Request $request)
    {
        $instance = new LeadsFormGenerate($this->seoaic);
        $instance->isAPI = true;
        $data = $this->postsMassActionCheckStatusData($instance);

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), $data));
    }

    public function leadsFormResetPostStatus(WP_REST_Request $request)
    {
        $postID = intval($request->get_param('post_id'));
        $instance = new LeadsFormGenerate($this->seoaic);
        $instance->isAPI = true;
        $instance->resetPostStatus($postID);

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), []));
    }
}
