<?php

namespace backend\controllers;

use backend\models\Category;
use backend\models\Chapter;
use backend\models\Quote;
use backend\models\Comment;
use Yii;
use backend\models\Book;
use backend\models\BookSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\UploadedFile;

/**
 * BookController implements the CRUD actions for Book model.
 */
class BookController extends Controller
{
    public function behaviors()
    {
        return [
			'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['view', 'index','create','update','delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Book models.
     * @return mixed
     */
    public function actionIndex($id = NULL)
    {
        $searchModel = new BookSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $book= Book::find()->where('bookId ='.$id);
        $cate = Category::find()->all();
       // var_dump($book);exit;
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'book'=>$book,
            'cate'=> $cate
        ]);
    }

    /**
     * Displays a single Book model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = Book::find()->where('id ='.$id)->one();
        $category = Category::find()->where('id ='.$model->categoryId)->one();
        return $this->render('view', [
            'model' => $this->findModel($id),
            'category'=> $category
        ]);
    }

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

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if (Yii::$app->request->isPost) {
                $model->file = UploadedFile::getInstance($model, 'file');
                if ($model->file && $model->validate()) {
                    $time_string = time();
                    $name_img= $time_string.'.'.$model->file->extension;
                    $model->image = $name_img;
                }

                /*$model->attach = UploadedFile::getInstance($model, 'attach');
                if ($model->attach && $model->validate()) {
                    $time_string = time();
                    $name_attachment= $time_string.'.'.$model->attach->extension;
                    $model->attachment = $name_attachment;
                    $typeFile = $model->attach->extension;
                    //echo $typeFile ;exit;
                    if(strlen($typeFile)>0)
                    {
                        $check = $model->fileEpub($typeFile);
                        if( $check == true)
                        {
                            $model->type = 2;
                        }

                        $check2 = $model->filePdf($typeFile);

                        if( $check2 == true)
                        {
                            $model->type = 3;
                        }
                    }
                }
                else
                {
                    $model->type = 1;
                }*/

            } else {
                return 'Cannot Upload!';
            }

            if ($model->save()) {

                if(isset($model->file))
                {
                    $model->file->saveAs(Yii::$app->basePath .'/web/images/book/' . $model->image );
                }

                /*if(isset($model->attach))
                {
                    $model->attach->saveAs(Yii::$app->basePath .'/uploads/attachment/' . $model->attachment );
                }*/

                return $this->redirect(['index', 'id' => $model->id]);
            }

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

    /**
     * Updates an existing Book 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);
        $oldImage=$model->image;
        //$oldAttach=$model->attachment;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if (Yii::$app->request->isPost) {
                $model->file = UploadedFile::getInstance($model, 'file');
                if ($model->file && $model->validate()) {
                    //var_dump($model->file);exit;
                    $time_string = time();
                    $name_img = $time_string.'.'.$model->file->extension;
                    //echo $name_img;exit;
                    $model->image = $name_img;
                }
                else
                {
                    $model->image = $oldImage;
                }

                /*$model->attach = UploadedFile::getInstance($model, 'attach');
                if ($model->attach && $model->validate()) {
                    //var_dump($model->attach);exit;
                    $time_string = time();
                    $name_attach= $time_string.'.'.$model->attach->extension;
                    $model->attachment = $name_attach;

                    $typeFile = $model->attach->extension;
                    //echo $typeFile ;exit;
                    if(strlen($typeFile)>0)
                    {
                        $check = $model->fileEpub($typeFile);
                        if( $check == true)
                        {
                            $model->type = 2;
                        }

                        $check2 = $model->filePdf($typeFile);

                        if( $check2 == true)
                        {
                            $model->type = 3;
                        }
                    }
                }
                else
                {
                    if(strlen($oldAttach)>0)
                        $model->attachment = $oldAttach;
                    else
                        $model->type = 1;
                }*/
            } else {
                return 'Cannot Upload!';
            }

            if ($model->save()) {

                if(isset($model->file))
                {
                    $model->deleteImage($oldImage);
                    $model->file->saveAs(Yii::$app->basePath .'/web/images/book/' . $model->image);

                }

                /*if(isset($model->attach))
                {
                    $model->deleteAttachment($oldAttach);
                    $model->attach->saveAs(Yii::$app->basePath .'/uploads/attachment/' . $model->attachment);
                }*/

                return $this->redirect(['index', 'id' => $model->id]);
            }

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

    /**
     * Deletes an existing Book 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();
		$model = Book::findOne($id);
		$oldImage = $model->image;
        //$oldAttach = $model->attachment;
		if(strlen($oldImage)>0)
		{
			$model->deleteImage($oldImage);
		}

        /*if(strlen($oldAttach))
        {
            $model->deleteAttachment($oldAttach);
        }*/
		//Chapter::deleteAll(' bookId = :book', [':book' => $id]);
		//Quote::deleteAll(' chapterId = :chapter', [':chapter' => $id]);

		$chapters = Chapter::find()->where('bookId ='.$id)->all();
		if(count($chapters)>0)
		{
			foreach($chapters as $chapter)
			{
				$pages = Quote::find()->where('chapterId ='.$chapter->id)->all();
				if(count($pages)>0)
				{
					foreach($pages as $page)
					{
						$page->delete();
					}
				}
				if(strlen($chapter->attachment)>0)
				{
					$attachment = Yii::$app->basePath . '/uploads/attachment/' . $chapter->attachment;
					if(is_file($attachment)){
						unlink($attachment);
					}
				}
				$chapter->delete();
			}
		}

        Comment::deleteAll(' bookId = :book', [':book' => $id]);

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

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