<?php

namespace frontend\jobs;

use Yii;
use yii\helpers\{Html, Json, FileHelper};
use yii\base\BaseObject;
use yii\httpclient\Client;
use backend\models\{Galleriesbe,Sysmodels, Categoriesbe, Productsbe, Lookuptablebe, Uploadsbe,};

class AttachtoCategory extends BaseObject implements \common\components\Queue\JobInterface
{
    /**
     * Runs Imports from Various Sources.
     *
     * @param [type] $queue
     * @return void
     */
    public function execute($queue)
    {
        $categories = Categoriesbe::find()->select(['id', 'name',])->asArray()->indexby('name')->all();
        foreach (Productsbe::find()->where(['is','imagedata', null])->all() as $key => $model) {
            $importdata = json_decode($model->importdata, 1);
            if (empty($importdata['categories_p']) == false) {
                $cat = $categories[$importdata['categories_p']];
                $lt = Lookuptablebe::find()->where(['sourceid' => $model->id, 'relatedid' => $cat['id']]);
                if ($lt->exists() == false) {
                    $lookup = new Lookuptablebe([
                        'id' => Lookuptablebe::tempid(),
                        'language' => 'en',
                        'source' => 'Products',
                        'sourceid' => $model->id,
                        'related' => 'Category',
                        'relatedid' => $cat['id'],
                        'status' => 'Active',
                        'primaryrecord' => true,

                    ]);
                    $lookup->save();
                }
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function getTtr()
    {
        return 6000;
    }

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