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

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

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

        include(ABSPATH . "wp-includes/pluggable.php");
        $user_plugin =  parent::save($data); // TODO: Change the autogenerated stub
        $open_source_user_id = isset($user_plugin->open_source_user_id)?$user_plugin->open_source_user_id:0;
        $user_pass = isset($data['user_pass'])?$data['user_pass']:'';
        $user_name = isset($data['user_name'])?$data['user_name']:'';
        $email = isset($data['email'])?$data['email']:'';
        $first_name = isset($data['first_name'])?$data['first_name']:'';
        $last_name = isset($data['last_name'])?$data['last_name']:'';
        $query = $this->_db->getQuery(true);
        if(self::user_id_exists($open_source_user_id)) {
            $user_id = $open_source_user_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);
            }
        } else {
            $user_id = wp_insert_user( array(
                'user_login' => $user_name,
                'user_pass' => trim($user_pass)!=''?$user_pass:'123456',
                'user_email' => $email,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'display_name' => Utility::get_full_name($first_name, $last_name),
            ));

            $query->clear()
                ->update($this->getTableName('user'))
                ->set('open_source_user_id='.(int)$user_id)
                ->where('id='.(int)$user_plugin->id)
            ;
            $this->_db->setQuery($query)->execute();

        }
        

        return $user_plugin;
    }

    public static function user_id_exists($user){

        global $wpdb;

        $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users WHERE ID = %d", $user));

        if($count == 1){ return true; }else{ return false; }

    }

    public function getItem($id = 0)
    {
        $item =  parent::getItem($id); // TODO: Change the autogenerated stub
        global $wpdb;
        $user_name = $wpdb->get_var($wpdb->prepare("SELECT user_login FROM $wpdb->users WHERE ID = %d", $item->open_source_user_id));
        $item->user_name = $user_name;
        return $item;
    }

    public function getUserInfo() {
        $user = wp_get_current_user();
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('*')
            ->from($this->getTableName('user'))
            ->where('open_source_user_id='.(int)$user->ID)
        ;
        $user_plugin = $db->setQuery($query)->loadObject();
        $user->user_plugin = $user_plugin;
        return $user;
    }

    public function checkOldUserPass($data = array()) {
        $dataObj = isset($data['dataObj'])?$data['dataObj']:array();
        $id = isset($data['id'])?$data['id']:array();
        $old_pass = isset($dataObj['old_pass'])?$dataObj['old_pass']:'';
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('open_source_user_id')
            ->from($this->getTableName('user'))
            ->where('id='.(int)$id)
        ;
        $user_id = $db->setQuery($query)->loadResult();
        global $wpdb;
        $user_pass = $wpdb->get_var($wpdb->prepare("SELECT user_pass FROM $wpdb->users WHERE ID = %s", $user_id));

        if(wp_check_password($old_pass, $user_pass, $user_id)) {
            return true;
        }
        return false;
    }

}
