<?php

namespace app\models;


use Yii;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
use zip\lib\createDirZip;
use app\models\User;


/**
 * This is the model class for table "files".
 *
 * @property integer $id
 * @property string $path
 */
//Yii::$app->params['uploadPath'] = "../uploads/".Yii::$app->user->identity->id."/";

class Files extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public $file;
    public $project_dogovor;
    public $uploads = '../uploads/';
    public $isUpdate;

    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';
    
    public function scenarios()
    {
        return [
            self::SCENARIO_CREATE => ['file', 'project_dogovor', 'path', 'name', 'user_id', 'lot_id'],
            self::SCENARIO_UPDATE => ['file', 'project_dogovor', 'path', 'name', 'user_id', 'lot_id'],
        ];
    }

    public static function tableName()
    {
        return 'files';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['path','name','user_id','lot_id'], 'safe'],
    
            // 🔥 CREATE → обязательно
            [['file', 'project_dogovor'], 'required',
                'on' => self::SCENARIO_CREATE,
                'message' => 'Необхідно прикріпити файл'
            ],
    
            // 🔥 валидация файлов ВСЕГДА
            [['file', 'project_dogovor'], 'file',
                'skipOnEmpty' => true,
                'maxSize'=> 50*(1024*1024),
                'extensions' => ['doc','docx','pdf','png','jpg','tiff','zip','rar']
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'path' => Yii::t('app', 'Path'),
            'name' => Yii::t('app', 'file name'),
            'user_id' => Yii::t('app', 'owner'),
            'auction_id' => Yii::t('app', 'auction_id'),
            'lot_id' => Yii::t('app', 'lot_id'),
            'date'=> Yii::t('app','date'),
        ];
    }


    public function saveFile($insert)
    {   if(empty($insert['type'])) { $insert['type'] = null; }
        //var_dump($saveFile); exit;
        Yii::$app->db->createCommand()->insert(
            'files', [
                        'name' => $insert['name'],
                        'path' => $insert['path'],
                        'user_id' => $insert['user_id'],
                        'auction_id' => $insert['auction_id'],
                        'lot_id' => $insert['lot_id'],
                        'type' => $insert['type'],
        ])
            ->execute();
        return $this->getFileID($insert['user_id'],$insert['lot_id'],$insert['name']);
    }

    public function updateFile($update)
    {
        Yii::$app->db->createCommand("UPDATE `files` SET name='".$update['name']."' WHERE `id`=" . $update['file_id'])->execute();
        return true;
    }

    private function getFileID($user,$lot,$name)
    {
        $res = $this->find()->where(['user_id'=>$user,'lot_id'=>$lot,'name'=>$name])->one();
        return $res->id;
    }

    public static function transliteration($str)
    {
        // ГОСТ 7.79B
        $transliteration = array(
            'А' => 'A', 'а' => 'a',
            'Б' => 'B', 'б' => 'b',
            'В' => 'V', 'в' => 'v',
            'Г' => 'G', 'г' => 'g',
            'Д' => 'D', 'д' => 'd',
            'Е' => 'E', 'е' => 'e',
            'Ё' => 'Yo', 'ё' => 'yo',
            'Ж' => 'Zh', 'ж' => 'zh',
            'З' => 'Z', 'з' => 'z',
            'И' => 'I', 'и' => 'i',
            'Й' => 'J', 'й' => 'j',
            'К' => 'K', 'к' => 'k',
            'Л' => 'L', 'л' => 'l',
            'М' => 'M', 'м' => 'm',
            'Н' => "N", 'н' => 'n',
            'О' => 'O', 'о' => 'o',
            'П' => 'P', 'п' => 'p',
            'Р' => 'R', 'р' => 'r',
            'С' => 'S', 'с' => 's',
            'Т' => 'T', 'т' => 't',
            'У' => 'U', 'у' => 'u',
            'Ф' => 'F', 'ф' => 'f',
            'Х' => 'H', 'х' => 'h',
            'Ц' => 'Cz', 'ц' => 'cz',
            'Ч' => 'Ch', 'ч' => 'ch',
            'Ш' => 'Sh', 'ш' => 'sh',
            'Щ' => 'Shh', 'щ' => 'shh',
            'Ъ' => 'ʺ', 'ъ' => 'ʺ',
            'Ы' => 'Y`', 'ы' => 'y`',
            'Ь' => '', 'ь' => '',
            'Э' => 'E`', 'э' => 'e`',
            'Ю' => 'Yu', 'ю' => 'yu',
            'Я' => 'Ya', 'я' => 'ya',
            '№' => '#', 'Ӏ' => '‡',
            '’' => '`', 'ˮ' => '¨',
        );

        $str = strtr($str, $transliteration);
        $str = mb_strtolower($str, 'UTF-8');
        $str = preg_replace('/[^0-9a-z.\-]/', '', $str);
        $str = preg_replace('|([-]+)|s', '-', $str);
        $str = trim($str, '-');

        //return time() . '_' . $str;
        return $str;
    }

    public function fileName()
    {
        return isset(Yii::$app->user->identity->username) ? 
            Yii::$app->user->identity->username.date('ymdhis') :
            $this->user_id.date('ymdhis'); //dir name
    }


    public function uploadFile()
    {
        $docs = UploadedFile::getInstances($this, 'file');
        $fileName = $this->fileName();

        $dir = FileHelper::createDirectory($this->uploads.$fileName); //create dir
        $saved = false;

        foreach ($docs as $k => $file){
            $file->name = $this->transliteration($file->name);
            $saved = $file->saveAs($this->uploads.$fileName.'/'. $file->name) || $saved ; // move upload file to dir
        }

        /**
         * CREATE ZIP
         */

        $createZip = new createDirZip();

        $createZip->get_files_from_folder($this->uploads . $fileName.'/','');

        /**
         * DElETE UPLOADS DIR
         */
        FileHelper::removeDirectory($this->uploads.$fileName);

        $fileName .= '.zip';

        $fd = fopen($this->uploads.$fileName, 'wb');

        $out = fwrite ($fd, $createZip->getZippedfile());

        fclose ($fd);
        //$createZip->forceDownload($fileName); // start download archive

        return $saved ? $fileName : false;
    }

  public function getUser()
  {
      return $this->hasOne(User::className(),['id' => 'user_id']);
  }

  public function copy($lot_id)
  {
      $path = str_replace($this->lot_id,$lot_id,$this->path.$this->name);

      //string(38) "../uploads/lots/neiron180223093830.zip"

      $directoryPath = explode('/', $path);
      //array(4) { [0]=> string(2) ".." [1]=> string(7) "uploads" [2]=> string(4) "lots" [3]=> string(22) "neiron180223093830.zip" }

      $name = end($directoryPath);
      //string(22) "neiron180223093830.zip"

      array_pop($directoryPath);
      //string(4) "lots"


      $directoryPath = implode('/', $directoryPath).'/clone/'.$this->lot_id.'_'.date('now').'/';
      //string(51) "../uploads/lots/clone/neiron180223093830.zip220185/"
      //var_dump($directoryPath);die();

      $copyFileName = $directoryPath.$name;

      FileHelper::createDirectory($directoryPath);

      copy($this->path.$this->name,$copyFileName);

      $model = new Files();

      $data = $this->attributes;

      $data['path'] = $directoryPath;
      $data['name'] = $name;

      $data['lot_id'] = $lot_id;
      $model->load($data, '');
      return $model->save(false) ? $model->id : false;
  }

}
