<?php

namespace common\modules\bids\controllers;

use Yii;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\widgets\ActiveForm;
use yii\web\Response;
use yii\web\UploadedFile;

use common\modules\bids\models\Bid;
use dosamigos\transliterator\TransliteratorHelper;
/**
 * BidAdminController implements the CRUD actions for Bid model.
 */
class BidController extends \common\components\BaseController
{
    public static function actionsTitles()
    {
        return [
            'Add'          => 'Добавление заявки',
            'Upload-files'  => 'Загрузка файлов',
        ];
    }

    /**
     * Lists all Bid models.
     * @return mixed
     */
    public function actionAdd()
    {
        $model = new Bid;
        $model->scenario = Yii::$app->request->post('scenario');
        if(Yii::$app->request->isAjax)
        {
            $model->load(Yii::$app->request->post());
            $model->file = UploadedFile::getInstance($model, 'file');

            Yii::$app->response->format = Response::FORMAT_JSON;
            $model->filename = TransliteratorHelper::process($_POST['file_name'], '', 'en');
            $model->filename = str_replace("-", "_", $model->filename);
            $model->filename = preg_replace('/[^0-9a-z_\.]/i', '', $model->filename);
            
            if($model->validate())
            {
                /*if($model->file)
                {
                    $model->upload();
                    $model->file = null;
                }*/

                $model->save();
                $model->send();

                return ['success' => true];
            }
            else
            {
                return ActiveForm::validate($model);
            }
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    
    public function actionUploadFiles()
    {
        $model = new Bid();
        if (!empty($_FILES)) {

            $tempFile = $_FILES['file']['tmp_name'];                      
            $_FILES['file']['name'] = TransliteratorHelper::process($_FILES['file']['name'], '', 'en');
            $_FILES['file']['name'] = str_replace("-", "_", $_FILES['file']['name']);
            $_FILES['file']['name'] = preg_replace('/[^0-9a-z_\.]/i', '', $_FILES['file']['name']);
            
            $targetPath = $model->getPath();
            $targetFile =  $targetPath. $_FILES['file']['name'];  

            move_uploaded_file($tempFile,$targetFile); 
            return $_FILES['file']['name'];
        }
    }
}
