<?php

use Services\dtos\AttributeDto;
use Services\dtos\CategoryChildrenDto;
use Services\dtos\CategoryDto;
use Services\dtos\FilterDto;
use Services\enums\SortType;
use Services\ProductService;

$page_number = get_page_from_url();
$search_term = $_GET['s'] ?? '';
$stock_status = $_GET['in_status'] ?? '0';
$category_id = get_queried_object_id();
$sorting_s = $_GET['sort'] ?? 'date'; // Key is same with cart-mini empty link

$is_available = $stock_status == '1';
$page_size = 16;
$sorting = SortType::from($sorting_s);

$attributes = [];
foreach ($_GET as $key => $value) {
    if (str_starts_with($key, 'filter_')) {
        $attribute_name = substr($key, strlen('filter_'));
        $taxonomy = wc_attribute_taxonomy_name($attribute_name);

        if (taxonomy_exists($taxonomy)) {
            $term_slugs = explode(',', wc_clean(wp_unslash($value)));
            foreach ($term_slugs as $slug) {
                $term = get_term_by('slug', $slug, $taxonomy);
                if ($term && !is_wp_error($term)) {
                    $attributes[] = new FilterDto('filter_' . $attribute_name, $term->name);
                }
            }
        }
    }
}

$product_service = new ProductService();
$response = $product_service->getArchiveProducts($sorting, $page_size, $page_number, $search_term, $is_available, $category_id, $attributes);
$products = $response['products'];
$total_results = $response['total_results'];

// TODO
$wc_attributes = wc_get_attribute_taxonomies();
$all_attributes = array_map(function ($attr) {
    $attribute_label = $attr->attribute_label;
    $attribute_taxonomy_name = wc_attribute_taxonomy_name($attr->attribute_name);
    $terms = get_terms([
            'taxonomy' => $attribute_taxonomy_name,
            'hide_empty' => true
    ]);
    $attribute_values = array_map(function ($term) {
        return $term->name;
    }, $terms);
    return new AttributeDto($attr->attribute_id, $attribute_label, $attribute_values, false, $attr->attribute_name);
}, $wc_attributes);

$sorts = [SortType::Date, SortType::PriceDesc, SortType::Popularity];
$stock_filter = new FilterDto('in_status', '1', 'موجود');
$search_filter = new FilterDto('s', $search_term);
$sort_filter = new FilterDto('sort', $sorting->value, $sorting->get_display());

$total_pages = intval(ceil($total_results / $page_size));

$query_categories = get_terms([
        'taxonomy' => 'product_cat',
        'hide_empty' => true,
]);
$all_categories = [];
foreach ($query_categories as $category) {
    $all_categories[] = new CategoryChildrenDto($category->term_id, $category->parent,
            get_term_link($category->term_id), $category->name);
}

$current_term = get_queried_object();
$term_to_check = $current_term;
$categories = [];
while (!empty($term_to_check) && $term_to_check instanceof WP_Term) {
    $categories[] = new CategoryDto(null, get_term_link($term_to_check->term_id), $term_to_check->name);
    $term_to_check = get_term($term_to_check->parent, 'product_cat');
}
$all_categories = CategoryChildrenDto::buildHierarchy($all_categories, $category_id);

$filters = $attributes;
foreach ($_GET as $key => $value) {
    if ($key == 'in_status' && $value == '1')
        $filters[] = $stock_filter;
    if ($key == 'sort')
        $filters[] = $sort_filter;
    if ($key == 's')
        $filters[] = $search_filter;
}
?>

<?php
/* @var CategoryChildrenDto[] $categories */
function get_categories_tree(array $categories, int $category_id)
{
    $html = '<ul class="overflow-hidden flex flex-col gap-y-2">';
    foreach ($categories as $category) {
        if (empty($category->children)) {
            $html .=
                    '<li class="flex flex-row gap-x-2 items-center">' .
                    '<span class="text-detail opacity-0">' . get_icon("caret-left") . '</span>' .
                    '<a class="text-detail cursor-pointer" href="' .
                    update_url(['new_base_url' => $category->link]) . '"> ' . $category->title . '</a>';

            if ($category->id == $category_id) {
                $html .= '<span class="text-detail text-primary">' . get_icon("check") . '</span>';
            }
            $html .= '</li>';
        } else {
            $html .=
                    '<li class="flex flex-col" data-type="detail">' .
                    '<div class="flex flex-row gap-x-2 items-center">' .
                    '<span class="text-detail transition cursor-pointer data-[active=true]:-rotate-90" data-type="detail-activator" data-active="false">' .
                    get_icon("caret-left") .
                    '</span>' .
                    '<a class="text-detail cursor-pointer" href="' .
                    update_url(['new_base_url' => $category->link]) . '"> ' . $category->title . '</a>';

            if ($category->id === $category_id) {
                $html .= '<span class="text-detail text-primary">' . get_icon("check") . '</span>';
            }

            $html .=
                    '</div>' .
                    '<div class="data-[active=true]:mt-2 ps-3 grid grid-rows-[0fr] transition-all data-[active=true]:grid-rows-[1fr]" data-type="detail-content" data-active="false">' .
                    get_categories_tree($category->children, $category_id) .
                    '</div>' .
                    '</li>';
        }
    }
    $html .= '</ul>';
    return $html;
}

?>

<main>
    <div class="container-md mt-6 flex flex-col">
        <?php get_template_part("parts/breadcrumb/breadcrumb"); ?>

        <div class="mt-6 grid grid-cols-12 gap-x-6">
            <div class="max-md:fixed max-md:inset-x-0 max-md:-bottom-1 max-md:data-[active=true]:z-40 max-md:shadow-drawer md:col-span-5 lg:col-span-4 xl:col-span-3 h-fit bg-primary-light p-1 rounded-3xl max-md:rounded-b-none group/dialog"
                 data-type="dialog-content-filters-mobile" data-active="false">
                <div class="flex flex-col gap-y-1 relative">
                    <span class="max-md:hidden py-2 px-4 text-detail">فیلترها:</span>
                    <div class="md:hidden py-2 px-4 text-detail flex flex-col gap-y-1 items-center self-center w-full"
                         data-type="dialog-activator-filters-mobile">
                        <span class="rounded-full w-12 h-1 bg-primary/20"></span>
                        <div class="flex flex-row items-center gap-x-1">
                            <span><?= get_icon("sliders-horizontal") ?></span>
                            فیلترها
                        </div>
                    </div>
                    <div class="flex flex-col gap-y-1 transition-all max-md:h-0 max-md:group-data-[active=true]/dialog:h-[50dvh] max-md:overflow-auto max-md:mb-1 scrollbar-hidden">
                        <div class="flex flex-col p-4 bg-bg shadow-sm rounded-t-2xl rounded-b-sm gap-y-6">
                            <form class="relative text-body-s" data-type="form"
                                  action="<?= update_url(['remove_filters' => [$search_filter]]) ?>">
                                <input class="w-full py-2 ps-2 pe-6 bg-slate-50 focus:bg-white rounded-t-lg rounded-b-sm placeholder:text-placeholder"
                                       type="search" placeholder="جستجو در نتایج" name="s"
                                />
                                <span class="absolute left-2 top-1/2 -translate-y-1/2">
                                    <?= get_icon("magnifying-glass") ?>
                                </span>
                            </form>
                            <?php if (!empty($filters)) { ?>
                                <div class="flex flex-col gap-y-2">
                                    <span class="text-detail">فیلترهای اعمال‌شده:</span>
                                    <ul class="flex flex-row flex-wrap gap-1">
                                        <?php foreach ($filters as $filter) { ?>
                                            <li>
                                                <a class="text-detail bg-slate-100 rounded-sm flex flex-row gap-x-1 px-2 cursor-pointer items-center"
                                                   href="<?= update_url(['remove_filters' => [$filter]]) ?>">
                                                    <span><?= $filter->display ?></span>
                                                    <span class="text-primary"><?= get_icon("x-circle-fill", IconSize::Small) ?></span>
                                                </a>
                                            </li>
                                        <?php } ?>
                                    </ul>
                                </div>
                            <?php } ?>
                        </div>

                        <div class="flex flex-row items-center p-4 bg-bg shadow-sm rounded-sm last:rounded-b-2xl text-body-s"
                             data-type="link"
                             data-href="<?= empty($stock_status) ?
                                     update_url(['filter' => $stock_filter]) :
                                     update_url(['remove_filters' => [$stock_filter]]) ?>"
                        >
                            <?php get_template_part("parts/checkbox/checkbox", null, ['checked' => !empty($stock_status)]) ?>
                        </div>

                        <div class="flex flex-col bg-bg shadow-sm p-4 rounded-sm last:rounded-b-2xl"
                             data-type="detail">
                            <div class="flex flex-row items-center group cursor-pointer"
                                 data-type="detail-activator" data-active="false">
                                <span class="flex-1 text-body-s">دسته‌بندی</span>
                                <span class="text-body-s transition group-data-[active=true]:rotate-180">
                                        <?= get_icon("caret-up") ?>
                                    </span>
                            </div>
                            <div class="data-[active=true]:mt-2 grid grid-rows-[0fr] transition-all data-[active=true]:grid-rows-[1fr]"
                                 data-type="detail-content" data-active="false">
                                <?= get_categories_tree($all_categories, $category_id) ?>
                            </div>
                        </div>

                        <?php foreach ($all_attributes as $attribute) { ?>
                            <div class="flex flex-col bg-bg shadow-sm p-4 rounded-sm last:rounded-b-2xl"
                                 data-type="detail">
                                <div class="flex flex-row items-center group cursor-pointer"
                                     data-type="detail-activator" data-active="false">
                                    <span class="flex-1 text-body-s"><?= $attribute->name ?></span>
                                    <span class="text-body-s transition group-data-[active=true]:rotate-180">
                                        <?= get_icon("caret-up") ?>
                                    </span>
                                </div>
                                <div class="data-[active=true]:mt-2 grid grid-rows-[0fr] transition-all data-[active=true]:grid-rows-[1fr] group/detail"
                                     data-type="detail-content" data-active="false">
                                    <div class="flex flex-col gap-y-2 overflow-hidden group-data-[active=true]/detail:animate-detail max-h-50">
                                        <?php foreach ($attribute->options as $option) { ?>
                                            <?php $filter = new FilterDto('filter_' . $attribute->slug, $option); ?>
                                            <label class="cursor-pointer flex flex-row text-detail items-center"
                                                   data-type="link"
                                                   data-href="<?= is_in_url($filter) ?
                                                           update_url(['remove_filters' => [$filter]]) :
                                                           update_url(['filter' => $filter]) ?>"
                                            >
                                                <span class="flex-1"><?= $option ?></span>
                                                <input class="peer sr-only" type="checkbox"
                                                        <?= is_in_url($filter) ? 'checked' : '' ?>
                                                />
                                                <span class="text-primary hidden peer-checked:inline">
                                                        <?= get_icon("check-square-fill", IconSize::Large) ?>
                                                    </span>
                                                <span class="text-border inline peer-checked:hidden">
                                                        <?= get_icon("square", IconSize::Large) ?>
                                                    </span>
                                            </label>
                                        <?php } ?>
                                    </div>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <div class="col-span-12 md:col-span-7 lg:col-span-8 xl:col-span-9 flex flex-col gap-y-1 bg-primary-light p-1 rounded-3xl h-fit">
                <?php if ($total_results == 0) { ?>
                    <span class="text-detail py-2 px-4">هیچ محصولی یافت نشد.</span>
                <?php } else { ?>
                    <div class="flex flex-row py-2 px-4 gap-x-4">
                        <div class="flex-1 flex flex-row gap-x-2 text-detail whitespace-nowrap overflow-auto">
                            <span>مرتب‌سازی بر اساس:</span>
                            <?php foreach ($sorts as $sort) { ?>
                                <div class="cursor-pointer data-[active='true']:text-primary" data-type="link"
                                     data-active="<?= $sorting == $sort ? 'true' : 'false' ?>"
                                     data-href="<?= update_url(['filter' => $sort->get_filter(), 'remove_filters' => [$sort_filter]]) ?>">
                                    <?= $sort->get_display(); ?>
                                </div>
                            <?php } ?>
                        </div>
                        <div class="flex flex-row gap-x-2 text-detail">
                            <span>نمایش</span>
                            <span class="bg-bg px-2 rounded-sm">
                                <?= min($total_results, $page_number * $page_size) ?>-<?= ($page_number - 1) * $page_size + 1 ?>
                            </span>
                            <span>از <?= $total_results ?></span>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-1">
                        <?php foreach ($products as $product) { ?>
                            <div class="col-span-1">
                                <?php get_template_part("parts/product-card-archive/product-card-archive", null, ['product' => $product]); ?>
                            </div>
                        <?php } ?>
                    </div>

                    <?php get_template_part("parts/pagination/pagination", null,
                            ['page' => $page_number, 'total' => $total_pages]
                    ); ?>
                <?php } ?>
            </div>
        </div>
    </div>
</main>