<?php

namespace backend\controllers;

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

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

    /**
     * Lists all Chapter models.
     * @return mixed
     */
    public function actionIndex()
    {
       // echo $_REQUEST['bookid'];exit;
        $searchModel = new ChapterSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Chapter model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $chap= Chapter::findOne($id);
        $bookId= $chap->bookId;
        $book= Book::findOne($bookId);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'book'=>$book
        ]);
    }
    public function actionBack()
    {
        return $this->redirect(Yii::$app->urlManager->createUrl('book/index'));
    }
    /**
     * Creates a new Chapter model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Chapter();
        $model->bookId = $_GET['bookid'];

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

            $model->attach = UploadedFile::getInstance($model, 'attach');
			$directUrl = $_REQUEST['Chapter']['directURL'];
			$type = $_REQUEST['Chapter']['type'];
			//if(strlen($directUrl) > 0)
			//{
			//	$pos = strrpos($directUrl,'.')+1;
			//	$extensionFile = substr($directUrl,$pos);
			//	$type = Chapter::checkType($extensionFile);
				$model->type = $type;
			//}else{			
				if ($model->attach && $model->validate()) {
					$time_string = time().rand(0,100);
					$name_img= $time_string.'.'.$model->attach->extension;                
					$model->attachment = $name_img;
					
					//$type = $model->checkType($model->attach->extension);				
					//$model->type = $type;
				}
				//else
				//{
					//$model->type = 0;
				//}
			//}
            $model->time = date('Y-m-d H:i:s',strtotime('now'));
            if($model->save())
			{
				if(isset($model->attach)){
					$model->attach->saveAs(Yii::$app->basePath.'/uploads/attachment/' . $model->attachment);
				}
				if(isset($_GET["bookid"])) {
					return $this->redirect(['chapter/index','bookid'=> $_GET["bookid"], 'ChapterSearch[bookId]'=> $_GET["bookid"]]);
				}else {
					return $this->redirect(['index', 'id' => $model->id]);
				}
			}
            
            //return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Chapter 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->attach = UploadedFile::getInstance($model, 'attach');   
				$directUrl = $_REQUEST['Chapter']['directURL'];
				$type = $_REQUEST['Chapter']['type'];
				//if(strlen($directUrl) > 0)
				//{
				//	$pos = strrpos($directUrl,'.')+1;
				//	$extensionFile = substr($directUrl,$pos);
				//	$type = Chapter::checkType($extensionFile);
					$model->type = $type;
				//}else
				//{
					if ($model->attach && $model->validate()) {
						$time_string = time().rand(0,100);
						$name_img= $time_string.'.'.$model->attach->extension;                
						$model->attachment = $name_img;
						
						//$type = $model->checkType($model->attach->extension);				
						//$model->type = $type;
					}
					else
					{
						$model->attachment = $oldAttach;
					}
				//}
            } else {
                return 'Cannot Upload!';
            }
            //return $this->redirect(['view', 'id' => $model->id]);
            if($model->save())
            {
				if(isset($model->attach)){
					$model->deleteAttach($oldAttach);
					$model->attach->saveAs(Yii::$app->basePath.'/uploads/attachment/' . $model->attachment);
				}
                if(isset($_GET["bookid"])) {
                    return $this->redirect(['chapter/index','bookid'=> $_GET["bookid"], 'ChapterSearch[bookId]'=> $_GET["bookid"]]);
                }else {
                    return $this->redirect(['index', 'id' => $model->id]);
                }
            }

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

    /**
     * Deletes an existing Chapter model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if(isset($_GET["bookid"])) {
            $model = Chapter::findOne($id);
			/*$oldImage = $model->image;
			if(strlen($oldImage)>0)
			{
				$model->deleteImage($oldImage)  ;
			}*/
			
			$oldAttach = $model->attachment;
			if(strlen($oldAttach)>0)
			{
				$model->deleteAttach($oldAttach)  ;
			}
			
			Quote::deleteAll(' chapterId = :chapter', [':chapter' => $id]);
            Comment::deleteAll(' chapterId = :chapter', [':chapter' => $id]);
			
			$model->delete();
			
            return $this->redirect(['chapter/index','bookid'=> $_GET["bookid"], 'ChapterSearch[bookId]'=> $_GET["bookid"]]);
        }else {
            $model = Chapter::findOne($id);
			/*$oldImage = $model->image;
			if(strlen($oldImage)>0)
			{
				$model->deleteImage($oldImage)  ;
			}*/
			
			$oldAttach = $model->attachment;
			if(strlen($oldAttach)>0)
			{
				$model->deleteAttach($oldAttach)  ;
			}
			
			Quote::deleteAll(' chapterId = :chapter', [':chapter' => $id]);
            Comment::deleteAll(' chapterId = :chapter', [':chapter' => $id]);
			
			$model->delete();
            return $this->redirect(['index']);
        }
            /*$this->findModel($id)->delete();
            $url = $_SERVER['HTTP_REFERER']; // right back to the referrer page from where you came.
            echo '<meta http-equiv="refresh" content="0.1;URL=' . $url . '">';*/


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

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