<?php

namespace console\controllers;

use common\modules\product\models\Category;
use common\modules\product\models\Import;
use common\modules\product\models\ProductImage;
use common\modules\product\models\ProductVariantType;
use common\modules\product\models\Stock;
use common\modules\rubrication\models\TaxOption;
use common\modules\rubrication\models\TaxValueString;
use Yii;
use common\modules\product\models\Brand;
use common\modules\product\models\Product;
use common\modules\product\models\ProductVariant;
use yii\console\Controller;
use yii\helpers\Console;

class ImportController extends Controller {
    public $errors = [];


    public function actionImages(){
        $files = ProductImage::find()->all();
        foreach($files as $file_object){
            $file = $file_object->image;
            $file_array = explode('/',$file);
            if(is_array($file_array) && count($file_array) >3){
                $count = count($file_array);
                $file_name = $file_array[$count-2]."_".$file_array[$count-1];
                print_r($file_name);
                $save_image = Yii::getAlias('@productsDir') . "/" . $file_name;
                copy($file, $save_image);
                $file_object->image = $file_name;
                $file_object->save();
            }

        }


    }

    private function getProductsFile($file_type = 'uploadFileProducts') {
        $filename = Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@'. $file_type);
        if (!is_file($filename)) {
            $this->stderr('Task already executed');
            return Controller::EXIT_CODE_ERROR;
        }
        return fopen ($filename, 'r');
    }

    public function actionProducts() {
        if (file_exists(Yii::getAlias('@uploadDir/goProducts.lock'))) {
            $this->errors[] = 'Task already executed';
            return Controller::EXIT_CODE_ERROR;
        }
        $ff = fopen(Yii::getAlias('@uploadDir/goProducts.lock'), 'w+');
        fclose($ff);
        $model = new Import();
        $model->goProducts(0, null);
        unlink(Yii::getAlias('@uploadDir/goProducts.lock'));
        return Controller::EXIT_CODE_NORMAL;
    }

    public function actionPrices() {
        if (file_exists(Yii::getAlias('@uploadDir/goPrices.lock'))) {
            $this->stderr('Task already executed');
            return Controller::EXIT_CODE_ERROR;
        }
        $ff = fopen(Yii::getAlias('@uploadDir/goPrices.lock'), 'w+');
        fclose($ff);
        $model = new Import();
        $data = $model->goPrices(0, null);
        unlink(Yii::getAlias('@uploadDir/goPrices.lock'));
        return Controller::EXIT_CODE_NORMAL;
    }

    private function saveNotFoundRecord (array $line, $filename)
    {
        $str = implode (';', $line)."\n";
        $str = iconv ("UTF-8//TRANSLIT//IGNORE", "windows-1251", $str);

        $fg = fopen (Yii::getAlias('@uploadDir') .'/'. $filename, 'a+');
        fputs ($fg, $str);
        fclose ($fg);
    }
}