<?php

use Services\dtos\AttributeDto;
use Services\dtos\CommentDto;
use Services\dtos\FilterDto;
use Services\dtos\ImageDto;
use services\dtos\VariationDto;

enum IconSize
{
    case Medium;
    case Large;
    case Small;
    case Smaller;
}

function get_icon(string $name, IconSize $size = IconSize::Medium): string
{
    $base_path = get_template_directory() . '/assets/images/icons/';
    $safe_name = basename($name);
    $full_path = $base_path . $safe_name . '.svg';

    $svg_content = '';
    if (file_exists($full_path)) {
        $svg_content = file_get_contents($full_path);
        $svg_content = $svg_content ?: '';
    }

    return create_icon($svg_content, $size);
}

function create_icon(string $content, IconSize $size = IconSize::Medium): string
{
    if ($size == IconSize::Medium) {
        return '<i class="icon-medium">' . $content . '</i>';
    }
    if ($size == IconSize::Large) {
        return '<i class="icon-large">' . $content . '</i>';
    }
    if ($size == IconSize::Small) {
        return '<i class="icon-small">' . $content . '</i>';
    }
    if ($size == IconSize::Smaller) {
        return '<i class="icon-smaller">' . $content . '</i>';
    }

    return '';
}

function get_icon_image(string $image_src, IconSize $size = IconSize::Medium): string
{
    $img_content =
            '<div class="icon-image" style="mask-image: url(' . $image_src . ')"' . '></div>';

    return create_icon($img_content, $size);
}

/* @param array{new_base_url?: string , filter?: FilterDto, remove_filters?: FilterDto[], page?: int} $options */
function update_url(array $options): string
{
    $remove_filters = $options['remove_filters'] ?? [];
    $new_base_url = $options['new_base_url'];
    $filter = $options['filter'];
    $page = $options['page'] ?? 1;

    $current_params = $_GET;

    foreach ($remove_filters as $remove_filter) {
        if (isset($current_params[$remove_filter->key])) {
            $active_values = explode(',', $current_params[$remove_filter->key]);
            $active_values = array_filter($active_values, function ($v) use ($remove_filter) {
                return $v !== $remove_filter->value;
            });

            if (empty($active_values)) {
                unset($current_params[$remove_filter->key]);
            } else {
                $current_params[$remove_filter->key] = implode(',', $active_values);
            }
        }
    }

    if (!empty($filter)) {
        if (isset($current_params[$filter->key])) {
            $active_values = explode(',', $current_params[$filter->key]);
            $active_values = array_filter($active_values, function ($v) use ($filter) {
                return $v !== $filter->value;
            });
            $active_values[] = $filter->value;
            $current_params[$filter->key] = implode(',', $active_values);
        } else {
            $current_params[$filter->key] = $filter->value;
        }
    }

    $base_url = $new_base_url ?? strtok($_SERVER['REQUEST_URI'], '?');

    $base_url = apply_page_url($page, $base_url);

    if (empty($current_params)) {
        return $base_url;
    }

    return $base_url . '?' . http_build_query($current_params);
}

function is_in_url(FilterDto $filter): bool
{
    if (isset($_GET[$filter->key])) {
        $active_values = explode(',', $_GET[$filter->key]);
        if (in_array($filter->value, $active_values)) {
            return true;
        }
    }
    return false;
}

function format_price($price): string
{
    return number_format($price);
}

function product_image(?ImageDto $image): string
{
    if (!empty($image))
        return '<img class="w-full aspect-square" src="' . $image->src . '" alt="' . $image->alt . '"/>';

    return '';
}

function format_datetime(string $datetime, bool $diff = false): string
{
    $wc_datetime = wc_string_to_datetime($datetime);

    if ($diff)
        return human_time_diff($wc_datetime->getTimestamp()) . " پیش";

    return wc_format_datetime($wc_datetime);
}

function apply_page_url(int $page_number, string $base): string
{
    $page_key = "/page/";
    $parts = explode($page_key, $base);
    $base = sizeof($parts) > 1 ? $parts[0] : rtrim(strtok($parts[0], '?'), "/");

    if ($page_number == 1)
        return $base . "/";
    else
        return $base . $page_key . $page_number . "/";
}

function get_page_from_url(): int
{
    $page_key = "/page/";
    $parts = explode($page_key, strtok($_SERVER['REQUEST_URI'], '?'));
    if (sizeof($parts) > 1) return intval($parts[1]);
    return 1;
}

function get_input(string $label, string $name, string $type = 'text', bool $required = false): string
{
    ob_start();
    ?>

    <label class="relative w-full flex" data-type="input-box">
        <input class="peer w-full border border-border rounded-lg py-2 ps-4 pe-6 text-body placeholder:text-body-s group-data-[error=true]/checkout-form:data-[error=true]:outline group-data-[error=true]/checkout-form:data-[error=true]:outline-error"
               type="<?= $type ?>" name="<?= $name ?>" placeholder="<?= $label ?>"
                <?= $required ? "data-type='input-required'" : "" ?> data-error="false" data-message=""
        />
        <span class="absolute leading-none p-1 top-1/2 -translate-y-1/2 right-4 text-body-s bg-bg transition-all peer-focus:top-0 peer-not-placeholder-shown:top-0">
            <?= $label ?>
        </span>
        <span class="absolute top-1/2 -translate-y-1/2 left-2 text-body p-1 hidden peer-not-placeholder-shown:block cursor-pointer"
              data-type="input-box-clear">
            <?= get_icon("x", IconSize::Small) ?>
        </span>
    </label>

    <?php
    return ob_get_clean();
}

function get_textarea(string $label, string $name, int $rows, bool $required = false): string
{
    ob_start();
    ?>

    <label class="relative w-full flex" data-type="input-box">
        <textarea
                class="peer w-full border border-border rounded-lg py-2 ps-4 pe-6 text-body placeholder:text-body-s group-data-[error=true]/checkout-form:data-[error=true]:outline group-data-[error=true]/checkout-form:data-[error=true]:outline-error"
                type="text" name="<?= $name ?>" placeholder="<?= $label ?>" rows="<?= $rows ?>"
               <?= $required ? "data-type='input-required'" : "" ?> data-error="false" data-message=""
        ></textarea>
        <span class="absolute leading-none p-1 top-6 -translate-y-1/2 right-4 text-body-s bg-bg transition-all peer-focus:top-0 peer-not-placeholder-shown:top-0">
            <?= $label ?>
        </span>
        <span class="absolute top-6 -translate-y-1/2 left-2 text-body p-1 hidden peer-not-placeholder-shown:block cursor-pointer"
              data-type="input-box-clear">
            <?= get_icon("x", IconSize::Small) ?>
        </span>
    </label>

    <?php
    return ob_get_clean();
}

function get_selector(string $label, string $name, array $items, string $data_for, bool $required = false): string
{
    ob_start();
    ?>
    <div class="flex flex-col" data-type="select-box" data-for="<?= $data_for ?>">
        <label class="relative w-full h-full flex">
            <input class="peer w-full border border-border rounded-lg py-2 ps-4 pe-6 text-body placeholder:text-body-s cursor-pointer group-data-[error=true]/checkout-form:data-[error=true]:outline group-data-[error=true]/checkout-form:data-[error=true]:outline-error"
                   type="text" readonly placeholder="<?= $label ?>"
                    <?= $required ? "data-type='input-required'" : "" ?> data-error="false" data-message=""
            />
            <select class="sr-only" name="<?= $name ?>">
                <?php foreach ($items as $key => $value) { ?>
                    <option value="<?= $key ?>"><?= $value ?></option>
                <?php } ?>
            </select>

            <span class="absolute leading-none p-1 top-6 -translate-y-1/2 right-4 text-body-s bg-bg transition-all peer-focus:top-0 peer-not-placeholder-shown:top-0">
                <?= $label ?>
            </span>
            <span class="absolute top-1/2 -translate-y-1/2 left-2 text-body p-1">
                <?= get_icon("caret-up", IconSize::Small) ?>
            </span>
        </label>

        <div class="w-full relative">
            <ul class="absolute hidden data-[active='true']:flex flex-col w-full rounded-lg top-2 right-0 bg-bg animate-dropdown border border-border z-10 overflow-y-auto overflow-x-hidden max-h-50 p-2"
                data-type="select-box-content" data-active="false">
                <input type="text" class="text-body-s p-1 border border-border rounded-md mb-2"
                       data-type="select-box-search"/>
                <?php foreach ($items as $key => $value) { ?>
                    <li class="text-body-s transition hover:bg-primary-light cursor-pointer"
                        data-type="select-box-item" data-value="<?= $value ?>">
                        <?= $value ?>
                    </li>
                <?php } ?>
            </ul>
        </div>
    </div>

    <?php
    return ob_get_clean();
}

/* @param VariationDto[] $variations */
function get_variations_selector(array $variations): string
{
    /* @var AttributeDto[] $attributes */
    $attributes = [];

    foreach ($variations as $variation) {
        foreach ($variation->attributes as $attribute) {
            $find = false;
            foreach ($attributes as $e_attribute) {
                if ($e_attribute->name === $attribute->key){
                    $find = true;
                    $option_find = false;
                    foreach ($e_attribute->options as $option) {
                        if ($option === $attribute->value){
                            $option_find = true;
                            break;
                        }
                    }
                    if (!$option_find) {
                        $e_attribute->options[] = $attribute->value;
                    }
                    break;
                }
            }
            if (!$find) {
                $attributes[] = new AttributeDto(1, $attribute->key, [$attribute->value], true);
            }
        }
    }

    ob_start();
    ?>

    <div class="flex flex-col gap-y-4" data-type="variation-box">
    <select class="sr-only" data-type="variation-info">
        <?php foreach ($variations as $variation) { ?>
            <option value="<?= $variation->id ?>" data-stock="<?= $variation->in_stock ? 'true' : 'false' ?>"
                    data-sale-price="<?= $variation->sale_price ?>" data-regular-price="<?= $variation->regular_price ?>"
                    data-discount="<?= $variation->discount ?>"></option>
        <?php }?>
    </select>
    <input class="sr-only" name="variation_id" data-type="variation-id" />
        <?php foreach ($attributes as $e_attribute) { ?>

        <div class="flex flex-row items-center max-lg:group-data-[active=false]:hidden">
            <div class="flex flex-col" data-type="select-box" data-for="variation">
                <label class="relative w-full h-full grid grid-cols-2 items-center">
                    <span class="col-span-1 text-body-s"><?= $e_attribute->name ?>:</span>

                    <input class="col-span-1 border border-border rounded-lg py-1 ps-4 pe-6 text-body-s cursor-pointer group-data-[error=true]/form:data-[error=true]:outline group-data-[error=true]/form:data-[error=true]:outline-error"
                       type="text" readonly placeholder="انتخاب کنید"
                       data-type="input-required" data-error="false" data-message=""
                    />
                    <select class="sr-only">
                        <?php foreach ($e_attribute->options as $option) { ?>
                            <option value="<?= $option ?>"><?= $option ?></option>
                        <?php } ?>
                    </select>

                    <span class="absolute top-1/2 -translate-y-1/2 left-2 text-body p-1">
                        <?= get_icon("caret-up", IconSize::Small) ?>
                    </span>
                </label>

                <div class="w-full relative self-end min-w-1/2 max-w-fit">
                    <ul class="absolute hidden data-[active='true']:flex flex-col w-full rounded-lg top-2 right-0 bg-bg animate-dropdown border border-border z-10 overflow-y-auto overflow-x-hidden max-h-50 p-2"
                    data-type="select-box-content" data-active="false">
                        <input type="text" class="text-body-s p-1 border border-border rounded-md mb-2 <?= sizeof($e_attribute->options) < 6 ? "hidden" :"" ?>"
                           data-type="select-box-search"/>
                        <span class="text-body-s text-red-800 hover:bg-primary-light cursor-pointer data-[active=false]:hidden"
                              data-active="false" data-type="select-box-clear">
                            حذف انتخاب
                        </span>
                        <?php foreach ($e_attribute->options as $option) { ?>
                            <?php $variations_ids = []; ?>
                            <?php foreach ($variations as $variation) { ?>
                                <?php foreach ($variation->attributes as $attribute) { ?>
                                    <?php if($attribute->key === $e_attribute->name && $attribute->value === $option){ ?>
                                        <?php $variations_ids[] = $variation->id ?>
                                        <?php break; ?>
                                    <?php } ?>
                                <?php } ?>
                            <?php } ?>
                            <li class="text-body-s transition hover:bg-primary-light cursor-pointer data-[disabled=true]:pointer-events-none data-[disabled=true]:text-fg/50" data-disabled="false"
                            data-type="select-box-item" data-value="<?= $option ?>" data-variations-ids="<?= implode(',', $variations_ids) ?>">
                                <?= $option ?>
                            </li>
                        <?php } ?>
                    </ul>
                </div>
            </div>
        </div>
    <?php } ?>
    </div>

    <?php
    return ob_get_clean();
}

function get_shipping_method_selector(array $items): string
{
    ob_start();
    ?>
    <div class="flex flex-col" data-type="select-box">
        <label class="relative w-full h-full grid grid-cols-2 items-center">
            <span class="col-span-1 text-body-s">روش ارسال:</span>

            <input class="w-full border border-border rounded-lg py-2 ps-4 pe-6 text-body placeholder:text-body-s cursor-pointer group-data-[error=true]/checkout-form:data-[error=true]:outline group-data-[error=true]/checkout-form:data-[error=true]:outline-error"
                   type="text" readonly placeholder="انتخاب کنید"
                   data-type='input-required' data-error="false" data-message=""
            />
            <select class="sr-only" name="shipping_method[0]" form="checkout-form" data-type="shipping-method">
                <?php foreach ($items as $key => $item) { ?>
                    <option value="<?= $key ?>"></option>
                <?php } ?>
            </select>

            <span class="absolute top-1/2 -translate-y-1/2 left-2 text-body p-1">
                <?= get_icon("caret-up", IconSize::Small) ?>
            </span>
        </label>

        <div class="w-full relative self-end min-w-1/2 max-w-fit">
            <ul class="absolute hidden data-[active='true']:flex flex-col w-full rounded-lg top-2 right-0 bg-bg animate-dropdown border border-border z-10 overflow-y-auto overflow-x-hidden max-h-50 p-2"
                data-type="select-box-content" data-active="false">
                <?php foreach ($items as $key => $item) { ?>
                    <li class="text-body-s transition hover:bg-primary-light cursor-pointer"
                        data-type="select-box-item" data-value="<?= $item->method_title ?>">
                        <?= $item->method_title ?>
                    </li>
                <?php } ?>
            </ul>
        </div>
    </div>

    <?php
    return ob_get_clean();
}