<?php 

namespace modules\custom\jobs;

use backend\models\Mailqueue;
use modules\custom\models\{Assetsbe, Assetsbesearch};
use yii;
use yii\base\BaseObject;
use yii\httpclient\Client;

class ServiceReminders extends BaseObject implements \common\components\Queue\JobInterface
{
    
    /**
     * Send Service Reminders
     *
     * @param [type] $queue
     * @return void
     */
    public function execute($queue)
    {
        $searchModel = new Assetsbesearch();
        $dataProvider = $searchModel->ServiceSearchEmail([], 90, 500);
        $dataProvider->setPagination(false);
        $models =$dataProvider->models;
        $temp = [];
        foreach ($models as $key => $model) {
            $temp[$model->owner->email][] = $model;
        }
        foreach ($temp as $email => $array) {
            if(count($array) == 1){
                $model = $array[0];
                $next = $model->data->next_service;
                $subject = date('Y-m-d') < $next ? 'Service Is Over Due' : 'Service Is Due';
                $send = \backend\models\Mailqueue::find()->where(['to_email' => $email, 'subject' => $subject])->andWhere(['or', ['is', 'date_sent', null], ['>=', 'date_sent', date('Y-m-d', strtotime('-90 days'))]])->exists() ? false : true;
                $send ? $model->ReminderSingle($subject) : false;
            } else {
                $subject = 'Services Are Due';
                $send = true;
                $send = \backend\models\Mailqueue::find()->where(['to_email' => $email, 'subject' => $subject])->andWhere(['or', ['is', 'date_sent', null], ['>=', 'date_sent', date('Y-m-d', strtotime('-90 days'))]])->exists() ? false : true;
                $send ? Assetsbe::reminderMultiple($subject, $email, $array) : false;
            }
        }
        $delay = strtotime('tomorrow 10:30') - time();
        yii::$app->queue->delay($delay)->jobname('Service Reminders')->push(new self());
    }   
	
    /**
     * @inheritdoc
     */
    public function getTtr()
    {
        return 6000;
    }

    /**
     * @inheritdoc
     */
    public function canRetry($attempt, $error)
    {
        return $attempt < 3;
    }
}