<?php

namespace backend\controllers;

use Yii;
use common\models\Collection;
use backend\models\CollectionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Account;
use common\models\Transfer;
use common\models\User;

/**
 * CollectionController implements the CRUD actions for Collection model.
 */
class CollectionController extends \backend\controllers\BackendController
{

	
	public function behaviors()
	{
		return [
			'access' => [
				'class' => \yii\filters\AccessControl::className(),
				'rules' => [
					// allow authenticated users
					[
					'actions' => [ 'index','view' ],
					'allow' => true,
					'roles' => ['@'],
					],
					// everything else is denied
				],
			],
		];
	}
	
    /**
     * Lists all Collection models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CollectionSearch();
        $searchModel->accounts = Account::read();
        $searchModel->accountMap = Account::toAccaountMap($searchModel->accounts);
        
        $searchModel->users = User::read();
        
        $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,
        ]);
    }

    
    /**
     * 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.');
        }
    }
}
