<?php

namespace common\modules\artboxfile\controllers;

use common\modules\artboxfile\models\File;
use Yii;
use yii\helpers\Html;
use yii\web\Controller;
use yii\web\UploadedFile;

class ActionController extends Controller {

    public $tmpDir = '@storage/tmp';

    public function actionUpload() {
        $request = Yii::$app->request->post();

        $multiple = !empty($request['multiple']);
        $fileField = empty($request['fileField']) ? 'file' : $request['fileField'];
        $formField = empty($request['formField']) ? 'fileUpload' : $request['formField'];


        if($_FILES[$formField])
        {
            if (($_FILES[$formField] == "none") OR (empty($_FILES[$formField]['name'])) )
            {
                $error = "Вы не выбрали файл";
            }
            else if ($_FILES[$formField]["size"] == 0 OR $_FILES[$formField]["size"] > 2050000)
            {
                $error = "Размер файла не соответствует нормам";
            }
            /*else if (($_FILES['upload']["type"] != "image/jpeg") AND ($_FILES['upload']["type"] != "image/jpeg") AND ($_FILES['upload']["type"] != "image/png") AND ($_FILES['upload']['type'] != 'image/gif'))
            {
                $message = "Допускается загрузка только картинок JPG, GIF и PNG.";
            }*/
            else if (!is_uploaded_file($_FILES[$formField]["tmp_name"]))
            {
                $error = "Что-то пошло не так. Попытайтесь загрузить файл ещё раз.";
            }
            else{
                $ext = $this->getex($_FILES[$formField]['name']);
                $name = $_FILES[$formField]['name'] .'.'. $ext;
                $tmpName = uniqid('tmpfile_') .'.'. $ext;

                $path = Yii::getAlias($this->tmpDir);
                if(!is_dir($path)) {
                    mkdir($path, 0755, true);
                }

                if (!move_uploaded_file($_FILES[$formField]['tmp_name'], $path .'/'. $tmpName)) {
                    $error = "File not uploaded";
                } else {
                    $full_path = $path .'/'. $tmpName;
                    $message = "Файл " . $_FILES[$formField]['name'] . " in $full_path загружен";
                }
            }
        }
        if (!empty($error)) {
            print json_encode(['error' => $error]);
        } else {
            $sendingData = [
                'append' => $multiple,
//                'initialPreview' => Html::img()
//                'initialPreviewConfig' => ,
//                'initialPreviewThumbTags' => ,

            ];
            print json_encode(['message' => $message, 'tmpfile' => $full_path, 'filename' => $name]);
        }
        exit;
    }

    protected function getex($filename) {
        return end(explode(".", $filename));
    }
}