<?php

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

class JSSTuser
{

    private $jsst_currentuser = null;
    public $jsst_socialmedia = null;

    function __construct()
    {
        if (is_user_logged_in()) { // wp user logged in
            $jsst_wpuserid = get_current_user_id();
            if (!is_numeric($jsst_wpuserid))
                return false;
            $jsst_query = "SELECT * FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($jsst_wpuserid);
            $jsst_currentuser = jssupportticket::$_db->get_row($jsst_query);
            $jsst_jssupportticket_registerform = JSSTrequest::getVar('jsst_support_register_nonce', 'post', '');
            $jsst_registerform = JSSTrequest::getVar('jssupportticket_registerform', 'post', 0);
            if ($jsst_currentuser == '' and ($jsst_jssupportticket_registerform == '' && $jsst_registerform == 0)) {// inserting a record in our table
                $jsst_userdata = get_userdata($jsst_wpuserid);
                $jsst_profile['id'] = '';
                // User display name
                $jsst_user_first = get_user_meta($jsst_wpuserid, 'first_name', true);
                $jsst_user_last = get_user_meta($jsst_wpuserid, 'last_name', true);
                if ($jsst_user_first && $jsst_user_last) {
                    $jsst_display_name = sprintf(
                        /* translators: %1$s: user first name, %2$s: user last name */
                        _x('%1$s %2$s', 'Display name based on first name and last name', 'js-support-ticket'),
                        $jsst_user_first,
                        $jsst_user_last
                    );
                } elseif ($jsst_user_first) {
                    $jsst_display_name = $jsst_user_first;
                } elseif ($jsst_user_last) {
                    $jsst_display_name = $jsst_user_last;
                } else {
                    $jsst_display_name = $jsst_userdata->display_name;
                }

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

                $jsst_row = JSSTincluder::getJSTable('users');
                $jsst_data['id'] = '';
                $jsst_data['wpuid'] = $jsst_wpuserid;
                $jsst_data['name'] = $jsst_profile['name'];
                $jsst_data['display_name'] = $jsst_display_name;
                $jsst_data['user_nicename'] = $jsst_userdata->user_nicename;
                $jsst_data['user_email'] = $jsst_userdata->user_email;
                $jsst_data['issocial'] = 0;
                $jsst_data['socialid'] = null;
				$jsst_data['created'] = date_i18n('Y-m-d H:i:s');
                $jsst_data['status'] = 1;
                $jsst_data['autogenerated'] = 1;
                $jsst_row->bind($jsst_data);
                $jsst_row->store();

                if (is_numeric($jsst_row->id)) {
                    $jsst_query = "SELECT * FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE id = " . esc_sql($jsst_row->id);
                    $jsst_currentuser = jssupportticket::$_db->get_results($jsst_query);
                }
            }
            $this->jsst_currentuser = $jsst_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
                    $jsst_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->jsst_currentuser = jssupportticket::$_db->get_row($jsst_query);

                    $this->jsst_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->jsst_currentuser == null && !is_user_logged_in()) { // current user is guest
            return true;
        } else {
            return false;
        }
    }

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

    function uid()
    {

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

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

    function wpuid()
    {

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

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

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

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


    function isJSsupportticketUser()
    {
        if (is_user_logged_in()) { // wp user logged in
            $jsst_wpuserid = JSSTincluder::getObjectClass('user')->uid();
            if (!is_numeric($jsst_wpuserid))
                return false;
            $jsst_query = "SELECT COUNT(id) FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($jsst_wpuserid);
            $jsst_result = jssupportticket::$_db->get_results($jsst_query);
            if ($jsst_result > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            if (isset($_COOKIE['jssupportticket-socialid']) && !empty($_COOKIE['jssupportticket-socialid'])) { // social user is logged in
                $jsst_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
                $jsst_result = jssupportticket::$_db->get_results($jsst_query);
                if ($jsst_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($jsst_userid)
    {
        if (!is_numeric($jsst_userid)) return false;
        $jsst_query = "SELECT id FROM `".jssupportticket::$_db->prefix."js_ticket_users` WHERE wpuid = " . esc_sql($jsst_userid);
        $jsst_uid = jssupportticket::$_db->get_results($jsst_query);
        return $jsst_uid;
    }

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

    function deleteUserRecords($jsst_uid, $jsst_is_delete_user = false) {
        if (!is_numeric($jsst_uid)) return false;

        $jsst_model = JSSTincluder::getJSModel('ticket');
        $jsst_query = "SELECT id, ticketid FROM `" . jssupportticket::$_db->prefix . "js_ticket_tickets` WHERE wpuid = " . esc_sql($jsst_uid);
        $jsst_tickets = jssupportticket::$_db->get_results($jsst_query);

        do_action('jsst_addon_deletequery_for_user');
        $jsst_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($jsst_uid);
        jssupportticket::$_db->query($jsst_query);

        do_action('jsst_reset_aadon_query');
        $jsst_query = "DELETE user FROM `" . jssupportticket::$_db->prefix . "js_ticket_users` AS user WHERE wpuid = " . esc_sql($jsst_uid);
        
        if (jssupportticket::$_db->query($jsst_query)) {
            // --- START FILESYSTEM FIX ---
            global $wp_filesystem;
            if (!function_exists('wp_handle_upload')) {
                do_action('jssupportticket_load_wp_file');
            }
            if ( ! WP_Filesystem() ) {
                return false;
            }
            $jsst_wp_filesystem = $wp_filesystem;

            $jsst_maindir = wp_upload_dir();
            $jsst_path = $jsst_maindir['basedir'] . '/' . jssupportticket::$_config['data_directory'] . '/attachmentdata/ticket';

            foreach ($jsst_tickets as $jsst_key) {
                $jsst_userpath = $jsst_path . '/' . $jsst_key->ticketid;

                // Replaced glob, is_file, and rmdir with WP_Filesystem delete
                if ($jsst_wp_filesystem->exists($jsst_userpath)) {
                    $jsst_wp_filesystem->delete($jsst_userpath, true); // true means recursive (deletes files inside too)
                }
            }
            return true;
        }
        return false;
    }

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

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

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

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

}

