<?php

use Mtc\Plugins\TrustpilotAPI\Classes\TrustpilotAPI;
use Mtc\Plugins\TrustpilotAPI\Classes\TrustpilotSettings;

$path = '../../../';
require_once $path.'core/includes/header.inc.php';
$page['title'] = 'Trustpilot API';

if ($_REQUEST['action'] === 'businessId') {
    TrustpilotAPI::getBusinessId();
}

// log in to trustpilot to get the access token
if ($_REQUEST['action'] === 'login') {
    $errors = [];

    $callback = TrustpilotAPI::oAuth($_REQUEST['email'], $_REQUEST['password']);
    $callback = json_decode($callback);

    if (isset($callback->Error)) {
        $errors[] = $callback->Error;
    } elseif ($callback->status === 'Error') {
        $errors[] = $callback->message;
    } elseif ($callback->reason) {
        $errors[] = $callback->reason;
    }

    if (! empty($callback->access_token)) {
        $access_token = TrustpilotSettings::query()->where('key', '=', 'ACCESS_TOKEN')->first();
        $access_token->value = $callback->access_token;
        $access_token->save();

        $refresh_token = TrustpilotSettings::query()->where('key', '=', 'REFRESH_TOKEN')->first();
        $refresh_token->value = $callback->refresh_token;
        $refresh_token->save();
    }
}

// check oauth log
$oauth = TrustpilotAPI::getAccessToken();

require_once $path.'core/admin/templates/adminheader.html.php' ?>
    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li class="end">Trustpilot API</li>
    </ul>

    <h1>Trustpilot API</h1>

<?php

require 'tabnav.php';

if (count($errors) > 0) {
    showerrors($errors);
}

?>
    <form action="/plugins/TrustpilotAPI/admin/" method="post" class="style">
        <fieldset class="show">
            <h1><a class="show el">Login to Trustpilot<i class="icon-caret-right"></i></a></h1>
            <div class="row">
                <label for="email">Email</label>
                <input type="email" name="email" id="email" value="<?= clean_page($_REQUEST['email']); ?>"/>
            </div>
            <div class="row">
                <label for="password">Password</label>
                <input type="password" name="password" id="password" value="<?= clean_page($_REQUEST['password']); ?>"/>
            </div>
        </fieldset>

        <div class="row">
            <input type="hidden" name="action" value="login"/>
            <input type="submit" value="Login"/>
        </div>
    </form>
    <?php

    require_once $path.'core/admin/templates/adminfooter.html.php';
