<?php

namespace backend\controllers;

use backend\models\Chapter;
use Yii;
use backend\models\Quote;
use backend\models\QuoteSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;


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

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

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

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

    /**
     * Creates a new Quote model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Quote();
        $model->chapterId = $_GET['chapid'];

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->file = UploadedFile::getInstance($model, 'file');
            
            if ($model->file && $model->validate()) {
                $time_string = time().rand(0,100);
                $ha=  strrpos($model->file->name,'.',0);
                $name_img= $time_string.substr($model->file,$ha);

                $model->file->saveAs(Yii::$app->basePath.'/web/images/quote/' . $name_img);
                $model->image = $name_img;
            }
            if($model->save())
            if(isset($_GET["bookid"])) {
                return $this->redirect(['quote/index','QuoteSearch[chapterId]'=>$_REQUEST['chapid'],'bookid'=>$_GET["bookid"],'chapid'=>$_GET['chapid']]);
            }else {
                return $this->redirect(['index', 'id' => $model->id]);
            }
           // return $this->redirect(['index', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Quote 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;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if (Yii::$app->request->isPost) {
                $model->file = UploadedFile::getInstance($model, 'file');
                if(empty($model->file))
                {
                    $model->file= $oldImage;
                }
                else
                {
                    $time_string = time();
                    $ha=  strrpos($model->file,'.',0);
                    $name_img= $time_string.substr($model->file,$ha);
                   // $model->file = $name_img;                    
                }

                if ($model->file != $oldImage && $model->validate()) {
                    $model->deleteImage($oldImage)  ;
                    $model->file->saveAs(Yii::$app->basePath .'/web/images/quote/' . $name_img);
                    $model->image = $name_img;
                }
            } else {
                return 'Cannot Upload!';
            }
            if ($model->save()) {
                if(isset($_GET["bookid"])) {
                    return $this->redirect(['quote/index','QuoteSearch[chapterId]'=>$_REQUEST['chapid'],'bookid'=>$_GET["bookid"],'chapid'=>$_GET['chapid']]);
                }else {
                    return $this->redirect(['index', 'id' => $model->id]);
                }
            }
        } else {
            return $this->render('update', [
                'model' => $model,
                'QuoteSearch[chapterId]'=>$_REQUEST['chapid'],
                'bookid'=>$_GET["bookid"],
                'chapid'=>$_GET['chapid']
            ]);
        }
    }

    /**
     * Deletes an existing Quote 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 = Quote::findOne($id);
			/*$oldImage = $model->image;
			if(strlen($oldImage)>0)
			{
				$model->deleteImage($oldImage)  ;
			}*/		
						
			$model->delete();
            return $this->redirect(['quote/index','QuoteSearch[chapterId]'=>$_REQUEST['chapid'],'bookid'=>$_GET["bookid"],'chapid'=>$_GET['chapid']]);
        }else {
            $model = Quote::findOne($id);
			/*$oldImage = $model->image;
			if(strlen($oldImage)>0)
			{
				$model->deleteImage($oldImage)  ;
			}*/
					
			$model->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 Html::button('Back',array('name' => 'btnBack','onclick'=>'js:history.go(-1);returnFalse;','class'=>'uibutton loading confirm'));
    }
    public function actionBack()
    {
        return $this->redirect(Yii::$app->urlManager->createUrl(array('chapter/index','ChapterSearch[bookId]'=>$_GET["bookid"],'bookid'=>'14')));
    }
    /**
     * Finds the Quote model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Quote the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Quote::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
