<?php

namespace common\modules\school\controllers;

use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use common\modules\school\models\Courses;
use common\modules\school\models\SearchCourses;

class CoursesAdminController extends AdminController
{
    public static function actionsTitles()
    {
        return array(
            'View'   => 'Просмотр курса',
            'Create' => 'Создание курса',
            'Update' => 'Редактирование курса',
            'Delete' => 'Удаление курса',
            'Manage' => 'Управление курсами',
            'Upload' => 'Временное сохранение изображения',
        );
    }

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function actionView($id)
    {
        $model = $this->findModel($id);

        Yii::$app->controller->page_title  = 'Просмотр курса';

        Yii::$app->controller->breadcrumbs = [
            ['Список курсов' => '/school/courses-admin/manage'],
            'Добавить курс'
        ];

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

    public function actionCreate()
    {
        $model = new Courses;
        Yii::$app->controller->page_title = 'Добавить курс';
        Yii::$app->controller->breadcrumbs = [
            ['Список курсов' => '/school/courses-admin/manage'],
            'Добавить курс'
        ];

        if($model->load(Yii::$app->request->post()) && $model->validate()){
            //Try to get file info
            $model->upload_image = \yii\web\UploadedFile::getInstance($model, 'upload_image');
            //If received, then I get the file name and asign it to $model->image in order to store it in db
            if(!empty($model->upload_image)){
                $image_name = $model->upload_image->name;
                $model->image = $image_name;
            }
            
            $model->save();

            //If all went OK, then I proceed to save the image in filesystem
            if(!empty($model->upload_image)){
                $model->upload_image->saveAs($model->getPath().$image_name);
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }       
        else 
        {
            $form = new \common\components\BaseForm('/common/modules/school/forms/CourseForm', $model);
            return $this->render('create', [
                'model' => $model,
                'form' => $form->out
            ]);
        }
    }

    public function actionUpdate($id)
    {
        Yii::$app->controller->page_title = 'Редактировать курс';
        Yii::$app->controller->breadcrumbs = [
            ['Список курсов' => '/school/courses-admin/manage'],
            'Редактировать курс'
        ];
        $model = $this->findModel($id);

        if($model->load(Yii::$app->request->post()) && $model->validate()){
            //Try to get file info
            $model->upload_image = \yii\web\UploadedFile::getInstance($model, 'upload_image');

            //If received, then I get the file name and asign it to $model->image in order to store it in db
            if(!empty($model->upload_image)){
                $image_name = $model->upload_image->name;
                $model->image = $image_name;
            }

            $model->save();

            //If all went OK, then I proceed to save the image in filesystem
            if(!empty($model->upload_image)){
                $model->upload_image->saveAs($model->getPath().$image_name);
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }       
        else 
        {
            $form = new \common\components\BaseForm('/common/modules/school/forms/CourseForm', $model);
            return $this->render('update', [
                'model' => $model,
                'form' => $form->out
            ]);
        }
    }

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

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

       
    public function actionManage()
    {
        $searchModel = new SearchCourses();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams["SearchCourses"]);

            \yii::$app->controller->page_title = 'Управление курсами';

            \yii::$app->controller->breadcrumbs = [
                        'Управление курсами',
                    ];


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

    /**
     * Finds the Faq model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Faq the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Courses::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionUpload()
    {
        $model = new Courses;
            if (empty($_FILES['Courses'])) {
            echo json_encode(['error'=>'No files found for upload.']); 
            // or you can throw an exception 
            return; // terminate
        }

        // get the files posted
        $images = $_FILES['Courses'];
        $success = null;

        // file paths to store
        $paths= [];

        // get file names
        $filename = $images['name']["upload_image"];
        // loop and process files
        $ext = explode('.', basename($filename));
        $target = $model->getPath() . md5(uniqid()) . "." . array_pop($ext);
        if(move_uploaded_file($images['tmp_name']["upload_image"], $target)) {
            $success = true;
            $paths[] = $target;
        } else {
            $success = false;
            break;
        }

        // check and process based on successful status 
        if ($success === true) {

            $output = [];
        } elseif ($success === false) {
            $output = ['error'=>'Error while uploading images. Contact the system administrator'];

            foreach ($paths as $file) {
                unlink($file);
            }
        } else {
            $output = ['error'=>'No files were processed.'];
        }

        // return a json encoded response for plugin to process successfully
        echo json_encode($output);
    }
}
