<?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;

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

    public function getUserInfo() {
        if(is_user_logged_in()) {

            $user_id = isset($_SESSION['user_id']) ? sanitize_text_field($_SESSION['user_id']) : '';
            $user_login = isset($_SESSION['user_login']) ? sanitize_text_field($_SESSION['user_login']) : '';
            $user = wp_get_current_user();
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('user.*, groupuser.alias AS group_user_alias')
                ->from($this->getTableName('user').' AS user')
                ->leftJoin($this->getTableName('groupuser').' AS groupuser ON groupuser.id=user.group_user_id')
                ->where('user.open_source_user_id='.(int)$user_id)
            ;
            $user_plugin = $db->setQuery($query)->loadObject();
            $query->clear()
                ->select('*')
                ->from($this->getTableName('gallery'))
                ->where('type='.$query->quote('vendor'))
                ->where('object_id='.(int)$user_plugin->id)
            ;
            $user_plugin->gallery = $db->setQuery($query)->loadObjectList();
            if(isset($user_plugin->params) && $user_plugin->params) {
                $register = new Registry();
                $register->loadString($user_plugin->params);
                $user_plugin->params = $register;
            }

            $user->user_plugin = $user_plugin;
            return $user;
        }
        return array();
    }

    public function editInfoUserAccount($data=array()) {
        if(!function_exists('wp_get_current_user')) {
            include(ABSPATH . "wp-includes/pluggable.php");
        }
        $first_name = isset($data['first_name'])?$data['first_name']:'';
        $last_name = isset($data['last_name'])?$data['last_name']:'';
        $user_name = isset($data['user_name'])?$data['user_name']:'';
        $email = isset($data['email'])?$data['email']:'';
        $address = isset($data['address'])?$data['address']:'';
        $phonecode = isset($data['phonecode'])?$data['phonecode']:'';
        $countrycode = isset($data['countrycode'])?$data['countrycode']:'';
        $mobile = isset($data['mobile'])?$data['mobile']:'';
        $gender = isset($data['gender'])?$data['gender']:'';
        $birth_day = isset($data['birth_day'])?$data['birth_day']:'';
        $company = isset($data['company'])?$data['company']:'';
        $business = isset($data['business'])?$data['business']:'';
        $description = isset($data['description'])?$data['description']:'';
        $user_pass = isset($data['user_pass'])?$data['user_pass']:'';
        $country = isset($data['country'])?$data['country']:'';
        $city = isset($data['city'])?$data['city']:'';
        $state = isset($data['state'])?$data['state']:'';
        $postcode = isset($data['postcode'])?$data['postcode']:'';
        $address_bill = isset($data['address_bill'])?$data['address_bill']:'';
        $image = isset($data['image'])?$data['image']:'';

        $user_id = isset($_SESSION['user_id'])?$_SESSION['user_id']:'';

        $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();

        $db= Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->update($this->getTableName('user'))
            ->set('first_name='.$query->quote($first_name))
            ->set('last_name='.$query->quote($last_name))
            ->set('email='.$query->quote($email))
            ->set('address='.$query->quote($address))
            ->set('phonecode='.$query->quote($phonecode))
            ->set('countrycode='.$query->quote($countrycode))
            ->set('countrycode='.$query->quote($countrycode))
            ->set('mobile='.$query->quote($mobile))
            ->set('gender='.$query->quote($gender))
            ->set('birthday='.$query->quote($birth_day))
            ->set('company='.$query->quote($company))
            ->set('business='.$query->quote($business))
            ->set('description='.$query->quote($description))
            ->set('country='.$query->quote($country))
            ->set('city='.$query->quote($city))
            ->set('state='.$query->quote($state))
            ->set('postcode='.(int)$postcode)
            ->set('address_bill='.$query->quote($address_bill))
            ->set('image='.$query->quote($image))
            ->set('params='.$query->quote($data['params']))
            ->where('open_source_user_id='.(int)$user_id)
        ;

        $db->setQuery($query)->execute();

        $user = $this->getUserInfo();

        $galleryModel = Model::getInstance('gallery');

        $gallery=Factory::getInput()->files->get('gallery','','raw');
        if($gallery) {
            for($i=0;$i<count($gallery["name"]);$i++) {
                $query->clear()
                    ->delete($this->getTableName('gallery'))
                    ->where('type='.$query->quote('vendor'))
                    ->where('object_id='.(int)$user->data->user_plugin->id)
                    ->where('name='.$query->quote($gallery['name'][$i]))
                ;
                $db->setQuery($query)->execute();
            }

        }

        if($gallery && count($gallery["name"]))for($i=0;$i<count($gallery["name"]);$i++){
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $gallery['name'][$i];
            $short_path_image = "upload/vendor/gallery/$name";
            $new_file_image_vendor_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_vendor_path, FileAlias::read($gallery['tmp_name'][$i]))) {
                throw new Exception(Text::_("can not upload image gallery"));
            }

            $data_gallery=array(
                "id"=>0,
                "type"=>"vendor",
                "object_id"=>$user->data->user_plugin->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);
        }

        global $wpdb;
        $wpdb->query($wpdb->prepare("UPDATE $wpdb->users SET user_login = %s  WHERE ID = $user_id", $user_name));
        $wpdb->query($wpdb->prepare("UPDATE $wpdb->users SET user_nicename = %s  WHERE ID = $user_id", $user_name));
        $wpdb->query($wpdb->prepare("UPDATE $wpdb->users SET user_email = %s  WHERE ID = $user_id", $email));
        $wpdb->query($wpdb->prepare("UPDATE $wpdb->users SET display_name = %s  WHERE ID = $user_id", Utility::get_full_name($first_name, $last_name)));

        if(trim($user_pass) != '') {
            wp_set_password($user_pass,$user_id);
        }


    }







}
