<?php

if (!defined('ABSPATH'))
    die('Restricted Access');

class JSSTuser
{

    private $currentuser = null;
    public $socialmedia = null;

    function __construct()
    {
        if (is_user_logged_in()) { // wp user logged in
            $wpuserid = get_current_user_id();
            if (!is_numeric($wpuserid))
                return false;
            $query = "SELECT * FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($wpuserid);
            $currentuser = jssupportticket::$_db->get_row($query);
            $jssupportticket_registerform = JSSTrequest::getVar('jsst_support_register_nonce', 'post', '');
            $registerform = JSSTrequest::getVar('jssupportticket_registerform', 'post', 0);
            if ($currentuser == '' and ($jssupportticket_registerform == '' && $registerform == 0)) {// inserting a record in our table
                $userdata = get_userdata($wpuserid);
                $profile['id'] = '';
                // User display name
                $user_first = get_user_meta($wpuserid, 'first_name', true);
                $user_last = get_user_meta($wpuserid, 'last_name', true);
                if ($user_first && $user_last) {
                    // Translators: %1$s is the user's first name, %2$s is the user's last name.
                    $display_name = sprintf(
                        _x('%1$s %2$s', 'Display name based on first name and last name', 'js-support-ticket' ),
                        $user_first,
                        $user_last
                    );
                } elseif ($user_first) {
                    $display_name = $user_first;
                } elseif ($user_last) {
                    $display_name = $user_last;
                } else {
                    $display_name = $userdata->display_name;
                }

                $profile['name'] = $display_name;
                if ($userdata->display_name == '') {
                    $profile['name'] = $userdata->user_nicename;
                }
                $profile['email'] = $userdata->user_email;
                $profile['wpuid'] = $wpuserid;
                $profile['created'] = date_i18n('Y-m-d H:i:s');
                $profile['status'] = 1;
                $profile['autogenerated'] = 1;

                $row = JSSTincluder::getJSTable('users');
                $data['id'] = '';
                $data['wpuid'] = $wpuserid;
                $data['name'] = $profile['name'];
                $data['display_name'] = $display_name;
                $data['user_nicename'] = $userdata->user_nicename;
                $data['user_email'] = $userdata->user_email;
                $data['issocial'] = 0;
                $data['socialid'] = null;
				$data['created'] = date_i18n('Y-m-d H:i:s');
                $data['status'] = 1;
                $data['autogenerated'] = 1;
                $row->bind($data);
                $row->store();

                if (is_numeric($row->id)) {
                    $query = "SELECT * FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE id = " . esc_sql($row->id);
                    $currentuser = jssupportticket::$_db->get_results($query);
                }
            }
            $this->currentuser = $currentuser;
        } else { // wp user is not logged in
//            do_action('jsst_userid_by_sociallogin', $this);

            if (in_array('sociallogin', jssupportticket::$_active_addons)){
                if (isset($_COOKIE['jssupportticket-socialid']) && !empty($_COOKIE['jssupportticket-socialid'])) { // social user is logged in
                    $query = "SELECT * FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE socialid = '" . jssupportticket::JSST_sanitizeData($_COOKIE['jssupportticket-socialid']) . "'"; // JSST_sanitizeData() function uses wordpress santize functions
                    $this->currentuser = jssupportticket::$_db->get_row($query);

                    $this->socialmedia = isset($_COOKIE['jssupportticket-socialmedia']) ? jssupportticket::JSST_sanitizeData($_COOKIE['jssupportticket-socialmedia']) : ''; // JSST_sanitizeData() function uses wordpress santize functions
                }
            }
        }
    }

    function isguest()
    {
        if (isset($_COOKIE['jssupportticket-socialid']) && !empty($_COOKIE['jssupportticket-socialid'])) {
            if (in_array('sociallogin', jssupportticket::$_active_addons)) {
                return false;
            } else {
                return true;
            }
        } elseif ($this->currentuser == null && !is_user_logged_in()) { // current user is guest
            return true;
        } else {
            return false;
        }
    }

    function isdisabled()
    {
        if ($this->currentuser != null && $this->currentuser->status == 0) { // current user is disabled
            return true;
        } else {
            return false;
        }
    }

    function uid()
    {

        if ($this->currentuser != null) {

            return $this->currentuser->id;
        }
    }

    function wpuid()
    {

        if ($this->currentuser != null) {

            return $this->currentuser->wpuid;
        }
    }

    function emailaddress()
    {
        if ($this->currentuser == null) { // current user is guest
            return false;
        } else {
            return $this->currentuser->emailaddress;
        }
    }

    function fullname()
    {
        if ($this->currentuser == null) { // current user is guest
            return false;
        } else {
            $name = $this->currentuser->name;
			if($name == ""){
				$name = $this->currentuser->display_name;
			}
			if($name == ""){
				$name = $this->currentuser->user_nicename;
			}
			if($name == ""){ // get from wordpress
				$current_user = wp_get_current_user();
				if(0 != $current_user->ID){
					$name = $current_user->user_firstname.' '.$current_user->user_lastname;
					if($name == ""){
						$name = $current_user->display_name;
					}
				}
			}
            return $name;
        }
    }


    function isJSsupportticketUser()
    {
        if (is_user_logged_in()) { // wp user logged in
            $wpuserid = JSSTincluder::getObjectClass('user')->uid();
            if (!is_numeric($wpuserid))
                return false;
            $query = "SELECT COUNT(id) FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($wpuserid);
            $result = jssupportticket::$_db->get_results($query);
            if ($result > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            if (isset($_COOKIE['jssupportticket-socialid']) && !empty($_COOKIE['jssupportticket-socialid'])) { // social user is logged in
                $query = "SELECT COUNT(id) FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE socialid = '" . jssupportticket::JSST_sanitizeData($_COOKIE['jssupportticket-socialid']) . "'"; // JSST_sanitizeData() function uses wordpress santize functions
                $result = jssupportticket::$_db->get_results($query);
                if ($result > 0) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    function isSocialLogin()
    {
        if (isset($_COOKIE['jssupportticket-socialid']) && !empty($_COOKIE['jssupportticket-socialid'])) {
            return true;
        } else {
            return false;
        }
    }

    function getjssupportticketuidbyuserid($userid)
    {
        if (!is_numeric($userid)) return false;
        $query = "SELECT id FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($userid);
        $uid = jssupportticket::$_db->get_results($query);
        return $uid;
    }

    function getJSSTCurrentUser(){
        return $this->currentuser;
    }

    function deleteUserRecords($uid , $is_delete_user = false ){
        if(! is_numeric($uid))
            return false;
        $model = JSSTincluder::getJSModel('ticket');
        $query = "SELECT id , ticketid FROM `".jssupportticket::$_db->prefix."js_ticket_tickets` WHERE wpuid = ".esc_sql($uid);
        $tickets = jssupportticket::$_db->get_results($query);

        do_action('jsst_addon_deletequery_for_user');
        $query = "DELETE  ticket, reply,attachment,activity_log,erasedatarequests ". jssupportticket::$_addon_query['select'] . "
            FROM `". jssupportticket::$_db->prefix ."js_ticket_users` AS user
            LEFT JOIN `". jssupportticket::$_db->prefix ."js_ticket_tickets` AS ticket ON ticket.uid = user.id
            LEFT JOIN `". jssupportticket::$_db->prefix ."js_ticket_replies` AS reply ON reply.ticketid = ticket.id
            LEFT JOIN `". jssupportticket::$_db->prefix ."js_ticket_attachments` AS attachment ON attachment.ticketid = ticket.id
            LEFT JOIN `". jssupportticket::$_db->prefix ."js_ticket_activity_log` AS activity_log ON activity_log.uid = user.id
            LEFT JOIN `". jssupportticket::$_db->prefix ."js_ticket_erasedatarequests` AS erasedatarequests ON erasedatarequests.uid = user.id
            "
            . jssupportticket::$_addon_query['join'] . "
            WHERE user.id = " . esc_sql($uid);
        jssupportticket::$_db->query($query);
        do_action('reset_jsst_aadon_query');
        $query = "DELETE user FROM `".jssupportticket::$_db->prefix."js_ticket_users` AS user WHERE wpuid = " . esc_sql($uid);
        if(jssupportticket::$_db->query($query)){
            $maindir = wp_upload_dir();
            $basedir = $maindir['basedir'];
            $datadirectory = jssupportticket::$_config['data_directory'];
            $path = $basedir . '/' . $datadirectory. '/attachmentdata/ticket';
            foreach ($tickets as $key) {
                $userpath = $path . '/' . $key->ticketid;
                $files = glob($userpath.'/*');      
                // Deleting all the files in the list 
                foreach($files as $file) { 
                    if(is_file($file))  {
                        wp_delete_file($file);  
                    }
                }
                rmdir($userpath);
            }
            return true;
        }else{
            return false;
        }
    }

    function getUserIDByWPUid($wpuid) {
        if (!is_numeric($wpuid))
            return false;

        $query = "SELECT id FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($wpuid);
        $result = jssupportticket::$_db->get_var($query);
        return $result;
    }

    function getUserNameByUid($uid) {
        if (!is_numeric($uid))
            return false;

        $query = "SELECT display_name,user_nicename FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE id = " . esc_sql($uid);
        $result = jssupportticket::$_db->get_row($query);
        return $result;
    }

}

