<?php
namespace WpBookingEventAdmin\app\models;
defined('_WPBOOKINGEVENT_EXEC') or die;

use Exception;
use WpBookingEvent\Factory;
use WpBookingEvent\Filesystem\File as FileAlias;
use WpBookingEvent\Language\Text;
use WpBookingEvent\Mvc\Model\Model;
use WpBookingEvent\Mvc\Model\ModelForm;
use WpBookingEvent\Form\Form;
use WpBookingEvent\Mvc\Model\ModelList;
use WpBookingEvent\Registry\Registry;
use WpBookingEvent\Utilities\Utility;
use WpBookingEventAdmin\app\helpers\AdminHelper;

class ServiceModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "service";
    /**
     * @var string
     */
    public $table_name = "service";
    public function getListEmployee($service_id) {
        $query = $this->_db->getQuery(true);
        $query->select('service_employee.employee_id')
            ->from($this->getTableName('service_employee'). ' service_employee')
            ->where('service_employee.service_id='.(int)$service_id)
            ;
        $list_employee = $this->_db->setQuery($query)->loadColumn();
        return $list_employee;
    }
    public function save($data = array())
    {
        $input = Factory::getInput();
        if (!$data) {
            $data = $input->getData()['data'];

        }
        $params = array();
        foreach ($data as $key => $value) {
            if (strpos($key, "params") !== false) {
                $key = substr($key, 7);
                $params[$key] = $value;
            }
        }
        $params=reset($params);//TODO: Fix later
        $register = new Registry();
        $register->loadArray($params);
        $data['params'] = $register->toString();
        $service =  parent::save($data); // TODO: Change the autogenerated stub

        $image=Factory::getInput()->files->get('image','','raw');
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            $short_path_image = "upload/service/images/cover/$name";
            $new_file_image_tour_path = WPBOOKINGEVENT_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"));
            }
            $service->image = $short_path_image;
            $data_image = (array)$service;
            $service = parent::save($data_image);
        }

        $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/services/gallery/$name";
            $new_file_image_tour_path = WPBOOKINGEVENT_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"));
            }

            $service->gallery[] = $short_path_image;

            $data_gallery=array(
                "id"=>0,
                "type"=>AdminHelper::getWpBookingServiceKey(),
                "object_id"=>$service->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);
        }
        $query = $this->_db->getQuery(true);
        $list_employee_id = isset($data['list_employee_id'])?$data['list_employee_id']:array();
        $query->clear()
            ->delete($this->getTableName('service_employee'))
            ->where('service_id=' . (int)$service->id);
        $this->_db->setQuery($query)->execute();
        foreach ($list_employee_id as $employee_id) {
            $query->clear()
                ->insert($this->getTableName('service_employee'))
                ->set('service_id=' . (int)$service->id)
                ->set('employee_id=' . (int)$employee_id);
            $this->_db->setQuery($query)->execute();
        }
        return $service;
    }

    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('gallery.*')
                ->from($this->getTableName('gallery') . ' AS gallery')
                ->where('object_id=' . (int)$item->id)
                ->where('type=' . $query->quote(AdminHelper::getWpBookingServiceKey()));
            $item->gallery = $db->setQuery($query)->loadObjectList();
            $query->clear()
                ->select('service_employee.employee_id')
                ->from($this->getTableName('service_employee') . ' AS service_employee')
                ->where('service_id=' . (int)$item->id);
            $item->list_employee_id = $db->setQuery($query)->loadColumn();
            $query->clear()
                ->select('location.id')
                ->from($this->getTableName('location') . ' AS location')
                ->where('location.id=' . (int)$item->location_id);
            $item->location_id = $db->setQuery($query)->loadResult();
            $register = new Registry();
            $register->loadString($item->params);
            $item->params = $register;
        }

        return $item;
    }
}
