<?php

namespace console\controllers;

//use common\modules\product\models\Brand;
//use common\modules\product\models\BrandName;
use common\modules\product\models\Product;
use common\modules\product\models\ProductVariant;
use common\modules\product\models\RemoteProducts;
use yii\console\Controller;
use yii\helpers\Console;

class ImportController extends Controller {

    public function actionIndex($section) {
        $method = 'go'. ucfirst(strtolower($section));
        if (!method_exists($this, $method)) {
            print $this->stdout("What is $section?\n");
            return Controller::EXIT_CODE_ERROR;
        }

        $this->$method();

        return Controller::EXIT_CODE_NORMAL;
    }

    public function goClear() {
        foreach(Product::find()->all() as $product) {
            if (empty($product->variant)) {
                if (FALSE && !$product->delete()) {
                    $this->stdout("#$product->product_id '$product->name'\n");
                    exit;
                } else {
                    $this->stdout("#$product->product_id '$product->name'\n");
                }
            }
        }
    }

    public function goGo() {
        $new_products = $linked_products = 0;
        foreach(RemoteProducts::find()->all() as $product) {
//            $product->Brand = trim($product->Brand);
            if (empty($product->remoteCategory) || empty($product->remoteCategory->category)) {
                continue;
            }
            if (!empty($product->product))
            {
                $linked_products++;

                $_productVariant = ProductVariant::findOne($product->product->product_variant_id);

                $_product = Product::findOne($product->product->product_id);

//                $brand = Brand::find()->filterWhere(['ilike', 'remote_id', trim($product->Brand)])->one();

                if (
                $_product->name != $product->Name ||
                $_product->categories[0]->category_id != $product->remoteCategory->category->category_id
                /*|| ($product->Brand && $brand !== null && $_product->brand_id != $brand->brand_id)*/
                ) {
                    $_product->name = $product->Name;
                    $_product->categories = [$product->remoteCategory->category->category_id];
                    /*if ( $product->Brand ) {
                        if ( $brand !== null ) {
                            $_product->brand_id = $brand->brand_id;
                        } else {
                            // Create brand
                            $brand = new Brand();
                            $brand->name = $product->Brand;
                            $brand->remote_id = $product->Brand;
                            $brand->save();
                            $_product->brand_id = $brand->brand_id;
                        }
                    }*/
                    $_product->save();
                }

                $price = floatval($product->Price);
                $price_old = floatval($product->Price_old);
                $stock = (bool)$product->In_stock ? NULL : 0;

                if (
                $_productVariant->price != $price ||
                $_productVariant->price_old != $price_old ||
                (!empty($product->Article) && $_productVariant->sku != $product->Article) ||
                $_productVariant->stock !== $stock
                ) {
                    $_productVariant->price = floatval($product->Price);
                    $_productVariant->price_old = floatval($product->Price_old);
                    $_productVariant->sku = empty($product->Article) ? uniqid('gds_') : $product->Article;
                    $_productVariant->stock = $stock;
//                    if (!$_productVariant->price) {
//                        $_productVariant->stock = 0;
//                    }
                    $_productVariant->save();
                }
            }
            elseif (!empty($product->remoteCategory->category->category_id)) {
                $new_products++;

                $_product = new Product();
                $_productVariant = new ProductVariant();
                $_product->name = $product->Name;
                $_product->categories = [$product->remoteCategory->category->category_id];

                /*if ( $product->Brand ) {
                    if ( ($brand = Brand::find()->filterWhere(['ilike', 'remote_id', trim($product->Brand)])->one()) !== null ) {
                        $_product->brand_id = $brand->brand_id;
                    } else {
                        // Create brand
                        $brand = new Brand();
                        $brand->name = trim($product->Brand);
                        $brand->save();
                        $_product->brand_id = $brand->brand_id;
                    }
                }*/
                $_productVariant->price = floatval($product->Price);
                $_productVariant->price_old = floatval($product->Price_old);
                $_productVariant->sku = empty($product->Article) ? uniqid('gds_') : $product->Article;
                $_productVariant->product_unit_id = 1;
                $_productVariant->remote_id = $product->ID;
                $_productVariant->stock = $_productVariant->price > 0 ? null : 0;

                if ($_product->save()) {
                    $_productVariant->product_id = $_product->product_id;
                    if (!$_productVariant->save()) {
                        print $this->stdout("Saved error for variant of the {$_product->name} {$_product->product_id}?\n");
//                    return Controller::EXIT_CODE_ERROR;
                    }

                }
            }
//            $product->delete();
        }

//        $this->goStat();
    }

    public function goStat() {
        $all_products = $new_products = $linked_products = $orpahed_products = 0;
        $remoteProducts = RemoteProducts::find()->all();

        $not_linked_cats = [];

        foreach($remoteProducts as $product) {
            if (!empty($product->product->product_id)) {
                $linked_products++;
            } elseif (!empty($product->remoteCategory) && !empty($product->remoteCategory->category) && !empty($product->remoteCategory->category->category_id)) {
                $new_products++;
            } else {
                if (!empty($product->remoteCategory)) {
                    if (empty($not_linked_cats[$product->remoteCategory->ID])) {
                        $not_linked_cats[$product->remoteCategory->ID] = $product->remoteCategory->Name ." (". $product->remoteCategory->ID .")\n";
                    }
                }
                $orpahed_products++;
            }
            $all_products++;
        }

        $this->stdout("Всего $all_products товаров, $new_products новых и $linked_products уже связанных.\n");
        if (!empty($not_linked_cats)) {
            $this->stdout("$orpahed_products товаров не привязаны к категориям:\n");
            foreach ($not_linked_cats as $not_linked_cat) {
                $this->stdout("$not_linked_cat");
            }
        }
    }

    public function goProducts() {

    }
}