<?php
namespace WpBookingProAdminWooPanel\app\models;
defined('_WPBOOKINGPRO_EXEC') or die;

use Exception;
use WpBookingPro\Factory;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Utilities\Utility;
use WpBookingProAdminWooPanel\app\helpers\AdminHelper;

class EventModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "event";
    /**
     * @var string
     */
    public $table_name = "event";
    public function save($data = array()) {
        $input = Factory::getInput();
        if (!$data) {
            $data = $input->getData()['data'];

        }
        $data['open_date'] = Factory::getDate($data['open_date'])->toSql();
        $data['close_date'] = Factory::getDate($data['close_date'])->toSql();
        $rates = $data['rates'];
        $custom_address = isset($data['custom_address'])?$data['custom_address']:'';

        if ($data['location_id'] == "" && $custom_address != "") {

            $modelLocation = Model::getInstance('location');
            $location = [
                'address' => $custom_address,
                'published' => 1
            ];
            $dataLocation = $modelLocation->save($location);
            $data['location_id'] = $dataLocation['id'];
        }
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $data['published'] = $data['published'] == 1 ? $data['published'] : 0;

        $event = parent::save($data); // TODO: Change the autogenerated stub

        $modelRate = Model::getInstance('rate');
        $query->clear()
            ->delete($this->getTableName('rate'))
            ->where('object_id=' . $event->id)
            ->where('type=' . $query->quote(AdminHelper::getWpBookingEventKey()));
        $db->setQuery($query)->execute();
        if (count($rates)) {
            foreach ($rates as $rate) {
                $rate = (string)$rate;
                list($from, $to) = explode(";", $rate);
                $item_rate = [
                    "id" => 0,
                    "from" => Factory::getDate($from)->toSql(),
                    "to" => Factory::getDate($to)->toSql(),
                    "type" => AdminHelper::getWpBookingEventKey(),
                    "object_id" => $event->id
                ];
                $item_rate = $modelRate->save($item_rate);
            }
        }
        //save tag
        $tag_id = isset($data['tags'])?$data['tags']:array();
        $modelTag = Model::getInstance('tag');
        if(!empty((array)$tag_id)) {
            foreach ($tag_id as $tag_id_item) {
                if(!is_numeric($tag_id_item) && is_string($tag_id_item) && trim($tag_id_item) !='')  {
                    $data_tag = [
                        "name"=> $tag_id_item
                    ];
                    $tag_item_new = $modelTag->save($data_tag);
                    array_push($tag_id,$tag_item_new->id);
                }

            }

            $query->clear()
                ->delete($this->getTableName('event_tag'))
                ->where('event_id='.(int)$event->id)
            ;
            $this->_db->setQuery($query)->execute();

            foreach ($tag_id as $key => $value)  {
                $query->clear()
                    ->insert($this->getTableName('event_tag'))
                    ->set('tag_id=' . (int)$value)
                    ->set('event_id=' . (int)$event->id)
                ;
                $this->_db->setQuery($query)->execute();

            }
        }
        //start save employee
        $list_employee_id = $data['list_employee_id'];
        $query->clear()
            ->delete($this->getTableName('event_employee'))
            ->where('event_id=' . (int)$event->id);
        $db->setQuery($query)->execute();
        foreach ($list_employee_id as $employee_id) {
            $query->clear()
                ->insert($this->getTableName('event_employee'))
                ->set('event_id=' . (int)$event->id)
                ->set('employee_id=' . (int)$employee_id);
            $db->setQuery($query)->execute();
        }
        $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/events/gallery/$name";
            $new_file_image_appointment_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_appointment_path, FileAlias::read($gallery['tmp_name'][$i]))) {
                throw new Exception(Text::_("can not upload image gallery"));
            }

            $event->gallery[] = $short_path_image;

            $data_gallery=array(
                "id"=>0,
                "type"=>AdminHelper::getWpBookingEventKey(),
                "object_id"=>$event->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 $event;
    }
    public function getItem($id = 0)
    {
        $item = parent::getItem($id); // TODO: Change the autogenerated stub

        if ($item) {
            $db = Factory::getDBO();
            $query = $db->getQuery(true)
                ->select("tag.id")
                ->from($this->getTableName('event_tag') . ' AS event_tag')
                ->leftJoin($this->getTableName('tag') . ' AS tag ON tag.id=event_tag.tag_id')
                ->where('event_tag.event_id=' . (int)$item->id);
            $item->tags = $db->setQuery($query)->loadColumn();
            $query->clear()
                ->select("rate.*")
                ->from($this->getTableName('rate') . ' AS rate')
                ->where('rate.object_id=' . (int)$item->id);
            $item->rates = $db->setQuery($query)->loadObjectList();

            $query->clear()
                ->select("gallery.*")
                ->from($this->getTableName('gallery') . ' AS gallery')
                ->where('gallery.object_id=' . (int)$item->id)
                ->where('gallery.type=' . $query->quote('event'));
            $item->gallery = $db->setQuery($query)->loadObjectList();

            $query->clear()
                ->select('service.id')
                ->from($this->getTableName('service') . ' AS service')
                ->where('service.id=' . (int)$item->service_id);
            $item->service_id = $db->setQuery($query)->loadColumn();
            $query->clear()
                ->select('event_employee.employee_id')
                ->from($this->getTableName('event_employee') . ' AS event_employee')
                ->where('event_id=' . (int)$item->id);
            $item->list_employee_id = $db->setQuery($query)->loadColumn();
        }
        return $item;
    }

}
