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

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
if (!empty($_REQUEST['sex'])) {
    $_SESSION['sex'] = $_REQUEST['sex'];
} else {
    $_SESSION['sex'] = 'm';
}

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

if (!$isAjaxBootstrap) {
    $seoadmin = new Seo();
    $seoadmin->getSeoData();

    /*
    * Prepare standard page data
    */

    $page_meta['title'] = $seoadmin->data['title'];
    $page_meta['description'] = $seoadmin->data['description'];
    $page_meta['matched_by'] = $seoadmin->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_data = PlaceholderImage::get()->toArray();

    $placeholder_images = [];

    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'] ?? []);
}
