<?php
namespace WpBookingProAdmin\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\ModelForm;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingPro\Utilities\Utility;
use WpBookingProAdmin\app\helpers\AdminHelper;

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

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

        $check_user_demo = AdminHelper::checkUserDemo();
        $cover=Factory::getInput()->files->get('cover','','raw');
        if(!empty($cover['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $cover['name'];
            if($check_user_demo['is_demo']) {
                $short_path_image = "employee/images/cover/$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/employee/images/cover/$name";
                $new_file_image_appointment_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;
            }
            if (!FileAlias::write($new_file_image_appointment_path, FileAlias::read($cover['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $employee->cover = $short_path_image;
            $data_cover = (array)$employee;
            $employee = parent::save($data_cover);
        }
        $image=Factory::getInput()->files->get('image','','raw');
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            if($check_user_demo['is_demo']) {
                $short_path_image = "employee/images/fullimage/$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/employee/images/fullimage/$name";
                $new_file_image_appointment_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;

            }
            if (!FileAlias::write($new_file_image_appointment_path, FileAlias::read($image['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $employee->image = $short_path_image;
            $data_image = (array)$employee;
            $employee = parent::save($data_image);
        }

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