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

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

class CountryModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "country";
    /**
     * @var string
     */
    public $table_name = "country";
    public function save($data = array())
    {
        $country =  parent::save($data); // TODO: Change the autogenerated stub
        $galleryModel=Model::getInstance('gallery');
        $gallery=Factory::getInput()->files->get('gallery','','raw');
        if($gallery && count($gallery["name"]))for($i=0;$i<count($gallery["name"]);$i++){
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $gallery['name'][$i];
            $short_path_image = "upload/gallery/countries/$name";
            $new_file_image_hotel_path = WPBOOKINGHOTEL_PATH_ROOT . DS . $short_path_image;
            if (!File::write($new_file_image_hotel_path, File::read($gallery['tmp_name'][$i]))) {
                throw new Exception(Text::_("can not upload image gallery"));
            }

            $country->gallery[] = $short_path_image;

            $data_gallery=array(
                "id"=>0,
                "type"=>"country",
                "object_id"=>$country->id,
                "path"=>$short_path_image,
                "name"=>$gallery['name'][$i],
            );
            $galleryModel->save($data_gallery);
        }
        if(isset($data['list_image_gallery_deleted'])) {
            $list_image_gallery_deleted = $data['list_image_gallery_deleted'];
            $list_image_gallery_deleted = (array)json_decode($list_image_gallery_deleted);
        }else{
            $list_image_gallery_deleted=array();
        }
        if(count($list_image_gallery_deleted))foreach ($list_image_gallery_deleted as $id){
            $galleryModel->delete($id);
        }
        return $country;
    }
    public function getItem($id = 0)
    {
        $db=$this->_db;
        $query=$db->getQuery(true);
        $item = parent::getItem($id); // TODO: Change the autogenerated stub
        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('country'))
            ;
            $list_image= $this->_db->setQuery($query)->loadObjectList();
            $item->gallery=$list_image;
        }
        return $item;
    }
}
