<?php
namespace WpBookingHotelAdminWooPanel\app\models;
defined('_WPBOOKINGHOTEL_EXEC') or die;

use Exception;
use WpBookingHotel\Factory;
use WpBookingHotel\Language\Text;
use WpBookingHotel\Mvc\Model\ModelForm;
use WpBookingHotel\Filesystem\File as FileAlias;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Form\Form;
use WpBookingHotel\Mvc\Model\ModelList;
use WpBookingHotel\Registry\Registry;
use WpBookingHotel\Utilities\Utility;

class RoomtypeModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "roomtype";
    /**
     * @var string
     */
    public $table_name = "roomtype";

    public function save($data = array())
    {
        $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/roomtype/images/cover/$name";
            $new_file_image_roomtype_path = WPBOOKINGHOTEL_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_roomtype_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);
        }

        $query = $this->_db->getQuery(true);
        $list_amenity_id = isset($data['amenity_id'])?$data['amenity_id']:array();
        $query->clear()
            ->delete($this->getTableName('roomtype_amenity'))
            ->where('roomtype_id=' . (int)$item->id);
        $this->_db->setQuery($query)->execute();
        foreach ($list_amenity_id as $amenity_id) {
            $query->clear()
                ->insert($this->getTableName('roomtype_amenity'))
                ->set('roomtype_id=' . (int)$item->id)
                ->set('amenity_id=' . (int)$amenity_id)
            ;
            $this->_db->setQuery($query)->execute();
        }
        return $item;
    }
    public function getItem($id = 0)
    {
        $item =  parent::getItem($id); // TODO: Change the autogenerated stub
        if($item) {
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('roomtype_amenity.amenity_id')
                ->from($this->getTableName('roomtype_amenity') . ' AS roomtype_amenity')
                ->where('roomtype_id=' . (int)$item->id)
            ;
            $item->amenity_id = $db->setQuery($query)->loadColumn();
        }
        return $item;
    }


}
