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

use Exception;
use WpBookingPro\Factory;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingPro\Utilities\Utility;
use WpBookingProAdmin\app\helpers\AdminHelper;
use WpBookingProFrontend\app\helpers\FrontendHelper;

class EmployeeModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "employee";
    /**
     * @var string
     */
    public $table_name = "employee";
    public function save($data = array())
    {
        $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();

        $item= parent::save($data); // TODO: Change the autogenerated stub
        $image=Factory::getInput()->files->get('image','','raw');
        $check_user_demo = FrontendHelper::checkUserDemo();

        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            if($check_user_demo['is_demo']) {
                $short_path_image = "employee/images/cover/$name";
                $new_file_image_activity_path = WP_CONTENT_DIR . '/uploads/sites/' . $check_user_demo['blog_id'].DS.$short_path_image;
            } else {
                $short_path_image = "upload/employee/images/cover/$name";
                $new_file_image_activity_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;
            }
            if (!FileAlias::write($new_file_image_activity_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];
            if($check_user_demo['is_demo']) {
                $short_path_image = "employees/gallery/$name";
                $new_file_image_appointment_path = WP_CONTENT_DIR . '/uploads/sites/' . $check_user_demo['blog_id'].DS.$short_path_image;
            } else {
                $short_path_image = "upload/employees/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"));
            }

            $item->gallery[] = $short_path_image;

            $data_gallery=array(
                "id"=>0,
                "type"=>'employee',
                "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);
        }

        $list_service_id = isset($data['service']) ?$data['service']:array();
        $start_time = isset($data['start_time'])?$data['start_time']:array();
        $end_time = isset($data['end_time'])?$data['end_time']:array();
        $price = isset($data['price'])?$data['price']:array();
        $order_service = isset($data['order_service'])?json_decode($data['order_service']):array();
        $order_service  = array_count_values($order_service);
        $query = $this->_db->getQuery(true);
        $query->clear()
            ->delete($this->getTableName('service_employee'))
            ->where('employee_id ='.(int)$item->id)
        ;
        $this->_db->setQuery($query)->execute();
        foreach ($list_service_id as $service_id) {
            $number_service_item = $order_service[$service_id];
            for ($i = 0; $i < $number_service_item; $i++) {
                $query->clear()
                    ->insert($this->getTableName('service_employee'))
                    ->set('employee_id=' . (int)$item->id)
                    ->set('service_id=' . (int)$service_id)
                    ->set('start_time=' . $query->quote($start_time[$i]))
                    ->set('end_time=' . $query->quote($end_time[$i]))
                    ->set('price=' . (float)$price[$i]);
                $this->_db->setQuery($query)->execute();
            }
            for ($i = 0; $i < $number_service_item; $i++) {
                unset($start_time[$i]);
                unset($end_time[$i]);
                unset($price[$i]);
            }
            $start_time = array_values($start_time);
            $end_time = array_values($end_time);
            $price = array_values($price);
        }
            return $item;
    }
    public function getItem($id = 0)
    {
        $employee = (object)parent::getItem($id); // TODO: Change the autogenerated stub
        $query = $this->_db->getQuery(true);
        if(!empty((array)$employee)) {
            $query->clear()
                ->select('country.countryname')
                ->from($this->getTableName('country').' AS country')
                ->where('country.phonecode='.(int)$employee->phonecode)
                ->where('country.countrycode='.$query->quote($employee->countrycode))
            ;
            $employee->country_name = $this->_db->setQuery($query)->loadResult();
            $register = new Registry();
            $register->loadString($employee->params);
            $employee->params = $register;
        }

        return $employee;
    }




}
