<?php

namespace Miladmodaresi\Taamito\Api;

use Miladmodaresi\Taamito\Base\Model;
use Miladmodaresi\Taamito\Jobs\CategoryJob;
use Miladmodaresi\Taamito\Jobs\ProductJob;
use Miladmodaresi\Taamito\Jobs\VerifyJob;
use Miladmodaresi\Taamito\Model\TaamSync;

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class CronJobs
{
    public function __construct()
    {
    }

    public function init()
    {
        $schedules[TAAMITO_CRON_MINUTS . '_5'] = array(
            'interval' => TAAMITO_CRON_MINUTS * 60,
            'display' => 'Every ' . TAAMITO_CRON_MINUTS . 'minutes'
        );
        return $schedules;
    }
    public function use()
    {
        if (!as_has_scheduled_action('taamito_sync_data')) {
            as_schedule_recurring_action(time(), MINUTE_IN_SECONDS * TAAMITO_CRON_MINUTS, 'taamito_sync_data', [], true);
        }
    }
    public function crons()
    {
        /**
         * @var Model $taamSync
         */
        $taamSync = TaamSync::getInstance();
        // $taamSync = new TaamSync(['name' => 'las_sync', 'status' => 1, 'data' => ['test' => 'testV', 'test2' => 'test2V']]);
        // $taamSync->create(); 
        $taamSyncModel = $taamSync->where('name', 'las_sync')->first();
        if (!$taamSyncModel->exists())
            $taamSyncModel = (new TaamSync(['name' => 'las_sync', 'status' => 1, 'data' => []]))->create();

        $job = new VerifyJob();
        if ($job->isLogin) {
            new CategoryJob($taamSyncModel);
            new ProductJob($taamSyncModel);
            $taamSyncModel->update(['data' => ['last_sync_at' => wp_date("Y-m-d H:i:s")], 'status' => 2]);
        }
    }
    public function cronSchedules()
    {
        if (!isset($schedules["every_minute"])) {
            $schedules["every_minute"] = array(
                'interval' => 1 * 60,
                'display' => __('Every Minute', 'taamito')
            );
        }
        return $schedules;
    }
}
