<?php
namespace TourOperatorProAdmin\app\models;
defined('_TOUROPERATOR_EXEC') or die;

use Exception;
use TourOperatorPro\Factory;
use TourOperatorPro\Filesystem\File as FileAlias;
use TourOperatorPro\Language\Text;
use TourOperatorPro\Mvc\Model\Model;
use TourOperatorPro\Mvc\Model\ModelForm;
use TourOperatorPro\Form\Form;
use TourOperatorPro\Mvc\Model\ModelList;
use TourOperatorPro\Registry\Registry;
use TourOperatorPro\Utilities\Utility;
use TourOperatorProAdmin\app\helpers\AdminHelper as AdminHelperAlias;

class CountryModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "country";
    /**
     * @var string
     */
    public $table_name = "country";
    public function save($data = array())
    {

        $now = Factory::getDate();
        if(!isset($data['id'])) {
            $data['created_date'] = $now->toSql();
        }
        $item =  parent::save($data); // TODO: Change the autogenerated stub

        // insert image
        $image=Factory::getInput()->files->get('image','','raw');
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            $short_path_image = "upload/countries/images/cover/$name";
            $new_file_image_tour_path = TOUROPERATORPRO_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_tour_path, FileAlias::read($image['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $item->image = $short_path_image;
            $data = (array)$item;
            $item = parent::save($data);
        }

        return $item;
    }

}
