<?php

use App\MetaDataFactory;
use App\MultisiteHelper;
use App\ProductInfo;
use Mtc\Shop\Item\Custom;
use Mtc\Shop\Warning;


$path = '../';
$cloudzoom = true;
$page_meta['section'] = 'item';
$heatmap_name = 'item';
$admin_preview = false;
$page_meta['id'] = 'item';
$item = null;


/*
 * This controller can be called as part of the templating
 * previews found in /css and uses this code to load the
 * includes it needs for this.
 */
if (empty($css_templating)) {
    require_once $path . 'core/includes/header.inc.php';
    $twig_template_name = 'shop/item/full.twig';
}


redirect_if_trailing_slash(false);


if (strpos($_SERVER['REQUEST_URI'], '/medications/') !== false) {
    $twig->addGlobal('hide_pharmacy_items', true);
}


$item = null;

if (!empty($_REQUEST['id'])) {
    $item = new Item();
    $item->Get_Item($_REQUEST['id']);

    if (!empty($item->custom['slug'])) {
        header('HTTP/1.1 301 Moved Permanently');
        header("Location: " . $item->url);
        exit();
    }

    $item = MultisiteHelper::getProductToDisplay($_REQUEST['id']);

} elseif (!empty($_REQUEST['slug'])) {

    $item_id = Custom::query()
        ->where('slug', filter_input(INPUT_GET, 'slug'))
        ->pluck('item_id')
        ->first();

    if (!empty($item_id)) {
        $item = MultisiteHelper::getProductToDisplay($item_id);
    }
}

/*
 * If the controller is being used by the templating system
 * it will trigger these 404 links.  Checking for the
 * $css_templating variable being set avoids this.
 */
if (empty($css_templating)) {
    if (!$item) {
        header('HTTP/1.1 404 Not Found');
        header('Location: /404.html');
        exit();
    } elseif ($item->deleted) {
        header('HTTP/1.1 301 Moved Permanently');
        header("Location: " . $item->getRedirectURL('deleted'));
        exit();
    } elseif ($item->isHidden()) {
        if (defined('ITEM_PREVIEW') && ITEM_PREVIEW === true) {
            $admin_preview = true;
            if (!isset($_SESSION['adminId']) || empty($_SESSION['adminId'])) {
                header('HTTP/1.1 307 Temporary Redirect');
                header("Location: " . $item->getRedirectURL('preview_unauthorised'));
                exit();
            }
        } else {
            header('HTTP/1.1 307 Temporary Redirect');
            header("Location: " . $item->getRedirectURL('preview_disabled'));
            exit();
        }
    }
}


//Pass the item name to header file for title tag
$title_item_name = $item->name;


if (defined('BREADCRUMBS') && BREADCRUMBS === true) {

    // breadcrumbs
    $breadcrumbs = [];

    $breadcrumbs[] = [
        'id' => 1,
        'url' => '/',
        'name' => 'Home',
    ];

    // From main category (first) work upwards to generate breadcrumb trail
    if (!empty($item->categories->toArray())) {

        $main_category = array_slice($item->categories->toArray(), 0, 1);
        if ($main_category[0]['is_online_doctor']) {
            $breadcrumbs[] = [
                'id' => 'online_doctor',
                'url' => '/online-doctor/',
                'name' => 'Online Doctor',
            ];
            $main_category = collect($item->categories)
                ->reject(function ($category) {
                    return $category['name'] == "Doctor";
                })->first();

            $breadcrumbs[] = [
                'id' => $main_category['slug'],
                'url' => '/online-doctor/' . $main_category['slug'] . '/',
                'name' => $main_category['name'],
            ];
        } else {

            if (!empty($main_category[0]['id'])) {
                $category_breadcrumbs = CategoryHelper::generateBreadcrumbs($main_category[0]['id']);
                $breadcrumbs = array_merge($breadcrumbs, $category_breadcrumbs);
            } else {
                $breadcrumbs = [];
            }

        }
    }

    if (!empty($item->brand)) {
        $breadcrumbs[] = [
            'id' => 'item_' . $item->id,
            'url' => browse_url(0, $item->brand),
            'name' => $item->brand_name,
        ];
    }

    $breadcrumbs[] = [
        'id' => 'item_' . $item->id,
        'url' => (BREADCRUMBS_LINK_LAST_CRUMB) ? $item->url : null,
        'name' => clean_page($item->name),
    ];

}

if (defined('OPEN_GRAPH_META') && OPEN_GRAPH_META == true) {
    $page_meta['ogdata'] = get_item_meta($item->id);
}

$brand_data = [];
if ($item->brand) {
    $brand_data = brand_data($item->brand->id);
}

if (isset($_REQUEST['brandid']) && $_REQUEST['brandid'] > 0) {
    $title = $brand_data['name'];
} elseif (isset($_REQUEST['catid']) && $_REQUEST['catid'] > 0) {
    $title = category_name($_REQUEST['catid']);
} else {
    $title = $item->categories->first()->name ?? null;
}

/*
 * Check Multi buy discounts if this item matches any
 */

$discounts = [];
$discountOffers = \Mtc\Shop\DiscountOffer::query()
    ->where('disabled', 0)
    ->get();

foreach ($discountOffers as $discountOffer) {
    $data = $discountOffer->toArray();
    $discount = new DiscountOffer();
    $discount->Get($data['id']);

    if ($discount->checkItem($item)) {
        $discounts[] = $discount->name;
    }
}

/*
 * Item Full
 */

$item->title = $title;

if (isset($_REQUEST['image']) && is_numeric($_REQUEST['image'])) {
    $selected_image_id = $_REQUEST['image'];
} else {
    $selected_image_id = $item->image_default;
}

$image_zoom = false;
if ($selected_image_id) {
    if ((defined('IMAGES_ZOOM') && IMAGES_ZOOM === true) && $item->images[$selected_image_id]['zoom'] == true) {
        $image_zoom = true;
    }
}




$display_add = false;
if (!$item->isHidden()) {
    $display_add = true;
}

/*
 * Override h1 title with seoadmin heading
 * if it exists
 */
if (isset($seoadmin->data['heading']) && !empty($seoadmin->data['heading'])) {
    $item->name = $seoadmin->data['heading'];
}

if (isset($_REQUEST['error'])) {
    $error = $_REQUEST['error'];
} else {
    $error = null;
}

if (isset($_REQUEST['selectowncolor'])) {
    $selectowncolor = $_REQUEST['selectowncolor'];
} else {
    $selectowncolor = null;
}

$args = [&$item, &$twig, &$member];

// T79562 - Site speed increase. Disabling this saves 0.2 seconds on page load
HooksAdapter::do_action_ref_array('render_item', [$args]);



if (!empty($item->sizes)) {

    foreach ($item->sizes as $k => $size) {
        if (!empty($size['hide'])) {
            unset($item->sizes[$k]);
            continue;
        }
        // If sale price set, use that
        if ($size['sale_price'] > 0) {
            $size_price = $size['sale_price'];
        } else {
            $size_price = $size['price'];
        }

        // If the new price is lower, set that as item From price
        if (($size_price < $item->from_price || empty($item->from_price)) && $size_price > 0) {

            $item->from_price = $size_price;
            if ($size['sale_price'] > 0) {
                // If we have a sale price, set the Item sale price and Percentage off
                $item->sale_price = $size['sale_price'];
                $item->price = $size['price'];
                $item->percentage_off = round(($item->price - $item->sale_price) / $item->price * 100);
            } else {
                $item->sale_price = 0;
                $item->price = $size['price'];
            }
        }
    }
} else {
    $item->from_price = $item->sale_price > 0 ? $item->sale_price : $item->price;
}


$item->size_strength_options = [];

//Check overall stock including size stock
$item->total_stock = $item->stock;
$build_stock_from_sizes = false;

if (!empty($item->size_strengths)) {
    foreach ($item->size_strengths as $strength => $sizes) {
        foreach ($sizes as $k => $size) {
            if (!empty($size['quantity'])) {
                $item->has_quantities = true;
            }

            if ($item->total_stock < 1 || $build_stock_from_sizes) {
                $item->total_stock += !empty($size['stock']) ? (int) $size['stock'] : 0;
                $build_stock_from_sizes = true;
            }
        }

        $item->size_strength_options[] = [
            'name' => $strength,
            'sizes' => $sizes
        ];
    }
}



$item_comparison = null;
foreach ($item->categories as $category_id => $category) {
    if (empty($item_comparison)) {
        $item_comparison = \Mtc\Shop\Category\ItemComparison::getComparisonTable($category->id);
    }
}




$page_meta['canonical'] = $item->url;

//Set main category on item
$item->main_category = '';

if (!empty($main_category)) {
    $item->main_category = $main_category;
}








$item_warning = false;

if (!empty($item->custom['caution'])) {
    $item_warning = $item->custom['caution'];
}


/*
 * Navigation tabs
 */
$navigation_tabs = [];

/*
 * Description Tabs
 */

$description_tabs = ProductInfo::getDisplayReadyData($item->id);







//Vue
$temp_item = new Item();
$temp_item->Get_Item($item->id);

$item_eloquent = $temp_item->eloquent();


$warnings = Warning::query()->orderBy('warning_type')->get();

$set_warnings = [];

foreach ($warnings as $warning) {

    $visible = $item_eloquent->warnings->contains($warning->id) ? true : false;

    if ($visible) {

        $w_type = Warning::$warning_types[$warning->warning_type];

        if ($w_type == 'warning') {
            $w_type = 'alert';
        } elseif ($w_type == 'danger') {
            $w_type = 'error';
        }

        $set_warnings[] = [
            'type' => $w_type,
            'content' => $warning->content
        ];

    }

}
$item->warnings = $set_warnings;

$item->in_stock = (bool) $item_eloquent->in_stock;
$item->from_price = (float) $item_eloquent->from_price;
$item->url = $item_eloquent->url;
$item->image = $item_eloquent->getImagePath('small');
$item->basket_button_data = $item_eloquent->getProductCardData();
$item->main_category = $item_eloquent->getMainCategory();

$item->price = (float) $item->price;
$item->sale_price = (float) $item->sale_price;

if (empty($item->image)) {
    $item->images = [];
}



$meta_data = new MetaDataFactory($item);
if ($meta_data) {
    $page_meta['title'] = $meta_data->getMetaTitle($page_meta['title']);
    $page_meta['description'] = $meta_data->getMetaDescription($page_meta['description']);
}

if (config('subscription.enabled')) {
    $item->resolvePricePerPill();
    $item->mapSizePricesToSubscriptions();
}

$options = [
    'assessment_complete' => true,
    'item' => $item,
    'category_redirect_btn_text' => 'View all treatments',
    'item_warning' => $item_warning,
    'navigation_tabs' => $navigation_tabs,
    'page_meta' => $page_meta,
    'selected_image_id' => $selected_image_id,
    'error' => $error,
    'breadcrumbs' => !empty($breadcrumbs) ? $breadcrumbs : null,
    'display_add' => $display_add,
    'selectowncolor' => $selectowncolor,
    'discounts' => $discounts,
    'admin_preview' => $admin_preview,
    'item_comparison' => $item_comparison,
    'size_error' => filter_input(INPUT_GET, 'error') === 'size',
    'item_page' => true,
    'tabs' => $description_tabs,
    'added_to_basket' => !empty($_SESSION['added']),
    'basket_has_nhs_items' => !empty($_SESSION['basket_has_nhs_items']),
    'product_overlay_enabled' => false,//enable / disable the product options overlay
];


//Quick fix before a call
/*
$options['item']->size_strength_options = $item->size_strength_options;
$options['item']->total_stock = 9999;
$options['item']->stock = 9999;
$options['item']->from_price = 18.99;
$options['item']->assessment_complete = true;
*/


unset($_SESSION['added']);
unset($_SESSION['basket_has_nhs_items']);

echo template($twig_template_name, $options);
