<?php

namespace manager\controllers;

use  manager\models\Docs;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Yii;
use dosamigos\fileupload\FileUpload;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\helpers\BaseFileHelper;
use yii\helpers\Json;
/**
 * PageController implements the CRUD actions for Page model.
 */
class DocsController extends BaseController
{
    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
   //                     'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }

    /**
     * Lists all Page models.
     *
     * @return string
     */
    public function actionIndex()
    {
		$model = new Docs();
        return $this->render('index', [
            'model' => $model
        ]);
    }

    /**
     * Displays a single Page model.
     * @param int $id ID
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionUploads()
    {
        return $this->render('uploads', [
            'model' => new Docs(),
        ]);
    }


    /**
     * Creates a new Page model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Docs();

        if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
//				return json_encode( $model->getErrors() );
			}
        } else {
            $model->loadDefaultValues();
        }

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

    /**
     * Updates an existing Page model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param int $id ID
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
            Yii::$app->cache->delete("static_pagesx");
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

    /**
     * Deletes an existing Page model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param int $id ID
     * @return \yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
		if( is_numeric($id) ){
			$p = $this->findModel($id);
			if( $p ){
				$uid = $p->uid;
				$cat = $p->GetCat();
				$p->delete();
				$f = $cat. DIRECTORY_SEPARATOR .$uid;
				if( $uid && file_exists( $f ) ){
					unlink($f);
				}
				$ext = pathinfo($f, PATHINFO_EXTENSION);
				$ft = str_replace( '.'.$ext, '.webp', $f );
				if( $uid && file_exists( $ft ) ){
					unlink($ft);
				}
			}
		}else{
			$m = new Docs();
			$cat = $m->GetCat();
			$f = $cat. DIRECTORY_SEPARATOR .$id;
			if( file_exists( $f ) ){
				unlink( $f );
			}
			$ext = pathinfo($f, PATHINFO_EXTENSION);
			$ft = str_replace( '.'.$ext, '.webp', $f );
			if( file_exists( $ft ) ){
				unlink($ft);
			}
		}
		$cat = Yii::$app->request->get('cat', '');
		if( $cat ) return $this->redirect(['index', 'cat'=>$cat]);
        return $this->redirect(['index']);
    }

    public function actionUpdatetitle()
    {
        if ($this->request->isPost ) {
//			$this->request->enableCsrfValidation = false;
			if( $post && isset($post['uid'])  && isset($post['title']) ){
				$uid = str_replace( '_', '.', $post['uid'] );
				$model = Docs::findOne(['uid' => $uid]);
				if( !$model ){
					$model = new Docs();
					$model->text = '';
					$model->uid = $uid;
				}
				$model->title = $post['title'];
				if( $model->save() ){
					return json_encode(['status'=>'ok','item'=>$uid]);
				}else{
					return json_encode(['status'=>'err','text'=>'Ошибка сохранения']);
				}
			}else{
					return json_encode(['status'=>'err','text'=>'Ошибка данных']);
			}
        }
        return json_encode(['status'=>'err', 'text'=>'Ошибка передачи данных']);
    }

public function actionDocsupload()
{
    $model = new Docs();

    $imageFile = UploadedFile::getInstance($model, 'file');

    $directory = Yii::getAlias('@webroot/images/tmp') . DIRECTORY_SEPARATOR . Yii::$app->session->id . DIRECTORY_SEPARATOR;
    if (!is_dir($directory)) {
        FileHelper::createDirectory($directory);
    }

    if ($imageFile) {
		$cat = Yii::$app->request->get('cat', '');
        $uid = uniqid(time(), true);
        $fileName = $uid . '.' . $imageFile->extension;
        $filePath = $directory . $fileName;
        if ($imageFile->saveAs($filePath)) {
            $path = '/images/tmp/' . Yii::$app->session->id . DIRECTORY_SEPARATOR . $fileName;
			rename( $filePath, $model->GetCat() . DIRECTORY_SEPARATOR . $fileName );

			$model = new Docs();
			$model->title = $imageFile->baseName. '.' . $imageFile->extension;
			$model->uid = $fileName;
			$model->text = '';
			$model->cat = $cat;
			$model->save();

            return Json::encode([
                'files' => [
                    [
                        'name' =>  $model->GetUrl() . DIRECTORY_SEPARATOR . $fileName,
						'oname' => $imageFile->baseName. '.' . $imageFile->extension,
                        'size' => $imageFile->size,
                        'url' => $path,
                        'thumbnailUrl' => $path,
                        'deleteUrl' => 'image-delete?name=' . $fileName,
                        'deleteType' => 'POST',
                    ],
                ],
            ]);
        }
    }
    return Json::encode( [ 'error' => 'ok' ] );
}


    public function actionCatcreate()
    {
        $model = new Docs();

        if ($this->request->isPost && $cat = Yii::$app->request->post('Docs') ) {
            if ( isset($cat['cat']) && $model->CatCreate( $cat['cat'] ) ) {
                return $this->redirect(['index']);
            }
        }
        return $this->render('catcreate', [
            'model' => $model,
        ]);
    }


    /**
     * Finds the Page model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param int $id ID
     * @return Page the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Docs::findOne(['id' => $id])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
