<?php

namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Mtc\Shop\Category;
use Mtc\Shop\Item;
use Mtc\Shop\Assessment\Assessment;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswersFilter;
use App\CategoryPageHelper;
use MtcPharmacy\Bundles\Classes\BundleTypeItem;
use MtcPharmacy\Multisite\Classes\MultisiteManager;
use MtcPharmacy\Multisite\Classes\MultisiteConstants;
use App\CategoryInfo;


class CategoryController extends Controller
{

    public static function index($category_slug, Request $request)
    {
        redirect_if_trailing_slash();

        $category = Category::query()
            ->where('slug', $category_slug)
            ->first();

        if (!$category) {
            abort(404);
        }

        $category = \App\MultisiteHelper::getCategoryToDisplay($category->id);

        $fullscreen = (bool) request()->input('fullscreen');
        if ($fullscreen) {
            $template = 'shop/category/fullscreen_products.twig';
        } else {
            $template = 'shop/category/landing.twig';
        }

        $template_data = CategoryPageHelper::getTemplateData($category);


        $template_data['category'] = $category;
        $template_data['items'] = self::getDisplayItems($category);
        $template_data['items_doctor'] = self::getDisplayItems($category, ['doctor']);
        $template_data['items_standard'] = self::getDisplayItems($category, ['general', 'pharmacy']);

        $template_data['tabs'] = CategoryInfo::getDisplayReadyData($category->id);

        $template_data['faqs'] = [];

        if (!empty($template_data['category_faqs']['faqs'])) {
            $template_data['faqs'] = $template_data['category_faqs']['faqs'];
        }

        if (!empty($template_data['category']['overview'])) {

            //Extract tables from the content to avoid adding another field
            $overview_content = $template_data['category']['overview'];

            $tables_found = preg_match_all('/<table.*?>.*?<\/table>/is', $overview_content, $overview_tables);

            $table_html = '';

            if ($tables_found) {

                foreach ($overview_tables[0] as $table) {
                    $clean_table = preg_replace('/style\=\".*?\"/is', '', $table);
                    $table_html .= $clean_table;
                }

                $overview_content = preg_replace('/<table.*?>.*?<\/table>/is', '', $overview_content);
            }


            $template_data['overview'] = [
                'title' => !empty($template_data['category']['overview_title']) ? $template_data['category']['overview_title'] : '',
                'content' => $overview_content,
                'table' => $table_html
            ];


        }

        /*
        if(!empty($template_data['category']['overview'])) {
            $template_data['faqs'][] = [
                'question' => !empty($template_data['category']['overview_title']) ? $template_data['category']['overview_title'] : 'Overview',
                'answer' => $template_data['category']['overview']
            ];
        }

        if(!empty($template_data['category']['causes'])) {
            $template_data['faqs'][] = [
                'question' => !empty($template_data['category']['causes_title']) ? $template_data['category']['causes_title'] : 'Causes',
                'answer' => $template_data['category']['causes']
            ];
        }

        if(!empty($template_data['category']['symptoms'])) {
            $template_data['faqs'][] = [
                'question' => !empty($template_data['category']['symptoms_title']) ? $template_data['category']['symptoms_title'] : 'Symptoms',
                'answer' => $template_data['category']['symptoms']
            ];
        }

        if(!empty($template_data['category']['treatments'])) {
            $template_data['faqs'][] = [
                'question' => !empty($template_data['category']['treatments_title']) ? $template_data['category']['treatments_title'] : 'Treatments',
                'answer' => $template_data['category']['treatments']
            ];
        }

        */

        if (!empty($template_data['tabs'])) {

            foreach ($template_data['tabs'] as $tab) {
                $f = [];
                $f['question'] = $tab['title'];
                $f['answer'] = $tab['content'];
                $template_data['faqs'][] = $f;
            }

        }


        return template($template, $template_data);
    }


    /*** HELPERS ***/

    public static function getDisplayItems(Category $category, $type_filter = [], $assessmentResults = false)
    {
        $mm = new MultisiteManager($category);
        $base_category = $mm->getBaseEntity()->getConcreteEntity();

        $available_items_query = $base_category->items()->active();

        MultisiteManager::decorateQueryWithMultisiteInfo(
            $available_items_query,
            MultisiteConstants::ENTITY_TYPE_SHOP_ITEM
        );

        $available_items_query->having('ms_site_id', '=', SITE_ID);
        $available_items_query->orHaving('ms_mode', '=', MultisiteConstants::MODE_SINGLE_SITE);

        $available_items_query->addSelect(['items.*']);

        /** @var Collection $available_items */
        $items = $available_items_query
            ->with('images')
            ->with('sizes')
            ->orderBy('order')
            ->orderBy('id')
            ->get();

        /** @var Assessment $assessment */
        $assessment = Assessment::getCompletedForCategory($base_category);
        $items = self::addGroupBuyItems($items);
        $items = $items->unique();

        $items = self::applyQualifyingAnswersFilter($items, $assessment);
        $items = self::applyTypeFilter($items, $type_filter);
        /** @var Collection $items */

        // Find recommended items based on answers
        if ($assessmentResults && !empty($assessment)) {
            $items = $assessment->buildProductListBasedOnAnswers($items);
            $items = self::applyStockFilter($items);
        }

        return self::mapItemFields($items)->values();
    }

    protected static function applyQualifyingAnswersFilter($items, $assessment)
    {
        $qa_filter = QualifyingAnswersFilter::init($assessment);

        if (isset($_SESSION['adminId']) && request()->input('debug')) {
            \Util::var_dump($qa_filter->getDebugInfo());
            \Util::var_dump($qa_filter);
        }

        $rejected_items = $qa_filter->getRejectedItemIDs();

        return $items->filter(function ($i) use ($rejected_items) {
            return (!in_array($i->id, $rejected_items));
        });
    }

    protected static function addGroupBuyItems($items)
    {
        $groupbuy_items = Item::getMatchingGroupBuyItems($items);

        foreach ($groupbuy_items as $groupbuy_item) {
            $items->push($groupbuy_item);
        }
        return $items;
    }

    protected static function applyTypeFilter($items, $type_filter)
    {
        if (empty($type_filter)) {
            return $items;
        }

        return $items->filter(function ($item) use ($type_filter) {
            foreach ($type_filter as $type) {
                if ($item->product_type == $type || empty($item->product_type) && $type == 'general') {
                    return true;
                }
            }
            return false;
        });
    }

    protected static function mapItemFields($items)
    {
        $items->map(function ($item) {

            $assessment_display = !empty($category->displayed_on_assessment) || !empty($assessment);
            $item->basket_button_data = $item->getProductCardData(true, "Get started", $assessment_display);

            $main_category_id = $item->getMainCategory()->id;

            $sub_categories = $item->categories->filter(function ($c) use ($main_category_id) {
                return $main_category_id != $c->id;
            });

            $sub_category = $sub_categories->first();

            $sub_category_data = [];
            $sub_category_data['id'] = false;
            $sub_category_data['name'] = false;

            if (!empty($sub_category)) {
                $sub_category_data['id'] = $sub_category->id;
                $sub_category_data['name'] = $sub_category->name;
            }

            $item->main_sub_category = $sub_category_data;

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

            return $item;

        });

        return $items;
    }

    /**
     * Removes out of stock items
     *
     * @param $items
     * @return mixed
     */
    protected static function applyStockFilter($items)
    {
        return $items->filter(function ($item) {
            return $item->in_stock;
        });
    }
}
