<?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 WpBookingProAdmin\app\helpers\AdminHelper;

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

    public function save($data = array())
    {

        $customer =  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 = "customer/images/cover/$name";
                $new_file_image_customer_path = WP_CONTENT_DIR . '/uploads/sites/' . $check_user_demo['blog_id'].DS.$short_path_image;
            } else {
                $short_path_image = "upload/customer/images/cover/$name";
                $new_file_image_customer_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;
            }

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

    public function getItem($id = 0)
    {
        $customer =  parent::getItem($id); // TODO: Change the autogenerated stub
        $query= $this->_db->getQuery(true);
        if(!empty((array)$customer)) {
            $query->clear()
                ->select('country.countryname')
                ->from($this->getTableName('country').' AS country')
                ->where('country.phonecode='.(int)$customer->phonecode)
                ->where('country.countrycode='.$query->quote($customer->countrycode))
            ;
            $customer->country_name = $this->_db->setQuery($query)->loadResult();
        }

        return $customer;
    }
}
