<?php
namespace TourOperatorProAdmin\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();
        $is_new = (isset($data['id']) && $data['id'] != '' && is_numeric($data['id']))?false:true;
        if(!isset($data['id']) && $is_new) {
            $data['created_date'] = $now->toSql();
        } else {
            unset($data['created_date']);
            $data['update_time'] = $now->toSql();
        }
        $item =  parent::save($data); // TODO: Change the autogenerated stub
        if($is_new) {
            $tour_id = $item->id;
        } else {
            $tour_id = $data['id'];
        }
        $list_key_properties=AdminHelperAlias::$list_key_tour_properties;
        unset($list_key_properties['rate']);

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

        // save rate

        $from = isset($data['from'])?$data['from']:array();
        if(count($from) == 1 && trim($from['0']) == '') {
            $from = array();
        }
        $to = isset($data['to'])?$data['to']:array();
        if(count($to) == 1 && trim($to['0']) == '') {
            $to = array();
        }
        $modelRate = Model::getInstance('rate');
        $query = $this->_db->getQuery(true);

        if(!empty($from) && !empty($to)) {
            $query->clear()
                ->delete($this->getTableName('rate'))
                ->where('object_id='.(int)$tour_id)
                ->where('type='.$query->quote('tour'))
            ;
            $this->_db->setQuery($query)->execute();

            $query->clear()
                ->delete($this->getTableName('tourproperty'))
                ->where('tour_id='.(int)$tour_id)
                ->where('type='.$query->quote(AdminHelperAlias::getTourRateKey()))
            ;
            $this->_db->setQuery($query)->execute();

            foreach ($from as $key => $from_item) {
                $item_rate = [
                    "id" => 0,
                    "from" => Factory::getDate($from_item)->toSql(),
                    "to" => Factory::getDate($to[$key])->toSql(),
                    "type"=>'tour',
                    "object_id"=> $tour_id
                ];
                $item_rate = $modelRate->save($item_rate);



                $query->clear()
                    ->insert($this->getTableName('tourproperty'))
                    ->set('object_id=' . (int)$item_rate->id)
                    ->set('tour_id=' . (int)$tour_id)
                    ->set('type='.$query->quote(AdminHelperAlias::getTourRateKey()))
                ;
                $this->_db->setQuery($query)->execute();
            }
        }

        // 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);
        }

        $introduce_image=Factory::getInput()->files->get('introduce_image','','raw');
        if(!empty($introduce_image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $introduce_image['name'];
            $short_path_image = "upload/tours/introduce_image/cover/$name";
            $new_file_image_tour_path = TOUROPERATORPRO_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_tour_path, FileAlias::read($introduce_image['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $item->introduce_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 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 rate.*')
                ->from($this->getTableName('rate').' AS rate')
                ->leftJoin($this->getTableName('tourproperty').' AS tourproperty ON tourproperty.object_id=rate.id')
                ->where('tourproperty.tour_id='.(int)$tour->id)
                ->where('tourproperty.type='.$query->quote(AdminHelperAlias::getTourRateKey()))
            ;
            $list_rate= $this->_db->setQuery($query)->loadObjectList();
            $tour->list_rate=$list_rate;

            $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;
    }

}
