<?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'          => 'Добавление заявки',
        ];
    }

    /**
     * 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;

            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.');
        }
    }

}
