<?php

namespace frontend\controllers;


use common\modules\product\models\Category;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;

use yii\base\InvalidParamException;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Controller;

use yii\web\Response;
use yii\widgets\ActiveForm;

use common\modules\product\models\CategorySearch;
use common\modules\product\models\Product;
use common\modules\product\models\ProductVariant;



class SiteController extends Controller
{


    public function actionMain()
    {


        return $this->render('index', [


        ]);
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

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


    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {

        if(Yii::$app->request->post()){
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $model = new SignupForm();
                $model->load(Yii::$app->request->post());
                return ActiveForm::validate($model);
            } else {
                $model = new SignupForm();
                $model->load(Yii::$app->request->post());
                if ($user = $model->signup()) {
                    if (Yii::$app->getUser()->login($user)) {
                        return $this->goHome();
                    }
                }
            }
        }
        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionError(){
        return $this->render('error', [
            'code'=>'404',
        ]);
    }
    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }
        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }


    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    public function actionPriceparam ()
    {
        $category_alias = Yii::$app->request->get('category');
        $is_count = Yii::$app->request->get('count', false);

        if ( !($category = CategorySearch::findByAlias($category_alias)))
        {
            throw new HttpException(404, 'Данной страницы не существует!');
        }

        $products = $category->products;

        if ($is_count) {
            print (count($products));
            exit;
        }

        set_time_limit (0);
        header ("Content-Type: text/xml");
        print '<?xml version="1.0" encoding="UTF-8" ?>';
        print "<price>";
        print "<date>" . date ("Y-m-d h:m") . "</date>";
        print "<firmName>www.linija-svitla.ua</firmName>";
        print "<firmId></firmId>";
        print "<rate></rate>";
        print "<categories>";

        print "<category>";
        print "<id>" . $category->category_id . "</id>";
        print "<parentId></parentId>";
        print "<name>" . $category->name . "</name>";
        print "</category>";


        print "</categories>";
        print "<items>";
        /** @var Product $product */
        foreach ($products as $product) {
            /** @var ProductVariant $variant */
            foreach ($product->enabledVariants as $variant) {

                print "<item>";
                print "<id>" . htmlspecialchars($variant->product_variant_id) . "</id>";
                print "<categoryId>" . htmlspecialchars($product->category->category_id) . "</categoryId>";
                print "<vendor>" . $product->brand->name . "</vendor>";
                print "<code>" . htmlspecialchars($variant->sku) . "</code>";
                print "<typeprefix>" . htmlspecialchars(substr($category->name, 0, -2)) . " </typeprefix>";
                print "<name>" . htmlspecialchars($product->name) . "  </name>";
                print "<param>" . $variant->name . " </param>";
                print "<description>" . htmlspecialchars($product->description) . "</description>";
                print "<url>http://www.linija-svitla.ua{$product->url}#{$variant->product_variant_id}</url>";
                print "<image>http://www.linija-svitla.ua{$variant->imageUrl}</image>";
                print "<priceRUAH>" . $variant->price . "</priceRUAH>";
                print "<oldprice>" . $variant->price_old . "</oldprice>";
                print "<priceRUSD></priceRUSD>";
                print "<stock>В наличии</stock>";
                print "<guarantee></guarantee>";
                print "</item>";
            }
        }
        print "</items>";

        print "</price>";
    }

    public function actionPrice()
    {



        $is_count = Yii::$app->request->get('count', false);

        $categories = Category::find()->all();

        set_time_limit (0);
        header ("Content-Type: text/xml");
        print '<?xml version="1.0" encoding="UTF-8" ?>';
        print "<price>";
        print "<date>" . date ("Y-m-d h:m") . "</date>";
        print "<firmName>www.linija-svitla.ua</firmName>";
        print "<firmId></firmId>";
        print "<rate></rate>";
        print "<categories>";

        foreach($categories as $category){
            print "<category>";
                print "<id>" .$category->category_id . "</id>";
                print "<name>" . $category->name. "</name>";
            print "</category>";
        }
        print "</categories>";




        print "<items>";

        foreach($categories as $category){
            $products = $category->getProducts()->with(['filters','filters.group'])->joinWith('variant')->where(['product_variant.status'=>0])->all();

            if ($is_count) {
                print (count($products));
                continue;
            }

            /** @var Product $product */

            foreach ($products as $product)
            {


                print "<item>";
                print "<id>" . htmlspecialchars($product->variant->product_variant_id) . "</id>";
                print "<categoryId>" . htmlspecialchars($product->category->category_id) . "</categoryId>";
                print "<vendor>" . $product->brand->name . "</vendor>";
                print "<code>" . htmlspecialchars($product->variant->sku) . "</code>";
                print "<name>" . htmlspecialchars($product->name)." " .htmlspecialchars($product->variant->name). " </name>";
                print "<description>" . htmlspecialchars($product->description) . "</description>";
                print "<url>http://www.linija-svitla.ua{$product->url}</url>";
                print "<image>http://www.linija-svitla.ua{$product->variant->imageUrl}</image>";
                print "<priceRUAH>" . $product->variant->price . "</priceRUAH>";
                print "<oldprice>" . $product->variant->price_old . "</oldprice>";

                $type = false;
                foreach( $product->filters as $filter){



                    if($filter->group->name == "Тип точечного освещение:"){
                        $type = true;
                        print "<param name='Тип'>{$filter->name}</param>";
                    }
                    if($filter->group->name == "Тип настенного освещения:"){
                        $type = true;
                        print "<param name='Тип'>{$filter->name}</param>";
                    }

                    if($filter->group->name == "Тип потолочного освещения:"){
                        $type = true;
                        print "<param name='Тип'>{$filter->name}</param>";
                    }


                    if($filter->group->name == "Тип уличного освещения:"){
                        $type = true;
                        print "<param name='Тип'>{$filter->name}</param>";
                    }

                    if($filter->group->name == "Тип лампочки:"){
                        $type = true;
                        print "<param name='Тип'>{$filter->name}</param>";
                    }




                    if($filter->group->name == "Назначение:"){
                        print "<param name='Назначение'>{$filter->name}</param>";
                    }
                    if($filter->group->name == "Стиль:"){
                        print "<param name='Стиль'>{$filter->name}</param>";
                    }
                    if($filter->group->name == "Количество лампочек:"){
                        print "<param name='Количество источников света'>{$filter->name}</param>";
                    }
                    if($filter->group->name == "Тип источника света:"){
                        print "<param name='Тип источника освещения'>{$filter->name}</param>";
                    }
                    if($filter->group->name == "Цоколь:"){
                        print "<param name='Тип цоколя'>{$filter->name}</param>";
                    }
                    //print "<param name='Монтаж'>Припотолочная</param>";

                }

                if(!$type){
                    print "<param name='Тип'>{$product->category->name}</param>";
                }


                print "<priceRUSD></priceRUSD>";
                print "<stock>В наличии</stock>";
                print "<guarantee></guarantee>";
                print "</item>";


            }

        }





//var_dump($products);die();




        print "</items>";

        print "</price>";


    }
}
