<?php

/**
 * Recently Viewed
 *
 * Collect and show recently viewed items
 *
 * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 */

namespace Mtc\Plugins\RecentlyViewed\Classes;

use Item;

class RecentlyViewed
{
    /**
     * RecentlyViewed::getRecentlyViewed()
     *
     * Returns an array of recently viewed items.
     *
     * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
     *
     * @return Array $recently_viewed
     */
    public static function getRecentlyViewed($twig, $limit, $currently_view)
    {
        if (! empty($_SESSION['viewed']) && is_array($_SESSION['viewed'])) {
            $recently_viewed_items_session = array_unique($_SESSION['viewed']);
            $recently_viewed_items_session = array_reverse($recently_viewed_items_session);

            //Remove currently view item from Recently Viewed
            if (! empty($currently_view)) {
                unset($recently_viewed_items_session[array_search($currently_view, $recently_viewed_items_session)]);
            }

            $recently_viewed_items_session = array_slice($recently_viewed_items_session, 0, $limit);

            foreach ($recently_viewed_items_session as $recently_viewed_item_id) {
                $recently_viewed_item = new Item;
                $recently_viewed_item->Get_Item($recently_viewed_item_id);

                $main_category = collect($recently_viewed_item->categories)
                    ->reject(function ($category) {
                        return (
                            strtolower($category['name']) == 'doctor'
                            || strtolower($category['name']) == 'pharmacy'
                            || strtolower($category['name']) == 'general'
                            || strtolower($category['name']) == 'shop'
                        );
                    })->first();

                if (! empty($main_category['name'])) {
                    $recently_viewed_item->main_category = $main_category['name'];
                } else {
                    $recently_viewed_item->main_category = '';
                }

                $recently_viewed[] = $twig->render('shop/item/small.twig', [
                    'item' => $recently_viewed_item,
                ]);
            }
        }

        return $recently_viewed;
    }

    /**
     * RecentlyViewed::registerItemView()
     *
     * Adds ID of the given item to the session of recently viewed items
     *
     * @return null
     */
    public static function registerItemView($args)
    {
        $item = &$args[0];

        if (empty($_SESSION['viewed'])) {
            $_SESSION['viewed'] = [];
        }

        if (! in_array($item->id, $_SESSION['viewed']) && ! empty($item->id)) {
            $_SESSION['viewed'][] = $item->id;
        }
    }
}
