<?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\Json;

class Import_filedata extends BaseObject implements \common\components\Queue\JobInterface
{
    /**
     * @var string $id
     */
    public $id;
    /**
     * @var string $schedule
     */
    public $schedule;
    /**
     * @var float $limit
     */
    public $limit;

    public function execute($queue)
    {
        echo "Starting Data Import" . PHP_EOL;
        //print_r(Yii::$app->Datafile);
        $sysmodel = Sysmodels::findOne(['id' => $this->id]);

        if ($this->schedule == 'auto') {
            $schedule = $sysmodel->options->schedule;
            //print_r($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) {
            $base = Yii::getAlias('@common', $throwException = true);
            echo $sysmodel->sourceurl . PHP_EOL;
            $fullfilepath = $sysmodel->sourceurl;
            $inputFileType = IOFactory::identify($fullfilepath);
            $reader = IOFactory::createReader($inputFileType);
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($fullfilepath);
            $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
            $worksheet = $spreadsheet->getActiveSheet();
            $headings = [];
            $array = [];
            $highestRow = $worksheet->getHighestDataRow(); // e.g. 10
            $highestColumn = $worksheet->getHighestDataColumn(); // e.g 'F'
            $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5
            $row = 1;
            for ($col = 1; $col <= $highestColumnIndex; ++$col) {
                $value = $worksheet->getCell([$col, $row])->getValue();
                $headings[$value] = strtolower(preg_replace('/[^A-Za-z0-9\w]/', '_', $value, -1));
            }

            for ($row = 2; $row <= $highestRow; ++$row) {
                $rowArray = [];
                for ($col = 1; $col <= $highestColumnIndex; ++$col) {
                    $title = (string) $worksheet->getCell([$col, 1])->getValue();
                    $title = strtolower(preg_replace('/[^A-Za-z0-9\w]/', '_', $title, -1));
                    $value = $worksheet->getCell([$col, $row])->getCalculatedValue();
                    $rowArray[$title] = $value;
                }
                $array[] = $rowArray;
            }
            $count = count($array);
            foreach ($array as $key => $model) {
                $r2 = $sysmodel->datamap['relation1'] == 'product_stockcode' ? 'stock_code' : $sysmodel->datamap['relation1'];
                $r1 = $sysmodel->datamap['relation2'];
                $M = $sysmodel->destination;
                $nmodel = new $M();
                if ($sysmodel->options->createcatsfromfield == true) {
                    $field = $sysmodel->options->createcatsfromfieldfield;
                    $category = Categoriesbe::find()->where(['name' => $model[$field]])->one();
                    if (!$category) {
                        $catid = Categoriesbe::Tempid();
                        $category = new Categoriesbe(
                            [
                                'id' => $catid,
                                'language' => 'en',
                                'status' => 'Active',
                                'type' => 'www-level2-category',

                            ]
                        );
                        $category->name = $model[$field];
                        if ($category->save()) {
                            if (empty($sysmodel->options->categoryparent) == false) {
                                $lt = new Lookuptablebe();
                                $lt->source = 'Category';
                                $lt->sourceid = $category->id;
                                $lt->related = 'Categories';
                                $lt->relatedid = $sysmodel->options->categoryparent;
                                $lt->primaryrecord = true;
                                $lt->save();
                            }
                        }

                        $nmodel->categories[] = $catid;
                    } else {
                        $nmodel->categories[] = $category->id;
                    }
                }
                $cms = [];
                foreach ($sysmodel->datamap as $destination => $source) {
                    if ($source !== '' && $destination !== 'relation1' && $destination !== 'relation2') {
                         empty($model[$source]) == false ? $nmodel->$destination = $model[$source] : null;
                        stripos($destination, 'cms_page') !== false && isset($model[$source])
                                ? $cms[] = ['source' => $source, 'content' => $model[$source]]
                                : false;
                    }
                }
                //$nmodel->source = $sysmodel->source;//
               // $nmodel->product_status = $sysmodel->options->importstatus;
                //$nmodel->importdata = Json::encode($model);
                $product = Productsbe::find()->select('id')->Where([$r2 => $model[$r1]])->one();
                if (!$product) {
                    echo 'Creating Product' . PHP_EOL;
                    $id = $nmodel->process();
                    if ($id !== null) {
                        $product = Productsbe::find()->select('id')->Where(['id' => $id])->one();
                        is_array($cms) == true ? $nmodel->cms($product->id, 'en', $cms) : false;
                    } else {
                        echo 'Create failed' . PHP_EOL;
                        print_r($nmodel);
                    }
                } else {
                    print_r($nmodel->update($product->id), 1);
                }
            }
        }
    }

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

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