<?php

use App\MultisiteHelper;
use Mtc\Cms\Models\Page as CmsPage;
use Mtc\Shop\Category;
/*
 * This file can be used to generate menus from the CMS that will work on ecommerce files
 * Other menus such as categories or brands can also be called here
 * Anything that needs to work across all platforms can be added here
 */

require_once 'includes/sidebar_controller.php';

/*
 * Page objects needed globally
 */


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

    $homepage_id = ContentManager::getFrontPageId();

    $page = MultisiteHelper::getCmsPageToDisplay($homepage_id);
    $homepage = new Page($page->id ?? $homepage_id);

    $twig->addGlobal('homepage', $homepage);

    /*
     * Order Cutoff Timer
     */

    if (!empty($homepage->pagedata['Show Delivery Timer'][0]['value'])) {
        $cutoff = $homepage->pagedata['Cutoff Time'][0]['value'] ?? null;
        $order_until = DeliveryMethod::getOrderUntilTime($cutoff);
        $twig->addGlobal('order_until', $order_until);
    }

    /*
     * Cookie notice
    */
    if (isset($homepage->pagedata['Cookie Notice'])) {

        if($homepage->pagedata['Cookie Notice'][0]['Enable Cookie Notice']['value'] == '1') {

            $twig->addGlobal('cookie_policy_page', $homepage->pagedata['Cookie Notice'][0]['Cookie Policy Link']['value']);

            if (!empty($_COOKIE['acceptedCookies'])) {

                if ($_COOKIE['acceptedCookies'] != '1') {
                    $twig->addGlobal('cookie_notice', true);
                }

            } else {
                $twig->addGlobal('cookie_notice', true);
            }

        }
    }

    /*
     * Contact Page
     */

    $contact_page_id = 12;

    if ($contact_page_id) {
        $contact_page = MultisiteHelper::getCmsPageToDisplay($contact_page_id);
        $contact = new Page($contact_page->id);
        $twig->addGlobal('contact', $contact);
    }

    $customer_service_id = Page::getPageIdByName('Customer Service');

    if (!empty($customer_service_id)) {

        $customer_service_menu = CMSNav::tree(
            $customer_service_id
        );

        $twig->addGlobal('footer_column_three', $customer_service_menu);

    }

    /*
     * Get the latest blog articles
     */

    $news_id = Page::getPageIdByName('News');

    if (!empty($news_id)) {

        $preview_news_articles = Listing::newInstance($news_id)
            ->setLimit(6)
            ->setOrder([["Publish Date", "DESC", "datetime"]])
            ->run();

        $preview_news_articles->getListing();

        $twig->addGlobal('preview_news_articles', $preview_news_articles->list);

    }

    /*
     * Slideshow if present
     */

    if (!empty($p->pagedata['Slideshow'])) {
        $twig->addGlobal('slideshow', $p->pagedata['Slideshow']);
    }

    /*
     * Homepage & NHS Prescriptions as global content
     */

    $twig->addGlobal('nhspresc', new Page(22));

    if (!empty($p->pagedata['Hide Pharmacy Items'][0]['value'])) {
        $twig->addGlobal('hide_pharmacy_items', true);
    }
}


// Static navigation tree. Passed in layout to menu.twig
$twig->addGlobal('main_nav_tree', [
    [
        'title' => 'Home',
        'link' => '/'
    ],
    [
        'title' => 'About',
        'link' => '/about/',
    ],
    [
        'title' => 'Services',
        'link' => '/services/',
    ],
    [
        'title' => 'Marketing',
        'link' => '/marketing/',
    ],
    [
        'title' => 'Case Studies',
        'link' => '/case-studies/',
    ],
    [
        'title' => 'News',
        'link' => '/news/',
    ]
]);


//$lazy_loading_image = THEME_PATH . '/images/loader.svg';
$twig->addGlobal('lazy_loading_image', '');


$whitelisted_ips = [
    '212.38.87.178', // Dundee Office
    '94.173.60.100', // Edinburgh Office
    '81.198.69.42', // Riga Office
    '80.232.252.140', // Riga Office
    '83.223.107.100', // VPN
    '2.24.228.53', // Euan Home
    '83.223.107.69', // Dev4
    '89.145.65.250', // Dev3
    '54.187.205.235', // Stripe
    '94.192.240.18', //carolyn
    '165.232.99.182', // New VPN
    '127.0.0.1', // localhost
    '167.99.92.17', // Dev5
    '82.132.218.107',
    '::1', // localhost

];

$remote_addr = $_SERVER['REMOTE_ADDR'] ?? null;

if (
    config('app.env') === 'staging' &&
    !in_array($remote_addr, $whitelisted_ips) &&
    php_sapi_name() !== 'cli' &&
    !str_contains($_SERVER['REQUEST_URI'], 'webhook.php') &&
    !str_contains($_SERVER['REQUEST_URI'], route('wisebee-webhook', [], false)) &&
    strpos(getcwd() . '/', '/admin/') === false
) {
    header('Location: /admin');
    exit();
}



/*
 * Trust Logos
 * Use 'active' to enable/disable logos globally
 * Use 'show_in_banners' to enable logos on banner versions, including hero version
 * Use show_in_breadcrumbs to enable/disable breadcrumb logos
 * Use show_in_footer to enable/disable footer logos
*/
$trust_logos = [];

$trust_logos = [

    [
        'active' => false,
        'title' => 'Medicine Registered Seller',
        'url' => $GLOBALS['settings']['MEDICINE_SELLER_REGISTER_URL'] ?? null,
        'img_path' => ($GLOBALS['settings']['THEME_URL'] ?? null) . '/images/icons/eu-common-logo.png',
        'helper_script' => false,
        'link_class' => false,
        'img_class' => 'lazyFade medSellerLogo',
    ],
    [
        'active' => true,
        'title' => 'General Pharmaceutical Council',
        'url' => $GLOBALS['settings']['GENERAL_PHARMACEUTICAL_COUNCIL_URL'] ?? null,
        'img_path' => ($GLOBALS['settings']['THEME_URL'] ?? null) . '/images/icons/reg.png',
        'helper_script' => false,
        'link_class' => false,
        'img_class' => 'lazyFade regLogo',
    ],
    [
        'active' => true,
        'title' => 'NHS',
        'hide_on_footer' => true,
        'url' => 'https://www.nhs.uk/',
        'img_path' => ($GLOBALS['settings']['THEME_URL'] ?? null) . '/images/icons/nhs.png',
        'helper_script' => false,
        'link_class' => false,
        'img_class' => 'lazyFade nhsLogo',
    ],
    [
        'active' => false,
        'title' => 'Trust Pilot',
        'url' => 'https://uk.trustpilot.com/',
        'img_path' => ($GLOBALS['settings']['THEME_URL'] ?? null) . '/images/icons/trust-pilot.svg',
        'helper_script' => false,
        'link_class' => false,
        'img_class' => 'rectangleLogo',
    ],

];

//Check for active logos
$trust_logos_active = false;
$trust_scripts = [];
$banner_logos = [];
$breadcrumb_logos = [];
$footer_logos = [];
$footer_logos_mini = [];

foreach($trust_logos as $logo) {
    if(!empty($logo['active'])) {
        $trust_logos_active = true;

        if(!empty($logo['helper_script'])) {
            $trust_scripts[] = $logo['helper_script'];
        }

        if(!empty($logo['show_in_breadcrumbs'])) {
            $breadcrumb_logos[] = $logo;
        }

        if(!empty($logo['show_in_banners'])) {
            $banner_logos[] = $logo;
        }

        if(!empty($logo['show_in_footer'])) {
            $footer_logos[] = $logo;
        }

        if(!empty($logo['show_in_mini_footer'])) {
            $footer_logos_mini[] = $logo;
        }
    }
}
if(!empty($trust_logos_active)) {
    $twig->addGlobal('trust_logos', $trust_logos);
    $twig->addGlobal('trust_banner_logos', $banner_logos);
    $twig->addGlobal('trust_breadcrumb_logos', $breadcrumb_logos);
    $twig->addGlobal('trust_footer_logos', $footer_logos);
    $twig->addGlobal('trust_footer_logos_mini', $footer_logos_mini);
}

if(!empty($trust_scripts) && !empty($trust_logos_active)) {
    $twig->addGlobal('trust_logo_scripts', $trust_scripts);
}

/*
* Online doctor
*/
$online_doctor_page_eloquent = ContentManager::getPageBySlug('online-doctor');
$online_doctor_page = $online_doctor_page_eloquent->legacy();
$twig->addGlobal('online_doctor', $online_doctor_page);


/*
 * Common conditions
 */
$conditions_page_eloquent = ContentManager::getPageBySlug('conditions');
$common_conditions_page = $conditions_page_eloquent->legacy();

if(!empty($common_conditions_page)) {
    $twig->addGlobal('common_conditions_url', $common_conditions_page->url);
}

/*
* Online doctor treatments/conditions
*/
$conditions_page = !empty($p->pagedata['Conditions']) ? $p : $online_doctor_page;

if(!empty($conditions_page->pagedata['Conditions'])) {

    $conditions_page->pagedata['Conditions'] = collect($conditions_page->pagedata['Conditions'])->map(function ($clinic) use ($online_doctor_page) {

        $category = \Mtc\Shop\Category::query()->find($clinic['Linked Category']['value']);

        if (!empty($category)) {

            $name = $clinic['Name']['value'];
            $clinic = $category;

            if (!empty($name)) {
                $clinic->name = $name;
            }

            if (!empty($clinic->slug)) {
                $clinic->url = $online_doctor_page->url . $category->slug;
            }

            $clinic->assessment_completed = !empty($_SESSION['category_assessments'][$category->id]);

        }

        return $clinic;
    });
}



/*
 * Featured categories
 */
if(!empty($p->pagedata['CTA Boxes (with Tabs)'])) {

    $boxes = $p->pagedata['CTA Boxes (with Tabs)'];

    $tab_boxes = [];

    foreach($boxes as $key => $box) {
        $tab = $box['Tab Title']['value'];
        $tab_boxes[$tab][] = $box;
    }


    $twig->addGlobal('cta_tab_list', $tab_boxes);
}




/*
* Page Links
*/
$twig->addGlobal('faqs_page', '/faqs/');
$twig->addGlobal('about_page', '/about/');
$twig->addGlobal('online_doctor_page', $online_doctor_page->url);
$twig->addGlobal('terms_and_conditions', '/customer-care/terms-and-conditions');
$twig->addGlobal('privacy_policy', '/customer-care/privacy-policy');
$twig->addGlobal('help_page', '/customer-care/faq/');
$twig->addGlobal('delivery_page', '/customer-care/delivery/');
/*
 * NHS Form Content
 */
$nhs_landing_page = new Page(72);
$twig->addGlobal('help_overlay', $nhs_landing_page->pagedata['NHS Prescription Form Help'][0] ?? null);

/*
* Settings
*/
$twig->addGlobal('disable_breadcrumbs', false);
$twig->addGlobal('inline_styles', false); //Won't work with webpack anymore


//Var to hide shop based stuff when the online doctor/shop is hidden
$twig->addGlobal('shop_doctor_is_live', false);


/*
 * Category banners
*/
if(!empty($p->pagedata['Category Blocks'])) {

    $category_list = [];

    foreach($p->pagedata['Category Blocks'] as $key => $category_banner) {

        $cats = [];

        for($x=0; $x<5; $x++) {

            $cat_id = $category_banner['Category ' . $x]['value'] ?? null;

            if(!empty($cat_id)) {
                $cats[] = $cat_id;
            }

        }


        $cat_list_items = [];

        foreach($cats as $cat) {

            if(!empty($cat)) {

                $inner_cat = (new \Mtc\Shop\Category())->where('id', $cat)->first();

                if(!empty($inner_cat)) {

                    $cat_list_items[] = [
                        'Title' => ['value' => $inner_cat->name],
                        'Link' => ['value' => '/online-doctor/' . $inner_cat->slug]
                    ];

                }


            }

        }

        if(!empty($cat_list_items)) {
            $p->pagedata['Category Blocks'][$key]['Category Links'] = $cat_list_items;
        }

    }

}



$about_page = new Page(13);
$how_it_works = new Page(56);



/*
 * Content blocks with sidebar
 */
if(!empty($p->pagedata['Content Sections'])) {
    $description_tabs = [];

    //Loop each content section
    foreach ($p->pagedata['Content Sections'] as $row) {

        //Build array content
        $title   = $row['Title']['value'] ?? null;
        $content = $row['Content']['value'] ?? null;

        //Add to tabs is content exists
        if (!empty($title) && !empty($content)) {

            $cta_text = false;
            $cta_link = false;

            if (!empty($row['CTA Button Text']['value'])
                && !empty($row['CTA Button Link']['value'])) {
                $cta_text = $row['CTA Button Text']['value'];
                $cta_link = $row['CTA Button Link']['value'];
            }

            $description_tabs[] = [
                'title'    => $title,
                'content'  => $content,
                'cta_text' => $cta_text,
                'cta_link' => $cta_link
            ];

        }

    }

    //Set twig variable to use in template
    $twig->addGlobal('description_tabs', $description_tabs);

}

/*
* Example page for testing
*/
$example_blocks = new Page(54);

if($p && $p->sub_id != 54) {
    unset($example_blocks->pagedata['Image Banner'][0]['Subtitle']['value']);
    unset($example_blocks->pagedata['Image Banner'][0]['Button Text']['value']);
    unset($example_blocks->pagedata['Image Banner'][0]['Button Link']['value']);
}

$twig->addGlobal('example_blocks', $example_blocks);


/*
 * 404 page
 */
$page_404_eloquent = ContentManager::getPageBySlug('404');
$page_404 = $page_404_eloquent->legacy();
$twig->addGlobal('page_404', $page_404);
$twig->addGlobal('use_svg_logo', true);


//Category Banner
$category_listings = Category::getParentCategories('order');

$category_listings = $category_listings->map(function($cat) {

    $cat->url = $cat->getURL();
    return $cat;

});


$category_listing_groups = array_chunk($category_listings->toArray() , 10, true);

$twig->addGlobal('category_listing_groups', $category_listing_groups);
