<?php
require_once 'modules/admin/models/PluginCallback.php';

class PluginOlarkCallback extends PluginCallback
{

    var $isLead = false;

    function processCallback()
    {

        if( !isset($_GET['apikey']) || !NE_Lib::authenticateAPIKey($_GET['apikey'])){
            $this->logger->log(4, 'Olark callback - but failed authentication with apikey');
            return;
        }

        $this->logger->log(4, 'Olark callback invoked');
        if (!isset($_POST['data'])) {
            $this->logger->log(4, 'Olark callback - no data');
            return;
        }

        $data = json_decode($_POST['data']);

        try {

            if (isset($data->isLead) && $data->isLead) {
                $this->isLead = true;
            }

            //let's create user - we need to first check email address
            include_once 'modules/clients/models/UserGateway.php';
            $userGateway = new UserGateway();

            $this->logger->log(4,"Searching:".$data->visitor->emailAddress);
            $userId = $userGateway->getUserIdForEmail($data->visitor->emailAddress,false);

            $user = new User($userId);

            //lets make sure this customer isn't admin
            if (($userId != 0) || ($this->isLead)) {
                if ($user->isAdmin()) {
                    $this->logger->log(1, "E-Mail from Olark callback belongs to an admin; Dropping callback.");
                    return;
                }

                //lets create guest user if one doesn't exist
                if ($userId == 0){
                    $user->setEmail($data->visitor->emailAddress);
                    $user->setGroupId(ROLE_GUEST);
                    $user->setDateCreated(date('Y-m-d'));
                    $user->setLastName($data->visitor->fullName);
                    $user->add();
                }

                $this->createNewTicket($user,$data);
            }
        } catch (Exception $ex) {
            $this->logger->log(1,$ex->getMessage());
        }
    }

    function createNewTicket($user,$data=false)
    {
        include_once 'modules/support/models/TicketGateway.php';
        include_once 'modules/support/models/TicketLog.php';
        include_once 'modules/support/models/TicketTypeGateway.php';

        $logs = $data->items;
        $visitor = $data->visitor;
        $conversationId = $data->id;
        $datetimeoflastlog = "";

        $tTimeStamp = date('Y-m-d H-i-s');
        $ticketTypeGateway = new TicketTypeGateway();
        $cTickets = new TicketGateway();


        $lastticketId = $cTickets->getTicketIdWithExternalId($conversationId,$user->getId());
        $cTicket = new Ticket($lastticketId);
        if ($lastticketId > 0) {
            //$datetimeoflastlog = $cTickets->getLastLogDateOfExternallyCreatedTicket($lastticketId);
            //get date stamp of last entry so we don't enter it again
            $datetimeoflastlog = $cTicket->getLastLogDatetime();
        }

        if ($cTickets->GetTicketCount() == 0) {
            $id = $this->settings->get('Support Ticket Start Number');
            $cTicket->setForcedId($id);
        }

        $messageType = $ticketTypeGateway->getExternallyCreatedTicketType();


        //we want to remove any previous tickets with this conversationId
        //since olark will resend all previous msgs of this conversation

        //$cTickets->deleteTicketWithExternalIdForUser($conversationId,$user->getId());
        //we want to check if previous ticket existed
        //GetAllLogsByTicketID

        $cTicket->setUser($user);
        $cTicket->setSubject("Ticket from chat: ".$conversationId);
        $cTicket->SetDateSubmitted($tTimeStamp);
        $cTicket->SetLastLogDateTime($tTimeStamp);
        $cTicket->setMethod(4);
        $cTicket->setExternalId($conversationId);
        $cTicket->SetPriority(2);
        $cTicket->setMessageType($messageType);
        //$cTicket->SetSupportEmail($user->getEmail());

        if ($this->isLead) {
            $cTicket->SetStatus(TICKET_STATUS_WAITINGONTECH);
        } else {
            $cTicket->SetStatus(TICKET_STATUS_CLOSED);
        }

        $cTicket->save();

        $message = "*** Originated Via Chat Msg";
        $message .= "\n\nVisitor: ".$visitor->fullName." (".$visitor->emailAddress.")";
        $message .= "\nIP: ".$visitor->ip;
        if ( isset($visitor->referrer) ) {
            $message .= "\nReferrer: ".$visitor->referrer;
        }
        $message .= "\nOlark Id: ".$visitor->id;

        $city = (!isset($visitor->city)) ? "NA" : $visitor->city;
        $region = (!isset($visitor->region)) ? "NA" : $visitor->region;
        $country = (!isset($visitor->country)) ? "NA" : $visitor->country;
        $countrycode = (!isset($visitor->countryCode)) ? "NA" : $visitor->countryCode;

        $message .= "\nLocation: ".$city." ".$region." ".$country." (".$countrycode.") ";
        $message .= "\nSystem: ".$visitor->operatingSystem." ".$visitor->browser;
        $message = NE_Lib::PrepareForDB($message);

        //this ticket didn't exist before
        if ($lastticketId == 0) {
            $ticketLog = new TicketLog();
            $ticketLog->setMessage(utf8_encode($message));
            $ticketLog->setUserId(0);
            $ticketLog->setPrivate(1);
            $ticketLog->setDeletedName("Olark Callback");
            $ticketLog->setIsExternalEmail(false);
            $ticketLog->setTroubleTicketId($cTicket->getId());
            $ticketLog->save();
            $firstLogId = $ticketLog->getId();
        }


        $first = true;
        $forceTicketOpen = false;
        $lastDate = "";
        foreach ($logs as $entry) {
            $entryDate = date("Y-m-d H:i:s", $entry->timestamp);


            if (($datetimeoflastlog!="") && ($entryDate <= $datetimeoflastlog)) {
                continue;
            }

            $tMessage = NE_Lib::PrepareForDB($entry->body);
            $ticketLog = new TicketLog();
            $ticketLog->setMessage(utf8_encode($tMessage));
            $ticketLog->setMyDateTime($entryDate);
            $lastDate = $entry->timestamp;
            //if staff member we want to add some notification even if we can't get
            //the proper staff member tied to the ticket
            if($entry->kind=="MessageToOperator") {
                $ticketLog->setUserId($user->getId());
            } else {
                $ticketLog->setUserId(0);
                if ($entry->nickname == null) {
                    $ticketLog->setDeletedName("NA");
                    //lets force ticket open since no admin answered ticket
                    $forceTicketOpen = true;
                }else{
                    $ticketLog->setDeletedName($entry->nickname);
                }
            }
            $ticketLog->setIsExternalEmail(false);
            $ticketLog->setTroubleTicketId($cTicket->getId());
            $ticketLog->save();

            if($first){
                $firstDate = $entry->timestamp;
            }
            $first = false;
        }

        //update ticket dates
        //we only need to update the ticket if we had at least one log
        if (!$first) {
            $cTicket->setLastLogDatetime(date("Y-m-d H:i:s", $lastDate));
            $cTicket->setDateSubmitted(date("Y-m-d H:i:s", $firstDate));
            $cTicket->save();
        }

        //this ticket didn't exist before
        if ($lastticketId == 0) {
            //update date of first log entry
            $ticketLog = new TicketLog($firstLogId);
            $ticketLog->setMyDateTime(date("Y-m-d H:i:s", $firstDate));
            $ticketLog->save();
        }

        if($forceTicketOpen) {
            $cTicket->SetStatus(TICKET_STATUS_WAITINGONTECH);
            $cTicket->save();
        }

        //NEED TO CREATE TYPE FOR CHAT LOG CREATED
        /*
        $supportLog = Ticket_EventLog::newInstance(    $user->getId(),
        $cTicket->getId(),
        TICKET_EVENTLOG_CREATED,
        $user->getId()  // $this->user is an empty user object in this context
        );
        $this->logger->addEventLog($supportLog);
        */

        $cTicket->notifyAssignation($user, false);
        return false;
    }
}