<?php

/**
 * Base plugin class.
 */

use HS\Domain\Workspace\Request;

require_once 'Savant2/Plugin.php';

/**
 * HelpSpot Libraries.
 */
require_once cBASEPATH.'/helpspot/lib/api.requests.lib.php';

/**
 * Get the latest forum topics and return as array.
 */
class Savant2_Plugin_Request_Check extends Savant2_Plugin
{
    /**
     * Store result set here.
     *
     *
     * @var ADODB Record Set
     */
    public $rs = [];

    public $_reqid = false;

    public $_req = [];

    /**
     * Central switcher API for the the various public methods.
     *
     *
     * @param string $method The public method to call from this class; all
     * additional parameters will be passed to the called method
     *
     * @return string XHTML generated by the public method.
     */
    public function plugin($method)
    {

        // only pass calls to public methods (i.e., no leading underscore)
        if (substr($method, 0, 1) != '_' && method_exists($this, $method)) {

            // get all arguments and drop the first one (the method name)
            $args = func_get_args();
            array_shift($args);

            // call the method, then return the tidied-up XHTML results
            return call_user_func_array([&$this, $method], $args);
        } else {
            return false;
        }
    }

    /**
     * Set array of req history updates.
     *
     *
     * @param pageid
     *
     * @return none
     */
    public function _setUpdates($key)
    {
        if (! $this->_reqid) {
            $this->accessKeyIsValid($key);
        }

        if ($this->_reqid) {
            $request = Request::with('history.documents')->find($this->_reqid);
            $allStaff = apiGetAllUsersComplete();
            $historyDocs = [];
            $this->rs = [];

            foreach ($request->history as $k => $history) {

                $historyDocs = [];
                if ($history->documents) {
                    foreach ($history->documents as $document) {
                        $doc = $document->toArray();
                        $historyDocs[$doc['xDocumentId']]['sCID'] = $doc['sCID'];
                        $historyDocs[$doc['xDocumentId']]['sFilename'] = $doc['sFilename'];
                        $historyDocs[$doc['xDocumentId']]['xDocumentId'] = $doc['xDocumentId'];
                        $historyDocs[$doc['xDocumentId']]['dtGMTChange'] = $doc['dtGMTChange'];
                        $historyDocs[$doc['xDocumentId']]['sFileMimeType'] = $doc['sFileMimeType'];
                    }
                }

                $v = $history->toArray();

                if ($v['fPublic'] == 1) {
                    $fromemail = ! hs_empty($v['tEmailHeaders']) ? true : false;
                    $this->rs[$k] = $v;
                    $this->rs[$k]['files'] = [];
                    $this->rs[$k]['files_info'] = [];

                    $this->rs[$k]['tNote'] = replaceInlineImages($v['tNote'], $historyDocs, $key, $v['xRequestHistory']);
                    $this->rs[$k]['tNote'] = formatNote($this->rs[$k]['tNote'], $k, ($v['fNoteIsHTML'] ? 'is_html' : 'html'), $fromemail);

                    //Add name
                    if ($this->rs[$k]['xPerson'] > 0) {
                        $this->rs[$k]['firstname'] = hs_htmlspecialchars($allStaff[$this->rs[$k]['xPerson']]['sFname']);
                        $this->rs[$k]['lastname'] = hs_htmlspecialchars($allStaff[$this->rs[$k]['xPerson']]['sLname']);
                    } elseif ($this->rs[$k]['xPerson'] == -1) {
                        $this->rs[$k]['firstname'] = lg('lg_systemnameportal');
                        $this->rs[$k]['lastname'] = '';
                    } else {
                        $this->rs[$k]['firstname'] = $this->_req['sFirstName'];
                        $this->rs[$k]['lastname'] = $this->_req['sLastName'];
                    }

                    //ADD FILE INFORMATION TO RETURNED ARRAY
                    if ($history->documents) {
                        foreach ($history->documents as $document) {
                            $file = $document->toArray();
                            $file['url'] = 'index.php?pg=file&from=3&id='.$file['xDocumentId'].'&reqid='.$key.'&reqhisid='.$k;
                            $file['image'] = '';
                            if (in_array($file['sFileMimeType'], $GLOBALS['imageMimeTypes'])) {
                                $file['image'] = '<a href="'.$file['url'].'"><img src="'.$file['url'].'" alt="'.$v['sFilename'].'" align="top" border="0"></a>';
                            }
                            $this->rs[$k]['files'][] = hs_showMimePortal($file['sFilename']). '<b class="file-name"><a href="'.$file['url'].'">'.$file['sFilename'] .'</a></b>'.$file['image'];
                            $this->rs[$k]['files_info'][] = $file;
                        }
                    }
                }
            }
        } else {
            $this->rs = [];
        }
    }

    /**
     * If closed.
     *
     *
     * @param pageid
     *
     * @return bool
     */
    public function isClosed($key, $timeafterclose)
    {
        if (! $this->_reqid) {
            $this->accessKeyIsValid($key);
        }

        if ($this->_reqid) {
            $time = ! empty($timeafterclose) ? strtotime($timeafterclose, $this->_req['dtGMTClosed']) : $this->_req['dtGMTClosed'];

            if ($this->_req['fOpen'] == 0 && date('U') > $time) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Return array of req history updates.
     *
     *
     * @param none
     *
     * @return array of updates
     */
    public function getPublicUpdates($key)
    {
        if (empty($this->rs)) {
            $this->_setUpdates($key);
        }

        return $this->rs;
    }

    /**
     * Return if the access key is valid or not.
     *
     *
     * @param none
     *
     * @return bool
     */
    public function accessKeyIsValid($key)
    {
        $pkey = parseAccessKey($key);

        if ($pkey['xRequest'] && is_numeric($pkey['xRequest'])) {
            $this->_req = apiGetRequest($pkey['xRequest']);

            //Check if this is a merged request, if so redirect
            if ($this->_req == false && $merged_id = apiCheckIfMergedValid($pkey['xRequest'], $pkey['sRequestPassword'])) {
                $req = apiGetRequest($merged_id);
                //Redirect
                hs_redirect('Location: '.cHOST.'/index.php?pg=request.check&id='.$merged_id.$req['sRequestPassword']);
            }

            //Check if request is valid for this portal
            if (isset($GLOBALS['hs_multiportal'])) {
                if (! $GLOBALS['hs_multiportal']->requestValidForPortal($this->_req)) {
                    return false;
                }
            }

            //Check if request is valid and if password is valid
            if ($this->_req && $this->_req['sRequestPassword'] == $pkey['sRequestPassword']) {
                $this->_reqid = $pkey['xRequest'];

                return $this->_reqid;
            } else {
                return false;
            }
        }
    }

    /**
     * Return the request id.
     *
     *
     * @param none
     *
     * @return int
     */
    public function getRequestID($key)
    {
        if (empty($this->rs)) {
            $this->_setUpdates($key);
        }

        return $this->_reqid;
    }

    /**
     * Return the request details.
     *
     *
     * @param none
     *
     * @return array of request details
     */
    public function getRequestDetails($key)
    {
        if (empty($this->rs)) {
            $this->_setUpdates($key);
        }

        $allstatus = apiGetAllStatus();
        $category = apiGetCategory($this->_req['xCategory']);

        $st = rsToArray($allstatus, 'xStatus');

        $assigneduser = apiGetUser($this->_req['xPersonAssignedTo']);

        $this->_req['sStatus'] = $st[$this->_req['xStatus']]['sStatus'];
        $this->_req['sCategory'] = isset($category['sCategory']) ? $category['sCategory'] : '';
        $this->_req['assignedto_firstname'] = $assigneduser['sFname'];
        $this->_req['assignedto_lastname'] = $assigneduser['sLname'];

        return $this->_req;
    }

    /**
     * Return the request history for a logged in portal user.
     *
     *
     * @param type - return results based on email or on Customer ID
     *
     * @return array of request results
     */
    public function requestHistoryData($type = 1)
    {
        $data = [];

        if ( session()->has('login_sEmail')) {
            return apiPortalRequestHistoryForEmail(session('login_sEmail'), $type);
        } else {
            return $data;
        }
    }

    /**
     * Return the count for request history.
     *
     *
     * @param type - return results based on email or on Customer ID
     *
     * @return array of request results
     */
    public function requestHistoryDataCount($type = 1)
    {
        $data = $this->requestHistoryData($type);

        return count($data);
    }

    /**
     * Return if the visitor is logged in.
     *
     *
     * @param none
     *
     * @return bool
     */
    public function isLoggedIn()
    {
        //Confirm if accessing a specific request that the ID is for this user. This makes sure logged in users can only access their requests.
        $data = $this->requestHistoryData(hs_setting('cHD_PORTAL_LOGIN_SEARCHONTYPE'));
        if (isset($_GET['id'])) {
            $id = parseAccessKey($_GET['id']);
            if ($_GET['pg'] == 'request.check' && ! in_array($id['xRequest'], array_keys($data))) {
                return false;
            }
        }

        if (session()->has('login_xLogin') && session('login_ip') == hs_clientIP()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Return the email of the logged in user.
     *
     *
     * @param none
     *
     * @return bool
     */
    public function loggedInEmailOrUsername()
    {
        return session('login_username', session('login_sEmail', ''));
    }
}
