<?php
/**
 * Featured Products
 *
 * Allow user to select featured products from product catalogue
 * then wrap these up for twig to display.
 *
 * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 */

use \Mtc\Plugins\FeaturedProducts\Classes\FeaturedProducts;
use Twig\TwigFunction;

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

$twig->addFunction(new TwigFunction('featured_products', function () use ($twig) {
    $featured_products = FeaturedProducts::get($twig);

    echo $twig->render('shop/item/featured_products.twig', [
        'featured_products' => $featured_products
    ]);
}));

$twig->addFunction(new TwigFunction('featured_products_vue', function () use ($twig) {
    
    try {
        $max_created_at    = FeaturedProducts::query()
                                             ->max('created_at')
        ;
        $featured_count    = FeaturedProducts::query()
                                             ->count()
        ;
        $cache_name        = "featured_{$max_created_at}_{$featured_count}";
        $featured_products = \Illuminate\Support\Facades\Cache::get($cache_name);


        if (empty($featured_products)) {
            $featured_products = FeaturedProducts::get($twig, true);
            \Illuminate\Support\Facades\Cache::set($cache_name, $featured_products);
        }

        return $featured_products;

    } catch (Exception $exception) {
        return [];
    }
}));

