<?php
namespace WpBookingEventAdmin\app\models;
defined('_WPBOOKINGEVENT_EXEC') or die;

use Exception;
use WpBookingEvent\Factory;
use WpBookingEvent\Filesystem\File as FileAlias;
use WpBookingEvent\Language\Text;
use WpBookingEvent\Mvc\Model\ModelForm;
use WpBookingEvent\Mvc\Model\Model;
use WpBookingEvent\Form\Form;
use WpBookingEvent\Mvc\Model\ModelList;
use WpBookingEvent\Registry\Registry;
use WpBookingEvent\Utilities\Utility;
class LocationModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "location";
    /**
     * @var string
     */
    public $table_name = "location";

    public function getItem($id=0){
        $table=$this->getTable();
        $key = $table->getKeyName();
        $input=Factory::getInput();
        if(!$id){
            $id=$input->getInt($key,0);
        }
        $db=Factory::getDBO();
        $query=$db->getQuery(true);
        $query->select('location.*')
            ->from($this->getTableName('location'). ' AS location')
            ->where($key.'='.(int)$id)
        ;
        $item=$this->db->setQuery($query)->loadObject();
        if(isset($item->id)&& $item->id!=0){
            $query->clear()
                ->select('DISTINCT gallery.*')
                ->from($this->getTableName('gallery').' AS gallery')
                ->where('object_id='.(int)$item->id)
                ->where('type='.$query->quote('destination'))
            ;
            $list_image= $this->_db->setQuery($query)->loadObjectList();
            $item->gallery=$list_image;
        }
        return $item;
    }
    public function save($data = array())
    {
        $location= parent::save($data); // TODO: Change the autogenerated stub
        $image=Factory::getInput()->files->get('image','','raw');
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            $short_path_image = "upload/location/images/cover/$name";
            $new_file_image_activity_path = WPBOOKINGEVENT_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_activity_path, FileAlias::read($image['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $location->image = $short_path_image;
            $data = (array)$location;
            $location = parent::save($data);
        }
        return $location;
    }


}
