<?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\ModelForm;
use WpBookingEvent\Form\Form;
use WpBookingEvent\Mvc\Model\ModelList;
use WpBookingEvent\Registry\Registry;
use WpBookingEvent\Utilities\Utility;

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
        $cover=Factory::getInput()->files->get('cover','','raw');
        if(!empty($cover['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $cover['name'];
            $short_path_image = "upload/employee/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($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'];
            $short_path_image = "upload/employee/images/fullimage/$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"));
            }
            $employee->image = $short_path_image;
            $data_image = (array)$employee;
            $employee = parent::save($data_image);
        }
        return $employee;
    }
    public function getItem($id = 0)
    {
        $employee = (object)parent::getItem($id); // TODO: Change the autogenerated stub
        $register = new Registry();
        $register->loadString($employee->params);
        $employee->params = $register;
        return $employee;
    }
}
