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

use Exception;
use TourOperatorPro\Filesystem\File as FileAlias;
use TourOperatorPro\Language\Text;
use TourOperatorPro\Utilities\Utility as UtilityAlias;
use TourOperatorProAdmin\app\helpers\AdminHelper as AdminHelperAlias;
use TourOperatorPro\Factory;
use TourOperatorPro\Filesystem\File;
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;

class TourModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "tour";
    /**
     * @var string
     */
    public $table_name = "tour";
    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

        $list_key_properties=AdminHelperAlias::$list_key_tour_properties;

        foreach ($list_key_properties as $key_tour=>$description){
            if(!isset($data[$key_tour]))
                continue;
            $this->deletePropertyByKey($key_tour,$item->id);
            $data_properties=$data[$key_tour];
            $this->insertNewPropertyByKey($key_tour,$data_properties, $item->id);
            $item->{$key_tour}=$data_properties;
        }

        // 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/tours/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);
        }
        $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/tours/$name";
            $new_file_image_tour_path = TOUROPERATORPRO_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_tour_path, FileAlias::read($gallery['tmp_name'][$i]))) {
                throw new Exception(Text::_("can not upload image gallery"));
            }

            $item->gallery[] = $short_path_image;

            $data_gallery=array(
                "id"=>0,
                "type"=>"tour",
                "object_id"=>$item->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 $item;
    }
    public function deletePropertyByKey($key='',$id=0) {
        $query=$this->_db->getQuery(true);
        $query->clear()
            ->delete($this->getTableName('tourproperty'))
            ->where('object_id='.(int)$id)
            ->where('type='.$query->quote($key))
        ;
        $this->_db->setQuery($query)->execute();

    }
    public function insertNewPropertyByKey($key='',$properties=array(), $tour_id=0) {
        $query =$this->_db->getQuery(true);
        foreach ($properties as $property) {
            $query->clear()
                ->insert($this->getTableName('tourproperty'))
                ->set('object_id='.(int)$property)
                ->set('type='.$query->quote($key))
                ->set('tour_id='.(int)$tour_id)
            ;
            $this->_db->setQuery($query)->execute();
        }


    }
    public function getItem($id = 0)
    {
        $db=$this->_db;
        $query=$db->getQuery(true);
        $tour= parent::getItem($id); // TODO: Change the autogenerated stub
        if(isset($tour->id) && $tour->id!=0) {
            $query->clear()
                ->select('DISTINCT tourtype.id')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('tourtype').' AS tourtype ON tourtype.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(AdminHelperAlias::getTourTypeKey()))
            ;
            $list_tour_type= $this->_db->setQuery($query)->loadColumn();
            $tour->tourtype=$list_tour_type;

            $query->clear()
                ->select('DISTINCT location.id')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('location').' AS location ON location.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(AdminHelperAlias::getTourDestinationKey()))
            ;
            $list_destination= $this->_db->setQuery($query)->loadColumn();
            $tour->destination=$list_destination;

            $query->clear()
                ->select('DISTINCT activities.id')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('activity').' AS activities ON activities.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(AdminHelperAlias::getTourActivityKey()))
            ;
            $list_activity= $this->_db->setQuery($query)->loadColumn();
            $tour->activity=$list_activity;

            $query->clear()
                ->select('DISTINCT seasons.id')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('season').' AS seasons ON seasons.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(AdminHelperAlias::getTourSeasonKey()))
            ;
            $list_season= $this->_db->setQuery($query)->loadColumn();
            $tour->season=$list_season;




            $query->clear()
                ->select('DISTINCT gallery.*')
                ->from($this->getTableName('gallery').' AS gallery')
                ->where('object_id='.(int)$tour->id)
                ->where('type='.$query->quote('tour'))
            ;
            $list_image= $this->_db->setQuery($query)->loadObjectList();
            $tour->gallery=$list_image;

            $query->clear()
                ->select('DISTINCT itinerary.*')
                ->from($this->getTableName('itinerary').' AS itinerary')
                ->where('itinerary.published=1')
                ->where('tour_id='.(int)$tour->id)
            ;
            $list_itineraries= $this->_db->setQuery($query)->loadObjectList();
            $tour->itineraries=$list_itineraries;


        }
        return $tour;
    }

}
