<?php
ini_set('error_reporting', E_ALL);

$mailConfig = array(
    "bugs" => array(
        "email" => "remy.apfelbacher@plusserver.com",
        "subject" => "NiceReply Error",
    ),
);

$mailreceiver = "christian.liebelt@plusserver.com";
$mailsubject = "Nicereply API PlusServer";

$apiUrl = 'https://api.nicereply.com/v1/csat/ratings';
$apiKey = '7966128f93b4b2b41e4ce899c4152a9785abf340';

$config = array(
    "proxy" => array(
        "url" => "webproxy.ps-intern.de",
        "port" => 3128,
    ),
);

/*
 * Allowed URL schemas:
 * http://rate.plusserver.com/<staff-id|staff-username>/<ticketId>/<customerId>?score=<g|o|p>
 *
 * staff-id or staff-username:
 * is the username found in nicereply for the user. We try to keep this in sync with RT.
 *
 * ticketid:
 * id of the ticket from the ticket system no real relevance for NiceReply
 *
 * customerId:ff
 * the customerId from AX with companyId prefix, e.g. 002/201629
 *
 * score:
 * <ul>
 * <li>g = good</li>
 * <li>o = ok</li>
 * <li>p = poor</li>
 * </ul>
 */

$route = isset($_GET['route']) ? $_GET['route'] : '';

$baseUrl = preg_replace('~[?&].*~', '', str_replace($route, '', $_SERVER['REQUEST_URI']));
// $baseUrl = "/"; // TODO ????
$route = (empty($_GET['route'])) ? array() : explode('/', trim($_GET['route'], '/\\'));

switch ($_SERVER['SERVER_NAME']) {
    case "rate.plusserver.com":
    case "localhost":
        $LANG = "DE";
        $survey = 9535;
        break;
    case "rate.nimblu.com":
        $LANG = "DE";
        $survey = 11198;
        break;
    default:
        header('HTTP/1.1 404 Not Found');
        die('The page is not available');
}
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="icon" href="/images/favicon.ico" type="image/x-icon">
<title>Feedback</title>

<link type="text/css" href="<?php echo $baseUrl ?>css/rate.css"
    rel="stylesheet">
<link type="text/css" href="<?php echo $baseUrl ?>css/smiley.css"
    rel="stylesheet">
</head>
<body>

    <div id="rate_wrapper">

<?php
if (!$route) {
    echo "<div class ='rate_body error'>";
    echo "Wrong URL";
    echo "</div>";
} else {
    $customerid = null;

    $userName = htmlspecialchars(trim($route[0]), ENT_QUOTES);
    $ticketId = (isset($route[1])) ? htmlspecialchars(trim($route[1]), ENT_QUOTES) : null;
    if (isset($route[2]) && isset($route[3])) {
        $customerid = htmlspecialchars(trim($route[2]), ENT_QUOTES) . "/" . htmlspecialchars(trim($route[3]), ENT_QUOTES);
    } elseif (isset($route[2]) && !isset($route[3])) {
        $customerid = htmlspecialchars(trim($route[2]), ENT_QUOTES);
    }
    $score = (isset($_GET['score'])) ? htmlspecialchars(trim($_GET['score']), ENT_QUOTES) : null;
    if (!$score) {
        $score = (isset($_POST['score'])) ? htmlspecialchars(trim($_GET['score']), ENT_QUOTES) : null;
    }

    $url = ($ticketId) ? $baseUrl . $userName . '/' . $ticketId . '/' . $customerid : $baseUrl . $userName;

    switch ($LANG) {
        case "DE":
            $HEAD = '<h1>Wie hilfreich war meine Antwort für Sie?</h1>';
            $BLOCK_NICE = "<a class='simple-button great' href='" . $url . "?score=g'><span class='face great'></span><span class='bigone'>Sehr gut</span><span class='data'>Ich bin begeistert!</span></a>";
            $BLOCK_NORMAL = "<a class='simple-button normal' href='" . $url . "?score=o'><span class='face normal'></span><span class='bigone'>Normal</span><span class='data'>War in Ordnung!</span></a>";
            $BLOCK_POOR = "<a class='simple-button poor' href='" . $url . "?score=p'><span class='face poor'></span><span class='bigone'>Nicht gut</span><span class='data'>Ich bin enttäuscht!</span></a>";
            $COMMENT_HEAD_NICE = "<label for='Ratings_comment'>Vielen Dank für Ihre Zeit!<br>Es freut mich sehr, dass ich Sie mit meiner Antwort begeistern konnte.<br>Darf ich erfahren, was Ihnen so gut gefallen hat?<br><br>Hinterlassen Sie auf Wunsch Ihren Kommentar einfach hier:<br></label>";
            $COMMENT_HEAD_NORMAL = "<label for='Ratings_comment'>Vielen Dank für Ihre Zeit!<br>Nur zufrieden ist nicht gut genug für mich.<br>Bitte helfen Sie mir dabei, Ihre Erfahrung mit unserem Service beim nächsten Mal zu verbessern.<br><br>Hinterlassen Sie auf Wunsch Ihren Kommentar einfach hier:</label>";
            $COMMENT_HEAD_POOR = "<label for='Ratings_comment'>Es tut mir sehr leid, dass Sie mit unserem Service dieses Mal keine gute Erfahrung gemacht haben.<br>Ich würde mich sehr freuen, wenn Sie mir den Grund für Ihre Enttäuschung mitteilen könnten, so dass dies nicht noch einmal passiert.<br><br>Hinterlassen Sie auf Wunsch Ihren Kommentar einfach hier:</label>";
            $THANK_YOU_NICE = "Vielen Dank, dass Sie sich die Zeit genommen und mir ein Feedback hinterlassen haben.<br>Es wird mir helfen Sie weiterhin mit unserem Service zu begeistern.";
            $THANK_YOU_NORMAL = "Vielen Dank, dass Sie sich die Zeit genommen und mir ein Feedback hinterlassen haben.<br>Dadurch geben Sie mir die Möglichkeit unseren Service für Sie ständig zu verbessern.";
            $THANK_YOU_POOR = "Vielen Dank, dass Sie sich die Zeit genommen und mir ein Feedback hinterlassen haben.<br>Dadurch geben Sie mir die Möglichkeit, unseren Service für Sie zu optimieren.";
            $SEND_RATING = "Feedback senden";
            break;

        case "EN":
            $HEAD = "<h1>How nice was my reply?</h1>";
            $BLOCK_NICE = "<a class='simple-button great' href='" . $url . "?score=g'><span class='face great'></span><span class='bigone'>Very nice</span><span class='data'>Great and helpful, nice job!</span></a>";
            $BLOCK_NORMAL = "<a class='simple-button normal' href='" . $url . "?score=o'><span class='face normal'></span><span class='bigone'>Normal</span><span class='data'>Average, could have been better.</span></a>";
            $BLOCK_POOR = "<a class='simple-button poor' href='" . $url . "?score=p'><span class='face poor'></span><span class='bigone'>Poor</span><span class='data'>I am sad now :(</span></a>";
            $COMMENT_HEAD_NICE = "<label for='Ratings_comment'>Thanks for your time!<br>I'm pleased to know I made you happy.<br>Care to tell me what made your experience so great?<br><br>Leave a comment below if you wish to.<br></label>";
            $COMMENT_HEAD_NORMAL = "<label for='Ratings_comment'>Thanks for your time!<br>Satisfied isn't good enough for me.<br>Can you let me know what I can do to improve your experience next time?<br><br>Leave a comment below if you wish to.</label>";
            $COMMENT_HEAD_POOR = "<label for='Ratings_comment'>I'm sorry I have made you unhappy.<br>Can you please provide more information below so I know how to improve my service to you?</label>";
            $THANK_YOU_NICE = "Thanks for taking the time to give me feedback!<br>It helps me to keep providing you with great service.";
            $THANK_YOU_NORMAL = "Thanks for taking the time to give me feedback!<br>It helps me to keep improving the service I provide to you.";
            $THANK_YOU_POOR = "Thanks for taking the time to give me feedback.<br>It will help me to improve the service I provide.";
            $SEND_RATING = "Send rating";
            break;
    }

    if (!$score) {
        echo "\n" . $HEAD;
        echo "\n" . $BLOCK_NICE;
        echo "\n" . $BLOCK_NORMAL;
        echo "\n" . $BLOCK_POOR;
    } else {
        if (!isset($_POST['comment'])) {
            if (!in_array($score, array(
                'g',
                'o',
                'p',
            ))) {
                // when no comment and no rating have been specified
                $location = ($ticketId) ? "{$baseUrl}{$userName}/{$ticketId}/$customerid" : "{$baseUrl}{$userName}";
                header("Location: $location");
            }
            echo "<div class='center-face " . $score . "'></div>";
            echo "<form name='rateform' action='" . $_SERVER['REQUEST_URI'] . "' method='post'>";
            echo "<div class='rate_body'>";
            try {
                if ($score == 'g') {
                    echo "\n" . $COMMENT_HEAD_NICE;
                } elseif ($score == 'o') {
                    echo "\n" . $COMMENT_HEAD_NORMAL;
                } elseif ($score == 'p') {
                    echo "\n" . $COMMENT_HEAD_POOR;
                } else {
                    throw new InvalidArgumentException("Invalid score.");
                }
            } catch (Exception $e) {
                error_log("problem occured for " . $_SERVER['REQUEST_URI'] . ", thus redirecting: " . $e);
                // when no comment and no rating have been specified
                $location = ($ticketId) ? "{$baseUrl}{$userName}/{$ticketId}/$customerid" : "{$baseUrl}{$userName}";
                header("Location: $location");
                exit();
            }
            ?>
        <textarea id="Ratings_comment" class="simple" name="comment"></textarea>
    </div>
    <input type="hidden" name="score" value="<?php echo $score; ?>" />
    <button type="submit"><?php echo $SEND_RATING; ?></button>
    </form>
    <script type="text/javascript">
        window.onbeforeunload = function(){
            document.getElementsByName("rateform")[0].submit();
        }
    </script>

         <?php
} else {
            // we have a comment and a rating, let's go
            $NiceReplyRatingId = setRating($apiUrl, $apiKey, $config, $survey, $customerid, $userName, $ticketId, $score);
            $result = updateRating($apiUrl, $apiKey, $config, $NiceReplyRatingId, $_POST['comment'], $score);
            if (!$result) {
                $text = "AgentID: " . $userName . "\nTicket: " . $ticketId . "\nCustomer: " . $customerid . "\nRatingpage: " . $page . "\nComment: " . (isset($_POST['comment']) ? $_POST['comment'] : "") . "\n";
                mail($mailConfig->bugs->email, $mailConfig->bugs->subject, $text, "From: Nicereply Wrapper <$mailConfig->bugs->email>");
            } else {
                // do nothing
            }
            echo "<div class ='rate_body success'>";
            if ($score == 'g') {
                echo "\n" . $THANK_YOU_NICE;
            } elseif ($score == 'o') {
                echo "\n" . $THANK_YOU_NORMAL;
            } elseif ($score == 'p') {
                echo "\n" . $THANK_YOU_POOR;
            }
            echo "</div>";
        }
    }
}

/**
 *
 * @param
 *            apiUrl
 * @param
 *            apiKey
 * @param
 *            config
 * @param
 *            page
 * @param
 *            customerid
 * @param
 *            userName
 * @param
 *            ticketId
 * @param
 *            score
 */
function setRating($apiUrl, $apiKey, $config, $survey, $customerid, $userName, $ticketId, $score)
{
    global $mailreceiver, $mailsubject;
    // params for api call
    $urlscore = getScoreForAPI($score);
    if (trim($customerid) == '' || $customerid == null) {
        $customerId_checked = "unknown";
    } else {
        $customerId_checked = trim($customerid);
    }
    $data = [
        'survey_id' => $survey,
        'score' => $urlscore,
        'from' => $customerId_checked,
        'comment' => isset($_POST['comment']) ? $_POST['comment'] : "",
        'ticket' => $ticketId,
        'user' => [
            'username' => $userName,
        ],
    ];

    // perform api call
    $curl = curl_init($apiUrl);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_PROXY, $config['proxy']['url']);
    curl_setopt($curl, CURLOPT_PROXYPORT, $config['proxy']['port']);
    curl_setopt($curl, CURLOPT_USERPWD, ":" . $apiKey);

    $result = json_decode(curl_exec($curl));

    if (isset($result->errors)) {
        if ($result->errors[0] == 'User doesn\'t exist.') {
            $text = "AgentID: " . $userName . "\nTicket: " . $ticketId . "\nCustomer: " . $customerid . "\nSurvey: " . $survey . "\nComment: " . (isset($_POST['comment']) ? $_POST['comment'] : "") . "\n";
            mail($mailreceiver, $mailsubject, $text, "From: Nicereply Wrapper <$mailreceiver>");
        }
        $result = false;
    } else {
        $result = $result->_results->id;
    }
    return $result;
}

function getScoreForAPI($score)
{
    switch ($score) {
        case 'g':
            $apiScore = 10;
            break;
        case 'o':
            $apiScore = 5;
            break;
        case 'p':
            $apiScore = 1;
            break;
        default:
            throw new InvalidArgumentException("Invalid argument for score");
            break;
    }
    return $apiScore;
}

/**
 *
 * @param
 *            apiUrl
 * @param
 *            apiKey
 * @param
 *            config
 * @param
 *            ratingId
 * @param
 *            comment
 */
function updateRating($apiUrl, $apiKey, $config, $ratingId, $comment, $score)
{
    // params for api call
    $data = [
        'score' => getScoreForAPI($score),
        'comment' => $comment,
    ];

    if ($ratingId === false) {
        return true;
    }
    // perform api call
    $curl = curl_init($apiUrl . "/$ratingId");
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_PROXY, $config['proxy']['url']);
    curl_setopt($curl, CURLOPT_PROXYPORT, $config['proxy']['port']);
    curl_setopt($curl, CURLOPT_USERPWD, ":" . $apiKey);

    $result = json_decode(curl_exec($curl));

    return true; // no errors are reported by API
}
?>
</div>
    <!-- #rate_wrapper -->
</body>
</html>


