<?php

namespace OtomaticAi\Jobs;

use OtomaticAi\Utils\Scheduler;
use OtomaticAi\Vendors\Carbon\Carbon;

class DeleteOldScheduleJob extends Job
{
    private int $days = 7;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        global $wpdb;

        $date = Carbon::now()->subDays($this->days);

        $keys = ["run_autopilot_job", "check_publications_to_publish", "process_failed_shedules", "delete_old_schedules"];

        foreach ($keys as $key) {

            $actions = Scheduler::get(
                $key,
                [],
                [
                    "date" => $date,
                    "date_compare" => "<=",
                    "per_page" => 1000,
                ],
                "ids"
            );

            if (count($actions) > 0) {

                $actionsTableName = $wpdb->prefix . 'actionscheduler_actions';
                $logsTableName = $wpdb->prefix . 'actionscheduler_logs';

                $logsQuery = "DELETE FROM `" . $logsTableName . "` WHERE `action_id` IN(" . implode(",", $actions) . ")";
                $actionsQuery = "DELETE FROM `" . $actionsTableName . "` WHERE `action_id` IN(" . implode(",", $actions) . ")";

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