<?php
namespace WpBookingProAdmin\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;

class CategoryModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "category";
    /**
     * @var string
     */
    public $table_name = "category";

    public function save($data = array())
    {
        $item= parent::save($data); // TODO: Change the autogenerated stub
        $image=Factory::getInput()->files->get('image','','raw');
        $check_user_demo = AdminHelper::checkUserDemo();
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            if($check_user_demo['is_demo']) {
                $short_path_image = "category/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/category/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);
        }

        return $item;
    }

    public function getUserIDByCategory($category_id='') {
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('user_id')
            ->from($this->getTableName('category'))
            ->where('id='.(int)$category_id)
        ;
        $user_id = $db->setQuery($query)->loadResult();
        return $user_id;
    }


}
