<?php

namespace SEOAIC;

use SeoaicAjaxValidation;

class SEOAIC_CALENDAR
{
    private $seoaic;

    public function __construct($_seoaic)
    {
        $this->seoaic = $_seoaic;
        add_action('wp_ajax_seoaic_get_calendar_draft_posts', [$this, 'get_calendar_draft_posts']);
        add_action('wp_ajax_seoaic_get_calendar_scheduled_posts', [$this, 'get_calendar_scheduled_posts']);
        // add_action('wp_ajax_seoaic_update_calendar_posts', [$this, 'update_calendar_posts']);
    }

    public function get_calendar_draft_posts($return = false, $count = false)
    {

        $query = $this->calendar_posts('draft');
        $html = '';
        if ($count) {
            return count($query);
        }
        $counter = 1;
        foreach ($query as $post) {
            $cluster_name = '<a href="#" class="seoaic-cluster-post-draft green d-none">' . esc_html('cluster name') . '</a>';
            $html .= '<div class="seoaic-dragging-post modal-button post-status--draft seoaic-ajax-submit seoaic-ajax-form" data-modal="#seoaic_calendar-posts-modal" data-title="' . $post['title'] . '" data-id="' . $post['id'] . '" data-status="draft">
                        <span class="number">' . $counter . '</span>
                        <div href="#" class="title"><span class="seoaic_pre_title_id">' . esc_html__('ID:', 'seoaic') . $post['id'] . '</span>' . $post['title'] . '</div>
                        <input type="hidden" name="action" class="seoaic-ajax-field" value="seoaic_load_post_content_to_editor">
                        <input type="hidden" name="post_id" class="seoaic-ajax-field" value="' . $post['id'] . '">
                    </div>';
            $counter++;
        }

        if ($return) {
            return $html;
        }

        wp_send_json(
            [
                'status' => 'success',
                'html' => $html
            ]
        );
    }

    private function calendar_posts($status, $auto_scheduled = false)
    {
        global $wpdb;

        $query = $wpdb->prepare(
            "SELECT p.ID, p.post_title, p.post_date_gmt
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE p.post_status = %s
        AND p.post_type != %s
        AND pm.meta_key = %s
        AND pm.meta_value = %s",
            $status, 'revision', 'seoaic_posted', '1'
        );

        $results = $wpdb->get_results($query);
        $posts = [];

        if (is_array($results)) {
            foreach ($results as $post) {
                $id = $post->ID;

                $get_post = get_post($id);
                $post_type_object = get_post_type_object($get_post->post_type);
                if (!$post_type_object) {
                    continue;
                }

                if ($auto_scheduled !== (bool)get_post_meta($id, 'seoaic_auto_scheduled', true)) {
                    continue;
                }
                $needs_review = get_post_meta($id, 'seoaic_ob_needs_review', true);
                $categories = get_the_category($id);
                $category_name = !empty($categories) ? esc_html($categories[0]->name) : 'Uncategorized';

                $date = gmdate('Y-m-d\TH:i:s\Z', strtotime($post->post_date_gmt));
                $end_date = date('Y-m-d\TH:i:s\Z', strtotime($date) + 60);

                $post = [
                    'title' => esc_html($post->post_title),
                    'start' => $date,
                    'end' => $end_date,
                    'category' => $category_name,
                    'id' => (int)$id,
                    'allDay' => false,
                    'status' => $auto_scheduled ? 'future' : $status,
                ];

                if ($needs_review) {
                    $post['needs_review'] = true;
                }

                $posts[] = $post;
            }
        }

        return $posts;
    }

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

        global $SEOAIC;

        $post = filter_input_array(INPUT_POST, [
            'display_published' => FILTER_VALIDATE_BOOLEAN,
        ]);

        $scheduled = $this->calendar_posts('future');
        $auto_scheduled = $SEOAIC->settings::get_auto_scheduled_posts();
        $all_scheduled = array_merge($scheduled, $auto_scheduled);
        $drafts = $this->calendar_posts('draft');

        $data = [
            'status' => 'success',
            'data' => [
                'scheduled' => $all_scheduled,
                'drafts' => $drafts
            ],
        ];

        if(!empty($post['display_published'])) {
            $data['data']['published'] = $this->calendar_posts('publish');
        }

        wp_send_json($data);
    }

    public function seoai_reschedule_missed_posts()
    {
        global $wpdb;

        $query = "
            UPDATE {$wpdb->posts}
            SET post_status = 'publish'
            WHERE post_status = 'future'
            AND post_date < NOW()
        ";

        $wpdb->query($query);
    }
}