<?php

namespace SEOAIC\rest_api;

use Exception;
use SEOAIC\repositories\InteractiveArticleAddonRepository;
use SEOAIC\resources\InteractiveArticleResource;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\traits\MassActionsWorkflow;
use WP_REST_Request;
use WP_REST_Response;

class InteractiveArticleAddonAPI extends AbstractAPI
{
    use MassActionsWorkflow;

    private $seoaic;
    private $interactiveArticleRepository;

    public function __construct($seoaic)
    {
        $this->seoaic = $seoaic;
        $this->interactiveArticleRepository = new InteractiveArticleAddonRepository();


        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/interactive-article-stats/(?P<post_id>\d+)/(?P<block_id>[a-zA-Z0-9_-]+)', [
                'methods' => 'GET',
                'callback' => [$this, 'getInteractiveArticleStats'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => [
                    'post_id' => [
                        'required' => true,
                    ],
                ],
            ]);

            register_rest_route('seoaic/v1', '/interactive-article-stats', [
                'methods' => 'POST',
                'callback' => [$this, 'createInteractiveArticleStats'],
                'permission_callback' => [$this, 'validateNonce'],
            ]);
        });

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

    public function getInteractiveArticleStats(WP_REST_Request $request)
    {
        $params = $request->get_params();
        $postId = !empty($params['post_id']) ? $params['post_id'] : '';
        $blockId = !empty($params['block_id']) ? $params['block_id'] : '';
        $postStats = $this->interactiveArticleRepository->getByPostId(intval($postId));
        $blockAnswersStats = [];

        foreach ($postStats as $record) {
            $interactiveArticleStats = InteractiveArticleResource::fromDBRecord($record);
            // error_log('interactiveArticle '.print_r($interactiveArticleStats, true));

            if (empty($interactiveArticleStats->data)) {
                continue;
            }

            $statsDataArray = json_decode($interactiveArticleStats->data);

            foreach ($statsDataArray as $statsData) {
                // error_log('$statsData '.print_r($statsData, true));
                if (
                    $statsData->id != $blockId
                    || empty($statsData->answers)
                ) {
                    continue;
                }

                foreach ($statsData->answers as $answer) {
                    // error_log('answer '.print_r($answer, true));
                    if (empty($answer->id)) {
                        continue;
                    }

                    if (!isset($blockAnswersStats[$answer->id])) {
                        $blockAnswersStats[$answer->id] = 0;
                    }

                    $blockAnswersStats[$answer->id] += 1;
                }
            }
        }

        return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
            'stats' => $blockAnswersStats,
        ]));
    }

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

            $article = new InteractiveArticleResource();
            $article->postId    = !empty($body->post_id) ? intval($body->post_id) : '';
            $article->blocksCount = !empty($body->blocks_count) ? intval($body->blocks_count) : 0;
            $article->data      = json_encode($this->recursiveSanitizeTextField($body->data));

            if ($id = $this->interactiveArticleRepository->create($article)) {
                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 updateInteractiveArticleStats(WP_REST_Request $request)
    {
        try {
            $id = intval($request->get_param('id'));

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

            $interactiveArticle = $this->interactiveArticleRepository->getById($id);
            if ($interactiveArticle->id !== $id) {
                return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__("Interactive Article record not found", "seoaic")), 404);
            }

            $body = json_decode($request->get_body());
            $result = $this->interactiveArticleRepository->update($id, [
                'data' => json_encode($this->recursiveSanitizeTextField($body->data)),
            ]);

            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")), 400);
    }
}
