<?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;

/**
 * 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 = $_POST['file_name'];
            if($model->validate())
            {
                /*if($model->file)
                {
                    $model->upload();
                    $model->file = null;
                }*/

                // Yii::$app->user->identity->afterSubscribe(12);

                $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'];                      

            $targetPath = $model->getPath();
            $targetFile =  $targetPath. $_FILES['file']['name'];  

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