<?php 
namespace frontend\jobs;

use yii;
use yii\base\BaseObject;
use yii\httpclient\Client;
use PhpOffice\PhpSpreadsheet\IOFactory;
use backend\models\{Categoriesbe, Galleriesbe, Lookuptablebe, Productsbe, Sysmodels};
use yii\helpers\{ArrayHelper, Json};

class Import_dbdataMissing extends BaseObject implements \common\components\Queue\JobInterface
{

    public $id;
    public $schedule;
    public $limit;
    public $dateOverride;
    
    public static function getIds(){
        return ArrayHelper::map(
            Sysmodels::find()->where(['enabled' => 1])->select(['id', 'destination'])->asArray()->all(), 
            'id', 
            'destination'
        );
    }
    
    public function execute($queue)
    {
		echo "Starting Data Import".PHP_EOL;
        $sysmodel = Sysmodels::findOne(['id' => $this->id]);

        if($this->schedule == 'auto'){
            $schedule = $sysmodel->options->schedule;
            $day = strtolower(Date('l'));
            echo $day.PHP_EOL;
            $start = $day. '_start';
            $finish = $day. '_finish';
            $interval = $day. '_repeat';
            echo $schedule[$start] .PHP_EOL;
            if(date('H:i') <= $schedule[$finish] ){
                $delay = $schedule[$interval] * 60;
                Echo $delay;
                $runnow = true;
                Yii::$app->queue
                    ->jobname('DataImport '. $sysmodel->destination)
                    ->relatedid($this->id)
                    ->delay($delay)
                    ->ttr(7200)
                    ->push(new self(['id' => $this->id, 'schedule' => 'auto']));
            } else {
                $runnow = false;
                $tomorrow = strtolower(date('l', strtotime('tomorrow')));
                $start = Date('Y-m-d ', strtotime('tomorrow')) . $schedule[$tomorrow. '_start'];
                echo $start.PHP_EOL;
                $delay = strtotime($tomorrow) - strtotime('now');
                echo $delay.PHP_EOL;
                Yii::$app->queue
                    ->jobname('DataImport '. $sysmodel->destination)
                    ->relatedid($this->id)
                    ->delay($delay)
                    ->ttr(7200)
                    ->push(new self(['id' => $this->id, 'schedule' => 'auto']));
            }
        } else {
            $runnow = true;
        }
        if($runnow == true){
            echo 'Model Copy'.PHP_EOL;
            echo  $sysmodel->destination.PHP_EOL;
            $class = $sysmodel->destination;
            $models = $class::Missing($sysmodel->source::find(), $sysmodel);
            Echo $models->createCommand()->getRawSql().PHP_EOL;
            echo 'Found: '. $models->count().PHP_EOL;
            $class = $sysmodel->destination ;
            foreach ($models->each() as $key => $model) {
                
                $r2 = match($sysmodel->datamap['relation1']){
                    'product_stockcode'  => 'stock_code',
                    'product_sourceid' =>'product_id',
                    default => $sysmodel->datamap['relation1'],
                };
                $r1 = $sysmodel->datamap['relation2'];
                if ($r2 == 'erpid' && in_array($class::datatype, ['CreditInvoice', 'AdhocInvoice',  'WashroomInvoice', 'ServiceInvoice', 'Invoice', 'Payment', 'Order']) && method_exists($class, 'getErpkey') ){
                    $concat = $model->_ID . $model->ACCOUNT . $model->TxREF . $model->TxDATE;
                    $nmodel = $class::find()
                        ->where(['type' => $class::datatype, 'indexes_erpkey' => $concat])
                        ->one();
                    
                } elseif ($r2 == 'erpid' && in_array($class::datatype, ['CreditInvoice', 'AdhocInvoice',  'WashroomInvoice', 'ServiceInvoice', 'Invoice', 'Payment', 'Order']) && !method_exists($class, 'getErpkey') ){
                    $nmodel = $class::find()->where(['type' => $class::datatype, 'indexes_erpid' => trim($model[$r1])])->one();
                } else {
                    $nmodel = $class::find()->where([$r2 => trim($model[$r1])])->one();
                }
                if (!$nmodel) {
                    $nmodeldiff = $class::find()
                        ->where(['type' => $class::datatype, 'indexes_erpid' => trim($model[$r1])])
                        ->one();
                    if($nmodeldiff && ($nmodeldiffData = $nmodeldiff->data) && (
                            $nmodeldiffData->_ID !== $model->_ID ||$nmodeldiffData->ACCOUNT !== $model->ACCOUNT || $nmodeldiffData->TxREF !== $model->TxREF || $nmodeldiffData->TxDATE !== $model->TxDATE 
                        )){
                        $nmodeldiff->delete();
                    }
                    
                    
                    echo $class::import($model, $sysmodel->datamap);
                } 
            }
        }
    }
	
    /**
     * @inheritdoc
     */
    public function getTtr()
    {
        return 6000;
    }

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