<?php
/**
 * FeefoReviews Class
 *
 * This code is used to make up FeefoReviews and their modification
 *
 * @category Plugins
 * @package  Mtc_Plugins
 * @author   Davis Lasis <davis.lasis@mtcmedia.co.uk>
 * @version  v3.0
 */
namespace Mtc\Plugins\FeefoReviews\Classes;
use Twig\Environment;
use \Item;

/**
 * FeefoReviews Class. Extends eloquent model.
 *
 * @category Plugins
 * @package  Mtc_Plugins
 * @author   Davis Lasis <davis.lasis@mtcmedia.co.uk>
 * @version  v3.0
 */
class FeefoReviews
{

    /**
     * API key
     *
     * @var string
     */
    static protected $api_key = FEEFO_REVIEWS_API_KEY;
    /**
     * Merchant Identofier
     *
     * @var string
     */
    static protected $merchant_identifier = FEEFO_REVIEWS_MERCHANT_IDENTIFIER;
    /**
     * API Enter Sales Remotely URL
     *
     * @var string
     */
    static protected $api_enter_sales_remotely_url = FEEFO_REVIEWS_API_ENTER_SALES_REMOTELY_URL;
    /**
     * API Summary URL
     *
     * @var string
     */
    static protected $api_summary_url = FEEFO_REVIEWS_API_SUMMARY_URL;
    /**
     * Logging setting
     *
     * @var bool
     */
    static protected $logs = FEEFO_REVIEWS_LOG_ALL_REQUESTS;

    /**
     * Sends sales data remotely to Feefo server
     *
     * @access public
     * @param Order $order Shop order object
     * @return bool
     */

    public static function enterSalesRemotely(\Order $order)
    {

        if (self::$logs) {
            FeefoReviewsLogs::deleteLogs();
        }

        $request = [
            'apikey' => self::$api_key,
            'merchantidentifier' => self::$merchant_identifier,
            'order' => $order
        ];

        if (empty($order)) {
            $response = 'Incorrect sales data.';
        } elseif (empty($order->getItems())) {
            $response = 'Order has no items.';
        } elseif (empty(self::$api_key)) {
            $response = 'Feefo API key is empty.';
        } elseif (empty(self::$merchant_identifier)) {
            $response = 'Feefo Merchant Identifier is empty.';
        } else {
            foreach ($order->getItems() as $item) {
                $items_class = new Item();
                $items_class->Get_Item($item['item_id']);

                $request = [
                    'apikey' => self::$api_key,
                    'merchantidentifier' => self::$merchant_identifier,
                    'email' => $order->info['email'],
                    'name' => $order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname'],
                    'date' => $order->getOrderDate(),
                    'description' => $item['item_name'],
                    'productsearchcode' => $item['item_id'],
                    'orderref' => $order->getId(),
                    'amount' => $item['price_paid'],
                    'productlink' => $items_class->url,
                    'customerref' => $order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname']
                ];

                $data = http_build_query($request, '', '&');
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, self::$api_enter_sales_remotely_url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $reply = curl_exec($ch);
                curl_close($ch);

                if (self::$logs) {
                    FeefoReviewsLogs::insertLog($request, $reply);
                }
            }
            return true;
        }
        FeefoReviewsLogs::insertLog($request, $response);
        return false;
    }

    /**
     * Renders a Feefo homepage badge
     *
     * @access public
     * @param Environment $twig Twig render handler
     * @return void
     */
    public static function homepageBadge(Environment $twig)
    {
        if (!empty(FEEFO_REVIEWS_ENABLED) && !empty(FEEFO_REVIEWS_BADGE_TEMPLATE)) {
            $twig_params = [];
            echo $twig->render('feefo_reviews/homepage_badge.twig', $twig_params);
        }
    }

    /**
     * Renders latest Feefo reviews
     *
     * @access public
     * @param Environment $twig Twig render handler
     * @return void
     */
    public static function latestReviews(Environment $twig)
    {
        if (!empty(FEEFO_REVIEWS_ENABLED) && !empty(FEEFO_REVIEWS_LATEST_REVIEWS)) {
            $twig_params = [];
            echo $twig->render('feefo_reviews/latest.twig', $twig_params);
        }
    }

    /**
     * Renders a Feefo reviews for particular item
     *
     * @access public
     * @param Item $item Shop item object
     * @param Environment $twig Twig render handler
     * @return void
     */
    public static function itemReviews(\Item $item, Environment $twig)
    {
        if (!empty(FEEFO_REVIEWS_ENABLED) && !empty(FEEFO_REVIEWS_ITEM_REVIEWS)) {
            $twig_params = [
                'item' => $item
            ];
            echo $twig->render('feefo_reviews/item_full.twig', $twig_params);
        }
    }

    /**
     * Renders a Feefo reviews badge for particular item
     *
     * @access public
     * @param Item $item Shop item object
     * @param Environment $twig Twig render handler
     * @return void
     */
    public static function itemReviewsBadge(\Item $item, Environment $twig)
    {
        if (!empty(FEEFO_REVIEWS_ENABLED) && !empty(FEEFO_REVIEWS_ITEM_REVIEWS)) {
            $twig_params = [
                'item' => $item
            ];
            echo $twig->render('feefo_reviews/product_reviews_badge.twig', $twig_params);
        }
    }

    /**
     * Collects Feefo reviews rating summary and renders summary schema meta tags
     *
     * @access public
     * @param Environment $twig Twig render handler
     * @return void
     */
    public static function getHomepageSummarySchema(Environment $twig) {
        if (!empty(FEEFO_REVIEWS_ENABLED)) {
            self::$api_summary_url .= '?merchant_identifier=' . self::$merchant_identifier;
            $curl = curl_init();
            $curl_options = [
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_URL => self::$api_summary_url,
                CURLOPT_CONNECTTIMEOUT_MS => 1000,
                CURLOPT_TIMEOUT_MS => 1000
            ];
            curl_setopt_array($curl, $curl_options);
            $response = curl_exec($curl);
            curl_close($curl);

            if (!empty($response)) {

                $response = json_decode($response);

                $twig_params = [
                    'feefo_ratings' => [
                        'ratingValue' => $response->rating->rating,
                        'bestRating' => $response->rating->max,
                        'worstRating' => $response->rating->min,
                        'ratingCount' => $response->meta->count
                    ]
                ];

                $settings = FeefoReviewsSettings::find(1);
                $settings_map = FeefoReviewsSettings::columnMap();

                foreach ($settings_map as $fieldset_title => $fieldset) {
                    foreach ($fieldset as $field => $title) {
                        if (!empty($settings->$field)) {
                            $twig_params[$fieldset_title][$field] = $settings->$field;
                        }
                    }
                }

                echo $twig->render('feefo_reviews/homepage_summary_schema.twig', $twig_params);
            }
        }
    }

}
