<?php

namespace SEOAIC\posts_mass_actions;

use Exception;
use SEOAIC\repositories\ContentImprovementSuggestionsRepository;
use SEOAIC\traits\Debug;

class ContentImprovementSuggestionsGenerate extends AbstractPostsMassAction
{
    use Debug;

    private $contentImprovementSuggestionsRepository;

    protected $postRevisionRepository;

    public function __construct($seoaic)
    {
        parent::__construct($seoaic);

        $this->contentImprovementSuggestionsRepository = new ContentImprovementSuggestionsRepository($seoaic);

        $this->backendActionURL = 'api/audit/suggestions/generate';
        $this->backendCheckStatusURL = 'api/audit/suggestions/generate/status';
        $this->backendContentURL = 'api/audit/suggestions/generate/content';
        $this->backendClearURL = 'api/audit/suggestions/generate/clear';
        $this->statusField = 'seoaic_update_status';
        // $this->cronCheckStatusHookName = 'seoaic/posts/edit/check_status_cron_hook';

        // $this->successfullRunMessage = 'Update started';
        // $this->completeMessage = 'All posts have been updated.';
        // $this->stopMessage = 'Posts update have been stopped.';
    }

    // public static function init()
    // {
    //     // see SEOAIC_POSTS __construct function
    //     global $SEOAIC;

    //     $self = new self($SEOAIC);
    //     add_action($self->cronCheckStatusHookName, [$self, 'cronPostsCheckStatus']);
    // }

    public function prepareData($data)
    {
        $issues = $data['issues'];
        $issuesItemsData = [
            "issues"    => [],
            "language"  => $data['language'],
            "data"      => [
                "title"         => $data['title'],
                "description"   => $data['description'],
                "content"       => $data['content'],
            ],
        ];

        foreach ($issues as $issue) {
            $uniqueId = $data['post_id'] . '--' . $issue;
            $issuesItemsData['issues'][] = [
                'id'        => $uniqueId,
                "post_id"   => $data['post_id'],
                "issue"     => $issue,
            ];
        }

        return $issuesItemsData;
    }

    /**
     * Override parent's method to be able to make requests in a loop
     */
    public function sendActionRequest($data = [])
    {
        $this->debugLog('Request data',__CLASS__, json_encode($data));
        $response = $this->sendRequest($this->getBackendActionURL(), $data);
        $this->debugLog('Response', __CLASS__, json_encode($response));

        return [
            'data'      => $data,
            'response'  => $response,
        ];
    }

    public function processActionResults($result = [])
    {
        if (
            !empty($result['response']['status'])
            && 'success' == $result['response']['status']
            && !empty($result['data'])
            && !empty($result['data']['issues'])
        ) {
            try {
                $postsIssuesData = [];

                foreach ($result['data']['issues'] as $issue) {
                    $post = get_post($issue['post_id']);

                    if (!$post) {
                        continue;
                    }

                    if (!isset($postsIssuesData[$post->ID])) {
                        $savedPostIssuesData = $this->contentImprovementSuggestionsRepository->getSavedPostIssues($post);
                        $postsIssuesData[$post->ID] = [
                            'post'      => $post,
                            'issuesData'    => $savedPostIssuesData,
                        ];
                    }
                }

                if (!empty($postsIssuesData)) {
                    foreach ($postsIssuesData as $postId => $postIssuesData) {
                        $post = $postIssuesData['post'];
                        $issuesData = $postIssuesData['issuesData'];

                        foreach ($issuesData['issues'] as &$issue) {
                            if (ContentImprovementSuggestionsRepository::CI_POST_ISSUE_STATUS_PENDING == $issue['status']) {
                                $issue['status'] = ContentImprovementSuggestionsRepository::CI_POST_ISSUE_STATUS_REQUESTED;
                            }
                        }

                        $this->contentImprovementSuggestionsRepository->savePostIssues($post, $issuesData);
                    }
                }

                return true;

            } catch (Exception $e) {
                $this->errors[] = $e->getMessage();

                return false;
            }

        } else {
            if (!empty($result['message'])) {
                $this->errors[] = $result['message'];
            }

            if (!empty($result['response']['message'])) {
                $this->errors[] = $result['response']['message'];
            }

            return false;
        }
    }

    public function pocessCheckStatusResults($result)
    {
        $returnData = [
            'done' => [],
            'failed' => [],
        ];


        if (!empty($result)) {
            if (
                !empty($result['completed'])
                && is_array($result['completed'])
            ) {
                $returnData['done'] = $this->processCompleted($result['completed']);
            }

            if (!empty($result['failed'])) {
                $this->processFailed($result['failed']);
                $returnData['failed'] = array_merge($returnData['failed'], $result['failed']);
            }
        }

        return $returnData;
    }

    protected function processCompleted($ids = [])
    {
        $return = [];

        if (
            !empty($ids)
            && is_array($ids)
        ) {
            $data = [
                'issue_ids' => $ids,
            ];
            $contentResponse = $this->sendContentRequest($data);

            if (
                !empty($contentResponse)
                && is_array($contentResponse)
            ) {
                foreach ($contentResponse as $suggestionResult) {
                    $issueId = $suggestionResult['issueId'];
                    $post = get_post($suggestionResult['postId']);

                    if (!$post) {
                        continue;
                    }

                    $return[$issueId] = [
                        'content'   => $suggestionResult['content'],
                    ];

                    $savedPostIssues = $this->contentImprovementSuggestionsRepository->getSavedPostIssues($post);
                    foreach ($savedPostIssues['issues'] as &$postIssue) {
                        // error_log('item '.print_r($postIssue, true));
                        if ($suggestionResult['issue'] == $postIssue['issue']) {
                            $postIssue['status'] = ContentImprovementSuggestionsRepository::CI_POST_ISSUE_STATUS_COMPLETED;
                            $postIssue['new_value'] = $suggestionResult['content']['value'];
                        }
                    }
                    $this->contentImprovementSuggestionsRepository->savePostIssues($post, $savedPostIssues);
                }
            }
        }

        return $return;
    }

    protected function processFailed($ids = [])
    {

    }

    public function isRunning()
    {
        $posts = $this->getRequestedIssuesPostsAll();

        return !empty($posts);
    }

    public function cronPostsCheckStatus()
    {
        // $this->seoaic->posts->debugLog('[CRON]', __CLASS__);
        // $this->getStatusResults();
    }

    public function stop()
    {
        $this->debugLog();
        $this->sendClearRequest(['full' => true]);
        // $this->unregisterPostsCheckStatusCron();
    }

    /**
     * Gets all posts that were sent for review
     * @param array $postIDs options array of IDs to search among
     * @return array
     */
    private function getRequestedIssuesPostsAll()
    {
        $posts = [];
        $args = [
            'posts_per_page'    => -1,
            'post_type'         => 'any',
            'post_status'       => 'any',
            'lang'              => '', // disable default lang setting
            'meta_query'        => [
                'relation' => 'AND',
                [
                    'key' => 'seoaic_posted',
                    'value' => '1',
                    'compare' => '=',
                ],
                [
                    'key' => ContentImprovementSuggestionsRepository::CI_POST_ISSUES_FIELD,
                    'compare' => 'EXISTS',
                ],
            ],
        ];

        $allPosts = get_posts($args);

        if (empty($allPosts)) {
            return $posts;
        }

        foreach ($allPosts as $post) {
            $postIssues = $this->contentImprovementSuggestionsRepository->getSavedPostIssues($post);

            // error_log('postIssues '.print_r($postIssues, true));
            $requestedIssues = array_filter($postIssues['issues'], function ($issue) {
                return $issue['status'] == ContentImprovementSuggestionsRepository::CI_POST_ISSUE_STATUS_REQUESTED;
            });

            if (!empty($requestedIssues)) {
                $posts[] = $post;
            }
        }

        // error_log('posts '.print_r($posts, true));

        // $this->posts = $posts;

        return $posts;
    }
}
