<?php

namespace frontend\controllers;

use Yii;
use common\models\Collection;
use frontend\models\CollectionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Account;
use common\models\User;
use common\models\CollectionCreate;
use common\models\Transfer;
use frontend\models\CreateAccountSelectForm;
use yii\helpers\ArrayHelper;
use common\models\UserSoldItem;

/**
 * CollectionController implements the CRUD actions for Collection model.
 */
class CollectionController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Collection models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CollectionSearch();
        
        $searchModel->accounts = Account::read();
        $searchModel->accountMap = Account::toAccaountMap($searchModel->accounts);
        
        
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $searchModel->searchTotal();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Collection model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
    	$model = $this->findModel($id);
    	
    	$accounts   = Account::read();
    	$accountMap = Account::toAccaountMap($accounts);
    	
    	$totals = Transfer::mkTotals($model->start, $model->end, $model->id_user, null, $model->id_account, $accounts, $accountMap);
    	
        return $this->render('view', [
            'model' => $model,
        	'totals' => $totals,
        ]);
    }

    /**
     * Creates a new Collection model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($id_account)
    {
        $model = new CollectionCreate();
        
        $user  = User::findOne(Yii::$app->user->id);

        $model->accounts = Account::read();
        $model->lastCollection = Collection::readLast($user);
		$model->id_user = $user->id;
		$model->id_account = $id_account;
		$model->account = Account::readOne($model->id_account);
        $model->accountMap = ArrayHelper::map( $model->accounts ,'id_account','name' );
		
		$model->timestampStart = isset($model->lastCollection) ? $model->lastCollection->end :null; 
		$model->timestampEnd   =  date("Y-m-d H:i:s");
		
		$model->start = isset($model->timestampStart) ? Yii::$app->formatter->asDatetime( $model->timestampStart ,'yyyy-MM-dd HH:mm:ss') : '';
		$model->end = isset($model->timestampEnd) ? Yii::$app->formatter->asDatetime( $model->timestampEnd ,'yyyy-MM-dd HH:mm:ss'): '';
		
		$model->type = Collection::TYPE_RECEPTION;
		
		
		$model->userCartTotal = UserSoldItem::readTotalForAccount($model->id_user, $model->id_account);
		
        if ( $model->load(Yii::$app->request->post()) && $model->save() ) {
            return $this->redirect(['view', 'id' => $model->id_collection]);
        } else {
			$model->totals = Transfer::mkTotals($model->timestampStart, $model->timestampEnd, $model->user->id, null, $model->account->id_account,  $model->accounts, $model->accountMap);
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    /**
     * Select account for which we will create collection
     * If selection is successful, the browser will be redirected to the 'create' page.
     * @return mixed
     */
    public function actionSelectAccount()
    {
        $model = new CreateAccountSelectForm();
        $model->accounts = Account::read();

        $model->id_account = Account::readDefault();
        
          if ($model->load(Yii::$app->request->post()) && $model->validate()) {
          	return $this->redirect(['create', 'id_account' => $model->id_account]);
          }
        
		return $this->render('_create_select_account.php', [
			'model' => $model,
		]);
    }



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