<?php

namespace backend\controllers;

use backend\models\TeamSkils;
use backend\models\TeamBooks;
use Yii;
use backend\models\Team;
use backend\models\TeamSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\helpers\Html;
use yii\helpers\Url;
use pavlinter\multifields\ModelHelper;
use yii\web\Response;
use yii\helpers\ArrayHelper;

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

    /**
     * Lists all Team models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TeamSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Team model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Team model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Team();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
	        $this->_uploadFile($model, 'file', 'photo', 'team');
	        $this->_uploadFile($model, 'file2', 'photo_big', 'team/big');
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Team model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

	    // Get skills
	    $skills = TeamSkils::find()->where(['team_id' => $id])->indexBy('id')->all();
	    if (empty($skills)) {
		    $skills[] = new TeamSkils(['scenario' => 'multiFields']);
	    } else {
		    foreach ($skills as &$skill) {
			    $skill->scenario = 'multiFields';
		    }
	    }

	    // Get books
	    $books = TeamBooks::find()->where(['team_id' => $id])->indexBy('id')->all();
	    if (empty($books)) {
		    $books[] = new TeamBooks(['scenario' => 'multiFields']);
	    } else {
		    foreach ($books as &$book) {
			    $book->scenario = 'multiFields';
		    }
	    }
	    
	    
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
	        $this->_uploadFile($model, 'file', 'photo', 'team');
	        $this->_uploadFile($model, 'file2', 'photo_big', 'team/big');

	        $this->_updateSkills($model, Yii::$app->request->post('TeamSkils'), $skills);
	        $this->_updateBooks($model, Yii::$app->request->post('TeamBooks'), $books);

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
	            'skills' => $skills,
	            'books' => $books,
            ]);
        }
    }

	private function _updateSkills($model, $post = [], $exists = []) {
		$exists_ids = [];
		foreach ( $exists as $row ) {
			if ($row->id > 0)
				$exists_ids[$row->id] = $row->id;
		}

		foreach ($post as $id => $data) {
			if ($id > 0 && in_array($id, $exists_ids)) {
				unset($exists_ids[$id]);
				// Exists row
				$modelRow = TeamSkils::findOne($id);
				if ($modelRow) {
					$dataArray = [
						'TeamSkils' => [
							'title' => $data['title'],
							'value' => floatval(str_replace([',', ' '], ['.', ''], trim($data['value'])))
						]
					];
					$modelRow->load( $dataArray );
					$modelRow->save();
				}
			} else {
				// New row
				if (empty($data['title'])) continue;

				$modelRow = new TeamSkils();
				$dataArray = [
					'TeamSkils' => [
						'team_id' => $model->id,
						'title' => $data['title'],
						'value' => floatval(str_replace([',', ' '], ['.', ''], trim($data['value'])))
					]
				];

				$modelRow->load( $dataArray );
				$modelRow->save();
			}
		}

		foreach ( $exists_ids as $id ) {
			$this->findModel($id)->delete();
		}
	}

	private function _updateBooks($model, $post = [], $exists = []) {
		$exists_ids = [];
		foreach ( $exists as $row ) {
			if ($row->id > 0)
				$exists_ids[$row->id] = $row->id;
		}

		foreach ($post as $id => $data) {
			if ($id > 0 && in_array($id, $exists_ids)) {
				unset($exists_ids[$id]);
				// Exists row
				$modelRow = TeamBooks::findOne($id);
				if ($modelRow) {
					$dataArray = [
						'TeamBooks' => [
							'title' => $data['title']
						]
					];
					$modelRow->load( $dataArray );
					$modelRow->save();

					$files = UploadedFile::getInstances($model, $varnameFile);

//					$this->_uploadFiles($modelRow, 'TeamBooks[1]', 'cover', 'team/books');
				}
			} else {
				// New row
				if (empty($data['title'])) continue;

				$modelRow = new TeamBooks();
				$dataArray = [
					'TeamBooks' => [
						'team_id' => $model->id,
						'title' => $data['title'],
						'cover' => ''
					]
				];

				$modelRow->load( $dataArray );
				$modelRow->save();

				$this->_uploadFiles($modelRow, 'TeamBooks', 'cover', 'team/books');
			}
		}

		foreach ( $exists_ids as $id ) {
			$this->findModel($id)->delete();
		}
	}

	private function _uploadFile($model, $varnameFile, $varnameField, $dir = 'team') {
		$file = UploadedFile::getInstance($model, $varnameFile);

		if (!empty($file)) {
			$fileName = $dir .'/' . $file->basename . '.' . $file->extension;
			$filePath = Yii::getAlias( '@filesDir' ) .'/'. $fileName;
			$i = 1;
			while (file_exists($filePath)) {
				$fileName = $dir. '/' . $file->basename .'_'. $i . '.' . $file->extension;
				$filePath = Yii::getAlias( '@filesDir' ) .'/'. $fileName;
				$i++;
			}
			$file->saveAs( $filePath );
			$model->{$varnameField} = $fileName;
			$model->save();
		}
	}

	private function _uploadFiles($model, $varnameFile, $varnameField, $dir = 'team') {
		$file = UploadedFile::getInstances($model, $varnameFile);

		if (!empty($file)) {
			$fileName = $dir .'/' . $file->basename . '.' . $file->extension;
			$filePath = Yii::getAlias( '@filesDir' ) .'/'. $fileName;
			$i = 1;
			while (file_exists($filePath)) {
				$fileName = $dir. '/' . $file->basename .'_'. $i . '.' . $file->extension;
				$filePath = Yii::getAlias( '@filesDir' ) .'/'. $fileName;
				$i++;
			}
			$file->saveAs( $filePath );
			$model->{$varnameField} = $fileName;
			$model->save();
		}
	}

    /**
     * Deletes an existing Team model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

	public function actionDeleteSkill()
	{
		$id = Yii::$app->request->post('id');
		$model = TeamSkils::findOne($id);
		if ($model !== null) {
			$model->delete();
		}
		Yii::$app->response->format = Response::FORMAT_JSON;
		return ['r' => 1];
	}

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