<?php

namespace frontend\controllers;

use backend\models\CustomerActivateForm;
use frontend\models\SingleCustomerActivateForm;
use common\components\Helper;
use frontend\components\HtmlHelper;
use frontend\models\PasswordChangeModel;
use frontend\models\TowelForm;
use Yii;
use common\models\Customer;
use frontend\models\ReceptionForm;
use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Card;
use frontend\models\CustomerUpdate;
use frontend\models\CustomerCreate;
use common\models\Image;
use common\models\Log;

/**
 * CustomerController implements the CRUD actions for Customer model.
 */
class CustomerController extends Controller
{



    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        		'access' => [
        				'class' => \yii\filters\AccessControl::className(),
        				'only' => ['create', 'update','reception','contract','towel','activate'],
        				'rules' => [
        						    // allow authenticated users
        						    [
        								        'allow' => true,
        								        'roles' => ['@'],
        								    ],
        						    // everything else is denied
        						],
        				],

        ];
    }

    public function actionActivate($number = "")
    {
        $model = new ReceptionForm();
        $model->number = $number;
        $model->readCard();

        $form = new SingleCustomerActivateForm( );
        $form->number = $number;
        $form->validate();
        $ticketsDataProvider = $form->loadTicketsDataProvider();

        if (\Yii::$app->request->isPost && $form->activate()) {
            return $this->redirect(['customer/activate', 'number' => $number]);
        }
        return $this->render('activate', ['model' => $model, 'formModel' => $form, 'ticketsDataProvider' => $ticketsDataProvider]);
    }

	public function actionReception($number = ""){
		$model = new ReceptionForm();

		$model->number = $number;

		$model->readCard();

		if ( $model->defaultAccount && $model->defaultAccount->isLogCardReadInReceptionOn()) {
    	    $model->mkDoorLog();
        }


		if ( $model->isFreeCard() ){
			return $this->redirect([ 'create',  'number' => $model->card->number ]);
		}else if ( $model->isCardWithKey()){
			return $this->redirect([ 'product/sale',  'number' => $model->card->number ]);
		}else if ( $model->isCustomerWithTicket()){
		}else if ( $model->isCardWithCustomer()  ){
			return $this->redirect([ 'ticket/create',  'number' => $model->card->number ]);
		}

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


	public function actionTowel($number = null)
	{
        $model = new TowelForm();
        if ($model->load(Yii::$app->request->post()) ) {
            if (   $model->save() ){
                if ( $model->direction == 'in'){
                    \Yii::$app->session->setFlash ( 'success', 'Törölköző(k) visszaadva!' );
                }else{
                    \Yii::$app->session->setFlash ( 'success', 'Törölköző(k) kiadva!' );
                }
            }else{
                \Yii::$app->session->setFlash ( 'danger', 'Sikertelen törölköző művelet' );
            }
        }
		return $this->redirect(['customer/reception', 'number' => $number ]);


	}

    /**
     * Creates a new Customer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @param null $number      the card number literal
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionCreate($number = null)
    {
    	$model = new CustomerCreate();

        $model->country = "Magyarország";
        $model->id_user = Yii::$app->user->id;
        $model->warn_mail_ticket_expire_enabled = 1;
        $model->newsletter = 0;

        $receptionForm = new ReceptionForm();
        $receptionForm->number = $number;
        $receptionForm->readCard();

        if ( isset($number)){
        	$model->cardNumber = $number;
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	$this->saveBinaryImage($model);
        	\Yii::$app->session->setFlash( 'success','Vendég létrehozva!' );

        	Log::log([
        			'type' =>Log::$TYPE_CREATE_CUSTOMER,
        			'message' => 'Új vendég:' .$model->name,
        			'id_customer' => $model->id_customer
        	]);

            return $this->redirect(['update', 'number' => $model->cardNumber]);
        } else {
            return $this->render('create', [
                'model' => $model,
            	'receptionForm' => $receptionForm
            ]);
        }
    }

    /**
     * Updates an existing Customer model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param null $number
     * @return mixed
     * @throws NotFoundHttpException
     * @internal param int $id
     * @throws \yii\web\HttpException
     */
    public function actionUpdate($number = null)
    {
    	$card = null;

        /** @var \backend\models\CustomerUpdate $model */
        $model = null;

    	$receptionForm = new ReceptionForm();
    	$receptionForm->number = $number;
    	$receptionForm->readCard();

    	if ( $number != null ){
	    	$card = Card::readCard($number);
    		if ( $card != null ){
		    	$model = CustomerUpdate::find()
                    ->innerJoin(Card::tableName(), "customer.id_customer_card = card.id_card")
                    ->andWhere( [ 'customer.id_customer_card' => $card->id_card   ])->one();
    		}
    	}

   	   if ( $model == null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }


        try {
            $model->birthdate = isset($model->birthdate) ? Yii::$app->formatter->asDate($model->birthdate) : '';
        } catch (InvalidConfigException $e) {
    	    \Yii::error("Failed to format date: " . $e->getMessage());
    	    $model->birthdate = '';
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

        	$this->saveBinaryImage($model);


        	\Yii::$app->session->setFlash( 'success','Vendég módosításai elmentve' );

        	$cardNumber = $card->number;
        	if ( isset( $model->replacementCard ) ){
        		$cardNumber = $model->replacementCard->number;
        	}

        	return $this->redirect(['update', 'number' => $cardNumber ]);
        } else {



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


    public function actionPasswordChange($id_card){
        $card = Card::findOne($id_card);
        if ( !isset($card)){
            throw new BadRequestHttpException("card not found");
        }
        $customer = $card->customer;

        if ( !isset($card)){
            throw new BadRequestHttpException("customer not found");
        }


        $model = new PasswordChangeModel();
        $model->card = $card;
        $model->customer = $customer;
        $model->email = $customer->email;
        $model->companyName = Helper::getCompanyName();
        $model->groupTrainingUrl = Helper::getGroupTrainingUrl();

        if ( \Yii::$app->request->isPost  ){
            $model->load(\Yii::$app->request->post());
             if (   $model->changePassword() ){
                 return $this->redirect(['password-change', 'id_card' => $card->id_card ]);
             }

        }

        return $this->render("password-change",[
            'card' => $card,
            'model' => $model
        ]);
    }

    /**
     * Save images as binary data.
     * @param $model \common\models\Customer
     * @throws \yii\web\HttpException
     */
    protected function saveBinaryImage($model) {
    	if ( !empty($model->photo_data)){
    		$encoded_data = $model->photo_data;
    		$binary_data = base64_decode( $encoded_data );
    		// save to server (beware of permissions)
    		$path = \common\components\Image::saveBinary($binary_data,'profile');

    		$image = new Image();
    		$image->path = $path;
    		$image->save();

    		//todo delete old image

    		$model->id_image = $image->id_image;
    		$model->save(false);
    	}
    }

    /**
     * Finds the Customer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Customer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Customer::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
