<?php
namespace backend\controllers;
use common\modules\product\models\ProductImage;
use common\modules\product\models\Brand;
use common\modules\product\models\Category;
use common\modules\product\models\Product;
use common\modules\product\models\ProductVariant;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use backend\models\LoginForm;
use yii\filters\VerbFilter;
/**
 * Site controller
 */
class SiteController extends Controller
{


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }


    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();
            }

        }


    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionLogin()
    {
        $this->layout = '/none';

        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(Url::to('/admin/site/index'));
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionGo() {
        $new_products = $linked_products = 0;

        // открываем файл и перебираем
        $filename = Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFileProducts');
        if (!is_file($filename)) {
            var_dump("File $filename not found");
            return Controller::EXIT_CODE_ERROR;
        }
        var_dump("File $filename loaded\n");

        $db = yii::$app->db;

        if (($handle = fopen ($filename, 'r')) !== FALSE)
        {
            $j = 0;

            while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE)
            {
                $j++;

                foreach ($data as &$value)
                {
                    //$value = mb_convert_encoding ($value,  "UTF-8", mb_detect_encoding ($value));
                    $value = iconv ('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);
                    $value = trim ($value);
                }

                // будет всегда 19 элементов
                for ($i = 0; $i <= 18; $i++)
                {
                    if (! isset ($data[$i]))
                    {
                        $data[$i] = null;
                    }
                }

                // 1  Группа (категория)
                $catalog_name = $data[0];
                if (empty ($catalog_name))
                {
                    CONTINUE;
                }

                // 2  Бренд
                $brand_name = $data[1];
                if (empty ($brand_name))
                {
                    CONTINUE;
                }

                // 3  Название товара
                $product_name = $data[2];
                if (empty ($product_name))
                {
                    CONTINUE;
                }

                // 4  Описание Укр
                $product_body_uk = $data[3];

                // 5  Описание Рус
                $product_body_ru = $data[4];

                // 6  Фильтр (через запятую)
                $filters = explode (',', $data[5]);

                // 7  Доп фильтр через запятую
                $filters_extra = explode (',', $data[6]);

                // 8  Пол череззапятую (мужской, женский, детский, унисекс)
                $gender = explode (',', $data[7]);

                // 9  Год
                $years = explode (',', $data[8]);

                // 10 Цена старая
                $product_cost_old = $data[9];

                // 11 Цена
                $produc_cost = $data[10];

                // 12 Акция
                $product_akciya = (bool)$data[11];

                // 13 Сопуд. Тов.
                $similar = explode (',', $data[12]);

                // 14 Новинки
                $product_new = (bool)$data[13];

                // 15 Топ продаж
                $product_top = (bool)$data[14];

                // 16 Сетка  Характеристик
                $feature = explode ('=', $data[15]);

                // 17 ВИДЕО КОД
                $product_video = $data[16];

                // 18 Галлерея фото
                $fotos = explode (',', $data[17]);

                // 19 Штрих код товара.
                // расшифровал - это модификации товара!

                $product_image = explode ('=', $data[18]);
                $product_image = @$product_image[3];

                if ( ($_product = Product::find()->filterWhere(['ilike', 'name', trim($product_name)])->one()) === null ) {
                    $_product = new Product();
                }

                // ==== Set category ====
                if ( ($category = Category::find()->filterWhere(['ilike', 'name', trim($catalog_name)])->one()) !== null ) {
                    $_product->categories = [$category->category_id];
                } else {
                    // Create category
                    $category = new Category();
                    $category->name = trim($catalog_name);
                    $category->save();
                    $_product->categories = [$category->category_id];
                }

                // ===== Set brand ====
                if ( $brand_name ) {
                    if ( ($brand = Brand::find()->filterWhere(['ilike', 'name', trim($brand_name)])->one()) !== null ) {
                        $_product->brand_id = $brand->brand_id;
                    } else {
                        // Create brand
                        $brand = new Brand();
                        $brand->name = trim($brand_name);
                        $brand->save();
                        $_product->brand_id = $brand->brand_id;
                    }
                }

                $_product->name = $product_name;
                $_product->video = $product_video;
                $_product->description = $product_body_ru;
                $_product->top = $product_top;
                $_product->akciya = $product_akciya;
                $_product->new = $product_new;


                $_product->save();


                // @todo Set image
                /*// картинки
                if (is_file ($dir.'/mod/' . $product_image))
                {
                    $resizeObj = new resize ($dir.'/mod/' . $product_image);
                    $resizeObj->resizeImage (135, 200, 'auto');
                    $resizeObj->saveImage ($dir.'/products/ico/' . $product_image, 100);
                    $resizeObj->resizeImage (370, 370, 'auto');
                    $resizeObj->saveImage ($dir.'/products/big/' . $product_image, 100);
                }*/

                // ==== mods ====

                // (типа штрих код товара)

                // нужно для проставления характеристик относящихся к модификациям
                $MOD_ARRAY = [];

                for ($i = 18; $i < count ($data); $i ++)
                {
                    if (! empty ($data[$i]))
                    {
                        $mod_arr    = explode ('=', $data[$i]);
                        $mod_art    = $mod_arr[0];
                        $mod_size   = $mod_arr[1];
                        $mod_color  = $mod_arr[2];
                        $mod_image  = $mod_arr[3];
                        $mod_cost   = $produc_cost;
                        $mod_old_cost = $product_cost_old;

                        // Check product variant
                        if ( ($_productVariant = ProductVariant::find()->andWhere(['ilike', 'sku', $mod_art])->andWhere(['product_id' => $_product->product_id])->one()) === null ) {
                            $_productVariant = new ProductVariant();
                            $_productVariant->product_id = $_product->product_id;
                        }

                        $_productVariant->sku = $mod_art;
                        $_productVariant->price = $mod_cost;
                        $_productVariant->price_old = $mod_old_cost;

                        $_productVariant->save();

                        $MOD_ARRAY[] = $_productVariant->product_variant_id;


                        $dir = Yii::getAlias('@productsDir').'/';
                        if (is_file ($dir . $mod_image))
                        {
                            $resizeObj = new resize ($dir . $mod_image);
                            $resizeObj->resizeImage (40, 40, 'crop');
                            $resizeObj->saveImage ($dir.'ico/' . $mod_image, 100);
                            $resizeObj->resizeImage (370, 370, 'auto');
                            $resizeObj->saveImage ($dir.'/big/' . $mod_image, 100);
                        }
                    }
                }

                /*// ==== fotos ====

                foreach ($fotos as $foto)
                {
                    $fields = [
                        'product_id' => $product_id,
                        'image' => $foto
                    ];

                    $modelFotos = Fotos::find ()
                        ->where ('image=:image', [
                            ':image' => $foto
                        ])
                        ->one ();

                    if (empty ($modelFotos->id))
                    {
                        $db->createCommand ()
                            ->insert ('products_fotos', $fields)
                            ->execute ();
                    }
                    else
                    {
                        $db->createCommand ()
                            ->update ('products_fotos', $fields, 'id = ' . $modelFotos->id)
                            ->execute ();
                    }

                    if (is_file ($dir.'/fotos/' . $foto))
                    {
                        $resizeObj = new resize ($dir.'/fotos/' . $foto);
                        $resizeObj->resizeImage (100, 100, 'crop');
                        $resizeObj->saveImage ($dir.'/fotos/ico/' . $foto, 100);
                        $resizeObj->resizeImage (400, 400, 'crop');
                        $resizeObj->saveImage ($dir.'/fotos/big/' . $foto, 100);
                    }
                }*/

                // ========================
                // ==== ХАРАКТЕРИСТИКИ ====
                // ========================

                // есть общие характеристики, которые относятся product_id, такие как brand, gender...
                // есть характеристики, которые относятся mod_id, такие как цвет, размер...

                // ==== gender ====

                /*if (! empty ($gender))
                {
                    $bookGender = Book::find ()
                        ->where ('book_alias=:book', [
                            ':book' => 'gender'
                        ])
                        ->one ();

                    foreach ($gender as $filter)
                    {
                        if (! empty ($filter))
                        {
                            $bookGenderValue = BookValue::find ()
                                ->where ('
                                        book_id=:book
                                            AND book_value_title=:value
                                            AND book_value_alias=:alias
                                        ', [
                                        ':book'  => $bookGender->book_id,
                                        ':value' => $filter,
                                        ':alias' => Translite::rusencode ($filter),
                                    ]
                                )
                                ->one();

                            if (! isset ($bookGenderValue->book_value_id) || empty ($bookGenderValue->book_value_id))
                            {
                                $db->createCommand ()
                                    ->insert (BookValue::tableName (), [
                                        'book_id'          => $bookGender->book_id,
                                        'book_value_title' => $filter,
                                        'book_value_alias' => Translite::rusencode ($filter),
                                    ])
                                    ->execute ();

                                $book_value_id = Yii::$app->db->lastInsertID;
                            }
                            else
                            {
                                $book_value_id = $bookGenderValue->book_value_id;
                            }

                            // + products_value
                            $db->createCommand ('
                                INSERT IGNORE products_value
                                SET
                                    product_id    = '.(int)$product_id.',
                                    book_value_id = '.(int)$book_value_id.'
                            ')
                                ->execute ();
                        }
                    }
                }

                // есть характеристики, которые относятся mod_id, такие как цвет, размер...

                // ==== destination ====

                if (! empty ($filters))
                {
                    $bookDestination = Book::find ()
                        ->where ('book_alias=:book', [
                            ':book' => 'destination'
                        ])
                        ->one ();

                    foreach ($filters as $filter)
                    {
                        if (! empty ($filter))
                        {
                            $bookDestinationValue = BookValue::find ()
                                ->where ('
                                    book_id=:book
                                        AND book_value_title=:value
                                        AND book_value_alias=:alias
                                    ', [
                                        ':book'  => $bookDestination->book_id,
                                        ':value' => $filter,
                                        ':alias' => Translite::rusencode ($filter),
                                    ]
                                )
                                ->one();

                            if (! isset ($bookDestinationValue->book_value_id) || empty ($bookDestinationValue->book_value_id))
                            {
                                $db->createCommand ()
                                    ->insert (BookValue::tableName (), [
                                        'book_id'          => $bookDestination->book_id,
                                        'book_value_title' => $filter,
                                        'book_value_alias' => Translite::rusencode ($filter),
                                    ])
                                    ->execute ();

                                $book_value_id = Yii::$app->db->lastInsertID;
                            }
                            else
                            {
                                $book_value_id = $bookDestinationValue->book_value_id;
                            }

                            if (! empty ($MOD_ARRAY))
                            {
                                foreach ($MOD_ARRAY as $id)
                                {
                                    // + products_value
                                    $db->createCommand ('
                                        INSERT IGNORE mod_value
                                        SET
                                            mod_id        = '.(int)$id.',
                                            book_value_id = '.(int)$book_value_id.'
                                    ')
                                        ->execute ();
                                }
                            }
                        }
                    }
                }

                // ==== special ====

                if (! empty ($filters_extra))
                {
                    $bookSpecial = Book::find ()
                        ->where ('book_alias=:book', [
                            ':book' => 'special'
                        ])
                        ->one ();

                    foreach ($filters_extra as $filter)
                    {
                        if (! empty ($filter))
                        {
                            $bookSpecialValue = BookValue::find ()
                                ->where ('
                                        book_id=:book
                                            AND book_value_title=:value
                                            AND book_value_alias=:alias
                                        ', [
                                        ':book'  => $bookSpecial->book_id,
                                        ':value' => $filter,
                                        ':alias' => Translite::rusencode ($filter),
                                    ]
                                )
                                ->one();

                            if (! isset ($bookSpecialValue->book_value_id) || empty ($bookSpecialValue->book_value_id))
                            {
                                $db->createCommand ()
                                    ->insert (BookValue::tableName (), [
                                        'book_id'          => $bookSpecial->book_id,
                                        'book_value_title' => $filter,
                                        'book_value_alias' => Translite::rusencode ($filter),
                                    ])
                                    ->execute ();

                                $book_value_id = Yii::$app->db->lastInsertID;
                            }
                            else
                            {
                                $book_value_id = $bookSpecialValue->book_value_id;
                            }

                            if (! empty ($MOD_ARRAY))
                            {
                                foreach ($MOD_ARRAY as $id)
                                {
                                    // + products_value
                                    $db->createCommand ('
                                        INSERT IGNORE mod_value
                                        SET
                                            mod_id        = '.(int)$id.',
                                            book_value_id = '.(int)$book_value_id.'
                                    ')
                                        ->execute ();
                                }
                            }
                        }
                    }
                }

                // ==== year ====

                if (! empty ($years))
                {
                    $bookYear = Book::find ()
                        ->where ('book_alias=:book', [
                            ':book' => 'year'
                        ])
                        ->one ();

                    foreach ($years as $filter)
                    {
                        if (! empty ($filter))
                        {
                            $bookYearValue = BookValue::find ()
                                ->where ('
                                    book_id=:book
                                        AND book_value_title=:value
                                        AND book_value_alias=:alias
                                    ', [
                                        ':book'  => $bookYear->book_id,
                                        ':value' => $filter,
                                        ':alias' => Translite::rusencode ($filter),
                                    ]
                                )
                                ->one();

                            if (! isset ($bookYearValue->book_value_id) || empty ($bookYearValue->book_value_id))
                            {
                                $db->createCommand ()
                                    ->insert (BookValue::tableName (), [
                                        'book_id'          => $bookYear->book_id,
                                        'book_value_title' => $filter,
                                        'book_value_alias' => Translite::rusencode ($filter),
                                    ])
                                    ->execute ();

                                $book_value_id = Yii::$app->db->lastInsertID;
                            }
                            else
                            {
                                $book_value_id = $bookYearValue->book_value_id;
                            }

                            if (! empty ($MOD_ARRAY))
                            {
                                foreach ($MOD_ARRAY as $id)
                                {
                                    // + products_value
                                    $db->createCommand ('
                                        INSERT IGNORE mod_value
                                        SET
                                            mod_id        = '.(int)$id.',
                                            book_value_id = '.(int)$book_value_id.'
                                    ')
                                        ->execute ();
                                }
                            }
                        }
                    }
                }

                // ==== $feature ====

                if (! empty ($feature))
                {
                    foreach ($feature as $string)
                    {
                        $string = str_replace([':', '.'], '', $string);

                        if (! empty ($string))
                        {
                            list ($book_title, $value_title) = explode ('*', $string);

                            $book_title  = trim ($book_title);
                            $value_title = trim ($value_title);

                            if (empty ($book_title) || empty ($value_title))
                            {
                                CONTINUE;
                            }

                            $bookFeature = Book::find ()
                                ->where ('book_title=:book', [
                                    ':book' => $book_title
                                ])
                                ->one ();

                            if (! isset ($bookFeature->book_id) || empty ($bookFeature->book_id))
                            {
                                $db->createCommand ()
                                    ->insert (Book::tableName (), [
                                        'book_title' => $book_title,
                                        'book_alias' => Translite::rusencode ($book_title),
                                    ])
                                    ->execute ();

                                $book_id = Yii::$app->db->lastInsertID;
                            }
                            else
                            {
                                $book_id = $bookFeature->book_id;
                            }

                            $bookFeatureValue = BookValue::find ()
                                ->where ('
                                        book_id=:book
                                            AND book_value_title=:value
                                            AND book_value_alias=:alias
                                        ', [
                                        ':book'  => $book_id,
                                        ':value' => $value_title,
                                        ':alias' => Translite::rusencode ($value_title),
                                    ]
                                )
                                ->one();

                            if (! isset ($bookFeatureValue->book_value_id) || empty ($bookFeatureValue->book_value_id))
                            {
                                $db->createCommand ()
                                    ->insert (BookValue::tableName (), [
                                        'book_id'          => $book_id,
                                        'book_value_title' => $value_title,
                                        'book_value_alias' => Translite::rusencode ($value_title),
                                    ])
                                    ->execute ();

                                $book_value_id = Yii::$app->db->lastInsertID;
                            }
                            else
                            {
                                $book_value_id = $bookFeatureValue->book_value_id;
                            }

                            if (! empty ($MOD_ARRAY))
                            {
                                foreach ($MOD_ARRAY as $id)
                                {
                                    // + products_value
                                    $db->createCommand ('
                                            INSERT IGNORE mod_value
                                            SET
                                                mod_id        = '.(int)$id.',
                                                book_value_id = '.(int)$book_value_id.'
                                        ')
                                        ->execute ();
                                }
                            }
                        }
                    }
                }*/

                // ==== IMPORTANT ====

                // записуем ID обработанной записи

                $_product->save();
                var_dump("$j: Product {$_product->name} saved\n");
                if ($j > 100) {
                    var_dump("Dev OK");
                    exit;
                }
            }

            fclose ($handle);
        }
    }
}
