<?php
/**
 * Trustpilot API plugin
 *
 * Pulls a feed from Trust Pilot and turns this into a twig global for output
 *
 * @author Aivars Francis <aivars.francis@mtcmedia.co.uk>
 * @author Efraim Zakarias <efraim.zakarias@mtcmedia.co.uk>
 *
 */

// The defaults are only set on the first load.
// After this they are available to amend in site settings.

use Mtc\Plugins\TrustpilotAPI\Classes\TrustpilotAPI;

if (!defined('TRUSTPILOT_API_ENABLED')) {
    require_once __DIR__ . '/includes/install.php';
}

// add trustpilot customer invitation details to queue to be sent an email later on
if (defined('TRUSTPILOT_API_ENABLED') && TRUSTPILOT_API_ENABLED == true) {
//    HooksAdapter::add_action(
//        'Order/markPaid',
//        '\Mtc\Plugins\TrustpilotAPI\Classes\TrustpilotAPI::sendInvitationLink',
//        10,
//        [$order]
//    );
//
//    $twig->addFunction(new \Twig\TwigFunction('truspilot_get_rating_image', function ($stars) {
//        return TrustpilotAPI::getStarImage($stars);
//    }));
}

// get trustpilot item reviews 
if (defined("TRUSTPILOT_API_ENABLED")
    && TRUSTPILOT_API_ENABLED == true
    && $_SERVER['PHP_SELF'] === '/shop/item.php'
) {
    if (!empty($_REQUEST['slug'])) {
        $item_id = \Mtc\Shop\Item\Custom::query()
            ->where('slug', filter_input(INPUT_GET, 'slug'))
            ->pluck('item_id')
            ->first();

        if (empty($item_id)) {
            return;
        }
    }
    $item = new Item();
    $item->Get_Item($item_id);

    $reviews = json_decode(TrustpilotAPI::getProductReviews($item->id, ''))->productReviews ?? [];
    $all_reviews = json_decode(TrustpilotAPI::getProductReviewsSummaries($item->id, $item->url));

    $reviews = collect($reviews)
        ->map(function ($review) {
            $review->createdAt = preg_replace("/\.[0-9]+Z/", '', $review->createdAt);
            $review->createdAt = \Carbon\Carbon::createFromFormat('Y-m-d\TH:i:s', $review->createdAt);
            $review->date = $review->createdAt->format('jS \of F Y');
            $review->ymd_date = $review->createdAt->format('Y-m-d');
            return $review;
        })
        ->sortBy('stars', SORT_DESC)
        ->take(10);

    $twig->addGlobal('trustpilot_item_reviews', $reviews);
    $twig->addGlobal('all_trustpilot_item_reviews', $all_reviews);
}
