<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;

class MenuItemForm extends Model {
    public $name;
    public $descr;
    public $cooking_time;
    public $category;
    public $price;
    public $img;

    public function rules()
    {
        return [
            [['name', 'descr', 'cooking_time', 'category', 'price'], 'required'],
            ['name', 'string', 'max' => 256],
            ['descr', 'string'],
            [['cooking_time', 'price'], 'integer', 'min' => 1],
            ['cooking_time', 'integer', 'max' => 180],
            ['price', 'integer', 'max' => 100000],
            ['category', 'string', 'max' => 100],
            [['img'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif', 'maxSize' => 2 * 1024 * 1024],
        ];  
    }

    public function attributeLabels()
    {
        return [
            'name' => 'Название блюда',
            'descr' => 'Описание',
            'cooking_time' => 'Время приготовления (минут)',
            'category' => 'Категория',
            'price' => 'Цена (руб.)',
            'img' => 'Изображение блюда',
        ];
    }

    public function uploadFile()
    {
        $file = UploadedFile::getInstance($this, 'img');
        if ($file) {            
            $folder = Yii::getAlias('@webroot') . '/menu_imgs/';
            $fileName = Yii::$app->security->generateRandomString(16) . '.' . $file->extension;
            $filePath = $folder . $fileName;
            
            if ($file->saveAs($filePath)) {
                return $fileName;
            } else {
                $this->addError('img', "Ошибка при сохранении файла: {$file->name}");
            }
        }
        
        return null;
    }

    public function saveMenuItem($menuItem = null)
    {
        if (!$this->validate()) {
            return false;
        }

        if ($menuItem === null) {
            $menuItem = new MenuItem();
        }
        
        $fileName = $this->uploadFile();
        if ($fileName) {
            $menuItem->img = $fileName;
        }

        $menuItem->name = $this->name;
        $menuItem->descr = $this->descr;
        $menuItem->cooking_time = $this->cooking_time;
        $menuItem->category = $this->category;
        $menuItem->price = $this->price;
        
        return $menuItem->save();
    }
}