<?php
declare(strict_types=1);
use Illuminate\Support\Facades\Event;
use Mtc\Shop\PlaceholderImage;
use Mtc\Shop\Brand;
use Illuminate\Support\Facades\Cache;

require_once $path . 'shop/includes/functions.php';

(new Mtc\Shop\Events\EventServiceProvider())->register();

// Set the currency based on whats been selected on client side
if (!empty($_COOKIE['currency'])) {
    $_SESSION['currency'] = $_COOKIE['currency'];
}

$isAjaxBootstrap = !empty($exclude_header_inc['not_for_ajax']);

if (!$isAjaxBootstrap) {
    require_once $path . 'shop/includes/functions.twig.php';
}
require_once $path . 'shop/includes/image_folders.php';

if (!$isAjaxBootstrap) {
    require_once $path . 'shop/browse/classes/productfilter.class.php';

    if (isset($_REQUEST['search-filter'])) {
        $search_terms = str_replace(['-', '/', '<'], ' ', $_REQUEST['search-filter']);
        $search_terms = trim($search_terms);

        if (!empty($search_terms)) {
            $params = [];
            foreach (explode(' ', $search_terms) as $search_term) {
                $params[] = $search_term;
            }

            $tmp_filter = new ProductFilter();
            header('Location: ' . $tmp_filter->generateURL(array('search_add' => $params)));
            exit();
        }
    }

    require_once $path . 'shop/checkout/includes/postal_zones.php';
    require_once $path . 'shop/checkout/includes/dynamic_countries.php';

    /**
     * Order detail titles
     */

    $orders_statuses = \Mtc\Shop\Order::$statuses;

    /**
     * emails sent out by $order->update_status() function
     */

    $status_send_mail = [
        0 => '/emails/shop/order_email.twig', # sent out when order is paid, uncomment here to resend if order status is updated to this again
        //1,
        //2,
        //3,
        4 => '/emails/shop/shipment_email.twig',
        //5, # partial refund email handled by /admin/orders/order.refund.php due to bespoke nature
        6 => '/emails/shop/refund.twig',
        //7,
        //8,
        //9,
        10 => '/emails/shop/gp_confirmation.twig',
    ];
}

// set default sex - only write to session if value changes
if (!empty($_REQUEST['sex'])) {
    if (!isset($_SESSION['sex']) || $_SESSION['sex'] !== $_REQUEST['sex']) {
        $_SESSION['sex'] = $_REQUEST['sex'];
    }
} elseif (!isset($_SESSION['sex'])) {
    $_SESSION['sex'] = 'm';
}

if (defined('PPC_TRACKING') && PPC_TRACKING && !$isAjaxBootstrap) {
    start_tracking();
}

if (!$isAjaxBootstrap) {
    // Cache SEO data by URI to avoid database queries on every request
    $seo_cache_key = 'seo_data_' . md5($_SERVER['REQUEST_URI'] ?? '');
    $seo_data = Cache::remember($seo_cache_key, 3600, function() {
        $seoadmin = new Seo();
        $seoadmin->getSeoData();
        return [
            'title' => $seoadmin->data['title'],
            'description' => $seoadmin->data['description'],
            'matched_by' => $seoadmin->matched_by
        ];
    });

    /*
    * Prepare standard page data
    */

    $page_meta['title'] = $seo_data['title'];
    $page_meta['description'] = $seo_data['description'];
    $page_meta['matched_by'] = $seo_data['matched_by'];
    $seosettings = new SeoSettings();
}


if (!empty($ogdata) ) {
    $ogdata['name'] = ucwords(strtolower($ogdata['name']));
    $ogdata['description'] = strip_tags($ogdata['description']);
    $page_meta['ogdata'] = $ogdata;
}

if (!$isAjaxBootstrap) {
    //Add Twig Globals
    $twig->addGlobal('page_meta', $page_meta);

    $placeholder_images = [];
    
    $placeholder_data = Cache::remember('placeholder_images_all', 3600, static function () {
        return PlaceholderImage::get()->toArray();
    });

    foreach ($placeholder_data as $image_data) {
        $placeholder_images[$image_data['name']] = $image_data;
    }

    $twig->addGlobal('placeholder_images', $placeholder_images);
} else {
    $placeholder_images = [];
}

// Add Quick-buy event listening
if (QUICK_BUY === true) {
    Event::listen(
        'Mtc\Shop\Events\AddToBasketEvent',
        function (Mtc\Shop\Events\AddToBasketEvent $event) {
            return Basket::quickBuyTrigger(
                $event->getBasket(),
                $event->getItem(),
                $event->getMember(),
                $event->getRequest()
            );
        }
    );
}

if (ADVANCED_STATS_ENABLED === true) {
    Event::listen(
        'Admin::dashboardStats',
        function () {
            return [
                [
                    'name' => 'Weekly Shop Sales Stats',
                    'type' => 'graph',
                    'id' => 'js_weeklyShopSales',
                    'url' => '/shop/admin/stats.php?section=weekly_sales'
                ],
                [
                    'name' => 'Monthly Shop Sales Stats',
                    'type' => 'graph',
                    'id' => 'js_monthlyShopSales',
                    'url' => '/shop/admin/stats.php?section=monthly_sales'
                ],
                [
                    'name' => 'Sales',
                    'type' => 'numeric',
                    'id' => 'js_salesNumbers',
                    'url' => '/shop/admin/stats.php?section=sales_numbers'
                ],
                [
                    'name' => 'Orders',
                    'type' => 'numeric',
                    'id' => 'js_orderNumbers',
                    'url' => '/shop/admin/stats.php?section=order_numbers'
                ],
            ];
        }
    );
}

if (!$isAjaxBootstrap) {
    // Build minibasket data so that it doesn't have to call ajax on each page load
    $minibasket = new stdClass();
    $minibasket->items = [];

    // Load basket from session
    if (!empty($_SESSION['basket'])) {

        // Only print data in HTML that is required for minibasket display.
        $minibasket->cost_subtotal = $_SESSION['basket']['cost_subtotal'];
        if (isset($_SESSION['basket']['items']) && is_array($_SESSION['basket']['items'])) {
            foreach ($_SESSION['basket']['items'] as $basket_item) {
                $new_basket_item = [
                    'id' => $basket_item['id'],
                    'item_url' => $basket_item['item_url'],
                    'item_image' => $basket_item['item_image'],
                    'item_name' => $basket_item['item_name'],
                    'quantity' => $basket_item['quantity'],
                    'size' => $basket_item['size'],
                    'sale_price' => $basket_item['sale_price'] ?? 0,
                    'item_price' => $basket_item['item_price'],
                ];
                $minibasket->items[] = $new_basket_item;
            }
        }
    }

    $twig->addGlobal('minibasket', $minibasket);
    $twig->addGlobal('minibasket_currencies', $GLOBALS['enabled_currencies'] ?? []);
}
