<?php

namespace common\modules\school\controllers;

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

use common\modules\school\models\Lessons;
use common\modules\school\models\SearchLessons;
use common\modules\school\models\LessonImage;

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

    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/lessons-admin/manage'],
            'Добавить урок'
        ];

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

    public function actionCreate()
    {
        $model = new Lessons;
        $exts = array("pdf", "gif", "jpg", "png", "doc", "docx", "xls", "xlsx", "rtf");
        $errorMessages = array();
        
        Yii::$app->controller->page_title = 'Добавить урок';
        Yii::$app->controller->breadcrumbs = [
            ['Список курсов' => '/school/lessons-admin/manage'],
            'Добавить урок'
        ];

        $model->load(Yii::$app->request->post());
        if (Yii::$app->request->isPost && $model->validate()) 
        {
             $files = UploadedFile::getInstancesByName('LessonImage');      
             $model->save();
                if ($files) {
                    foreach ($files as $key=>$file) {
                       $name = $_POST['Filename'][$key];
                       if ($name) {
                            // Получение расширения файла
                            $extension = $file->getExtensionName();
                             if (in_array($extension, $exts)){
                                $filename = $model->getFilename($name).'.'.$extension;
                                 if ($file->saveAs($model->getPath().$filename)) {
                                     $docs = new LessonImage;
                                     $docs->title = $name;
                                     $docs->filename =$filename;
                                     $docs->lesson_id = $model->id;
                                     $docs->save();
                                  } 
                            }
                            else {
                                $errorMessage = 'Неверное расширение файла "'.$file->name.'"';
                                array_push($errorMessages, $errorMessage);
                            }
                        }
                        else {
                           $errorMessage = 'Введите имя документа "'.$file->name.'"';
                           array_push($errorMessages, $errorMessage);
                        }
                     }
                  }
            if (!$errorMessages) {          
              return $this->redirect(['manage']);
            }
        } 
        $model->errors = $errorMessages;
        $form = new \common\components\BaseForm('/common/modules/school/forms/LessonForm', $model, $errorMessages);
        return $this->render('create', [
            'model' => $model,
            'form' => $form->out,
        ]);
    }

    public function actionUpdate($id)
    {
        $exts = array("pdf", "gif", "jpg", "png", "docx", "doc", "xls", "xlsx", "rtf");
        $errorMessages = array();
        
        Yii::$app->controller->page_title = 'Редактировать урок';
        Yii::$app->controller->breadcrumbs = [
            ['Список уроков' => '/school/lessons-admin/manage'],
            'Редактировать урок'
        ];
       $model = $this->findModel($id);
       $model->load(Yii::$app->request->post());
       if (Yii::$app->request->isPost && $model->validate()) {
           $model->save();
           $files = UploadedFile::getInstancesByName('LessonImage'); 
           if ($files) {
               foreach ($files as $key=>$file) {
                   $name = $_POST['Filename'][$key];
                   if ($name) {
                        // Получение расширения файла
                        $extension = $file->getExtension();
                         if (in_array($extension, $exts)){
                            $filename = $model->getFilename($name).'.'.$extension;
                             if ($file->saveAs($model->getPath().$filename)) {
                                 $docs = new LessonImage;
                                 $docs->title = $name;
                                 $docs->filename =$filename;
                                 $docs->lesson_id = $model->id;
                                 $docs->save();
                              } 
                        }
                        else {
                            $errorMessage = 'Неверное расширение файла "'.$file->name .'"';
                            array_push($errorMessages, $errorMessage);
                        }
                    }
                    else {
                           $errorMessage = 'Введите имя документа "'.$file->name.'"';
                           array_push($errorMessages, $errorMessage);
                       }
                 }   
             }
            if (!$errorMessages) {          
              return $this->redirect(['manage']);
            }
            $model->errors = $errorMessages;
        } 
        $form = new \common\components\BaseForm('/common/modules/school/forms/LessonForm', $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 SearchLessons();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams["SearchLessons"]);

        \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 = Lessons::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }  
        
    public function actionUpload()
    {
        $model = new Lessons;
        if (empty($_FILES['Lessons'])) {
            echo json_encode(['error'=>'No files found for upload.']); 
            // or you can throw an exception 
            return; // terminate
        }

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

        // file paths to store
        $paths= [];
        // get file names
        //$filename = $images['name']["upload_image"];
        // loop and process files
        //$ext = explode('.', basename($filename));
        $filename = str_replace("-", "_", $images['name']["filesUpload"][0]);
        $filename = TransliteratorHelper::process($filename, '', 'en');
        $filename = preg_replace('/[^0-9a-z_\.]/i', '', $filename);
        
        $target = $model->getPath() . $filename;//md5(uniqid()) . "." . array_pop($ext);
        if(move_uploaded_file($images['tmp_name']["filesUpload"][0], $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);
    }  
    
    public function actionUpdateFormDocument()
    {
        $id = $_POST['docId'];
        $model = LessonImage::findOne($id);
        echo  '<div class="tag-item">'.
               '<a title="Закрыть форму редактирования" href="javascript:void(0);" class="close-doc">
                   X</a>'.
               '<label for="Doc_name">Введите имя документа<span class="required"> *</span></label>'.
               '<input class="span12" name="Filename[]" type="text" id="Doc_name" value="'.$model->title.'">'.
                '<a class="btn btn-doc-proj" data-id='.$model->id.'>'.
                  'Сохранить'.
                '</a>'.
             '</div>'; 
    }
    
     public function actionDeleteDocument()
    {
        $docId = $_POST['docId'];
        $lesson = new Lessons();
        $model = LessonImage::findOne($docId);
        unlink($lesson->getPath().$model->filename);
        $model->delete();  
    }
    
    public function actionUpdateDocument()
	{
      $docId = $_POST['docId'];
      $docName = $_POST['name'];
      $model = $model = LessonImage::findOne($docId);
      $model->title = $docName;
      if ($model->save()) {
          echo '<div class="tag-item" id="document-'.$model->id.'">'.
              '<div class="tag-title"><input type="checkbox" value="'.$model->title.'" checked="checked" name="Filenames[]">'.
                 ($model->title ? $model->title : $model->filename). 
                  '</div>'.
               '<a title="Редактировать документ" href="javascript:void(0);" class="upd-doc-projs" data-id="'.$model->id.'">'.
                  '<i class="icon-pencil"></i>'.
              '</a>'.
              '<a title="Удалить документ" href="javascript:void(0);" class="remove-doc-projs" value="'.$model->id.'">
                   X
               </a>'.
           '</div>';
      }
	}
}
