<?php

namespace DEVELUXSCT\Metaboxes;
if (!defined('ABSPATH')) {
    exit;
}

use DEVELUXSCT\HTMLGenerators\CountdownTimerGenerator;

class Helper
{
    public static function calculate_price_difference($price, $sale_price): string
    {
        $price = (float) $price;
        $sale_price = (float) $sale_price;
        $difference = $sale_price - $price;
        return number_format($difference, 2, '.', '');
    }

    public static function calculate_price_difference_percentage($price, $sale_price): int
    {
        $price = (int) $price;
        $sale_price = (int) $sale_price;

        if ($price === 0) {
            return 0;
        }
        $difference = (($sale_price - $price) / $price) * 100;
        return (int)$difference;
    }
    public static function generate_writing_mode_styles($mode): string
    {
        if ($mode === 'horizontal_tb') {
            return 'writing-mode:horizontal-tb;';
        }
        if ($mode === 'vertical_rl') {
            return 'writing-mode:vertical-rl;';
        }
        if ($mode === 'upright') {
            return 'writing-mode:vertical-rl;text-orientation: upright;';
        }
        return '';
    }

    public static function count_percentage($price, $salePrice)
    {
        if (empty($price)) {
            $price = 0;
        }
        if (empty($salePrice)) {
            $salePrice = 0;
        }

        $parsedPrice = (int)$price;
        $parsedSalePrice = (int)$salePrice;

        if ($parsedPrice === 0 || $parsedSalePrice === 0) {
            return 0;
        }

        return 100 - floor(($parsedSalePrice / $parsedPrice) * 100);
    }

    public static function get_url_of_current_page(): string
    {
        $id = get_queried_object_id();

        if (is_tax() || is_category() || is_tag()) {
            $url = get_term_link($id);
        } elseif (is_archive()) {
            $url = get_post_type_archive_link(get_post_type());
        } elseif (is_singular()) {
            $url = get_the_permalink($id);
        } elseif (is_home()) {
            $url = get_permalink(get_option('page_for_posts'));
        } elseif (is_front_page()) {
            $url = home_url('/');
        } else {
            $url = home_url(add_query_arg([], ''));
        }

        return $url;
    }

    public static function display_countdown_timer($timer_data, $product_id, $dislocation): string
    {
        $html = '';
        if (!$timer_data || !is_array($timer_data)) {
            return '';
        }

        foreach ($timer_data as $data_item) {
            $develuxsct_timer_id = $data_item['id'] ?? 0;
            $timer_bulk = $data_item['bulk'] ?? '';
            $timer_bulk_arr = explode(',', $timer_bulk);
            $timer_dislocation = get_post_meta($develuxsct_timer_id, 'develux_timer_location', true);
            $develux_timer_start_date = get_post_meta($develuxsct_timer_id, 'develux_timer_start_date', true) ?? '';
            $develux_timer_date = get_post_meta($develuxsct_timer_id, 'develux_timer_date', true) ?? '';
            $develux_timer_display_on_card = get_post_meta( $develuxsct_timer_id, 'develux_timer_display_on_card', true);
            if(!$develux_timer_display_on_card){
                continue;
            }
            $develux_use_single_product_schedule = get_post_meta($develuxsct_timer_id, 'develux_use_single_product_schedule', true);
            if ($develux_use_single_product_schedule) {
                $develux_timer_date = '';
            }

            if ($timer_dislocation === $dislocation && in_array($product_id, $timer_bulk_arr, false)) {

                $html .= CountdownTimerGenerator::generate_countdown_timer($develuxsct_timer_id, $develux_timer_date, $develux_timer_start_date, $product_id,false);
            }
        }
        return $html;
    }
    public static function display_countdown_timer_single($timer_data, $product_id, $dislocation): string
    {
        $html = '';
        if (!$timer_data || !is_array($timer_data)) {
            return '';
        }

        foreach ($timer_data as $data_item) {
            $develuxsct_timer_id = $data_item['id'] ?? 0;
            $timer_bulk = $data_item['bulk'] ?? '';
            $timer_bulk_arr = explode(',', $timer_bulk);

            $timer_display = get_post_meta($develuxsct_timer_id, 'develux_timer_display_on_single', true);
            if(!$timer_display){
                return '';
            }
            $timer_dislocation = get_post_meta($develuxsct_timer_id, 'develux_timer_location_single', true);
            $develux_timer_start_date = get_post_meta($develuxsct_timer_id, 'develux_timer_start_date', true) ?? '';
            $develux_timer_date = get_post_meta($develuxsct_timer_id, 'develux_timer_date', true) ?? '';
            $develux_use_single_product_schedule = get_post_meta($develuxsct_timer_id, 'develux_use_single_product_schedule', true);
            if ($develux_use_single_product_schedule) {
                $develux_timer_date = '';
            }
            if ($timer_dislocation === $dislocation && in_array($product_id, $timer_bulk_arr, false)) {
                $html .= CountdownTimerGenerator::generate_countdown_timer($develuxsct_timer_id, $develux_timer_date, $develux_timer_start_date, $product_id, true);
            }
        }
        return $html;
    }

    public static function hex_to_rgba_with_alpha($hex, $alpha = 1): string
    {
        if ($hex === 'transparent') {
            return $hex;
        }
        // Remove the '#' if it's there
        $hex = ltrim($hex, '#');

        // Parse r, g, b values
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));

        // Return the rgba string with the alpha value
        return "rgba($r, $g, $b, $alpha)";
    }

    public static function hex_to_rgba($hex, $alpha = 1): string
    {
        if ($hex === 'transparent') {
            return '#00000000';
        }

        $hex = ltrim($hex, '#');

        if (strlen($hex) !== 6) {
            return '#000000FF';
        }
        // Ensure the hex string is exactly 6 valid hex characters
        if (!preg_match('/^[0-9A-Fa-f]{6}$/', $hex)) {
            return '#000000FF';
        }

        // Parse r, g, b values
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));

        // Ensure alpha is a valid float and within range
        $alpha = max(0, min(1, floatval($alpha))); // Clamps value between 0 and 1
        // Convert alpha (0-1) to 2-digit hex (0-255 -> 00-FF)
        $a = str_pad(dechex((int)round($alpha * 255)), 2, '0', STR_PAD_LEFT);

        // Return 8-digit hex format
        return sprintf("#%02X%02X%02X%s", $r, $g, $b, strtoupper($a));
    }


    /**
     * 'classic_arrow'=>'Classic Arrow &#x2190; &#x2192;',
     * 'double_arrow'=>'Double Arrow &#x21d0; &#x21d2;',
     * 'triple_arrow'=>'Triple Arrow &#x21da; &#x21db;',
     * 'angle'=>'Angle &#x2039; &#x203A;',
     * 'double_angle'=>'Double Angle &#xab; &#xbb;',
     * 'heavy_angle'=>'Heavy Angle &#x276E; &#x276F;',
     * @param $type
     * @return array
     */
    public static function get_slider_nav_arrows($type): array
    {
        switch ($type) {
            case 'classic_arrow':
                $left = '&#x2190;';
                $right = '&#x2192;';
                break;
            case 'double_arrow':
                $left = '&#x21d0;';
                $right = '&#x21d2;';
                break;
            case 'triple_arrow':
                $left = '&#x21da;';
                $right = '&#x21db;';
                break;
            case 'angle':
                $left = '&#x2039;';
                $right = '&#x203A;';
                break;
            case 'double_angle':
                $left = '&#xab;';
                $right = '&#xbb;';
                break;
            case 'heavy_angle':
                $left = '&#x276E;';
                $right = '&#x276F;';
                break;
            default:
                $left = '<';
                $right = '>';
        }

        return ['arrow_left' => $left, 'arrow_right' => $right];
    }


    public static function get_gradient($gradientType, $backgroundColorWithAlpha, $gradientColorWithAlpha): string
    {
        switch ($gradientType) {
            case 'linear-r-l':
                $gradient = "linear-gradient(to left, $backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
            case 'linear-l-r':
                $gradient = "linear-gradient(to right, $backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
            case 'linear-tl-br':
                $gradient = "linear-gradient(to bottom right, $backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
            case 'linear-tr-bl':
                $gradient = "linear-gradient(to bottom left, $backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
            case 'radial':
                $gradient = "radial-gradient($backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
            case 'conic':
                $gradient = "conic-gradient($backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
            default:
                // Default gradient
                $gradient = "linear-gradient($backgroundColorWithAlpha, $gradientColorWithAlpha)";
                break;
        }

        return $gradient;
    }


    public static function get_label_position_style($label_position, $width, $width_unit): string
    {
        $width_half = (int)$width / 2;
        switch ($label_position) {
            case 'top-left':
                return 'top: 0; left: 0;';
            case 'top-right':
                return 'top: 0; left: calc(100% - ' . $width . $width_unit . ');';
            case 'top-center':
                return 'top: 0; left: calc(50% - ' . $width_half . $width_unit . ');';
            default:
                return 'top: 0px; left: 0px;';
        }
    }

    public static function get_text_align($label_justify_content): string
    {
        switch ($label_justify_content) {
            case 'center':
                $text_align = 'center';
                break;
            case 'end':
                $text_align = 'right';
                break;
            default:
                $text_align = 'left';
        }
        return $text_align;
    }

    public static function get_list_style_icon_svg($properties_icon_std, $default = ''): string
    {
        $icon_std = $default;
        if ($properties_icon_std === 'circle') {
            $icon_std = '<span class="li-icon-std-js"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.3661 12C15.3661 13.8591 13.8591 15.3661 12 15.3661C10.1409 15.3661 8.63386 13.8591 8.63386 12C8.63386 10.1409 10.1409 8.63386 12 8.63386C13.8591 8.63386 15.3661 10.1409 15.3661 12Z" stroke="#333333" stroke-width="1.6"/>
</svg></span>';
        }
        if ($properties_icon_std === 'square') {
            $icon_std = '<span class="li-icon-std-js"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="7.83386" y="7.83386" width="8.33228" height="8.33228" fill="#333333"/>
</svg></span>';
        }
        if ($properties_icon_std === 'disc') {
            $icon_std = '<span class="li-icon-std-js"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.3661 12C15.3661 13.8591 13.8591 15.3661 12 15.3661C10.1409 15.3661 8.63386 13.8591 8.63386 12C8.63386 10.1409 10.1409 8.63386 12 8.63386C13.8591 8.63386 15.3661 10.1409 15.3661 12Z" fill="#333333" stroke="#333333" stroke-width="1.6"/>
</svg></span>';

        }
        return $icon_std;
    }

    public static function detect_single_product_admin_page(): bool
    {

        if (!is_admin()) {
            return false;
        }
        $screen = get_current_screen();

        if ($screen && $screen->post_type === 'product' && $screen->base === 'post') {
            return true;
        }
        return false;
    }

    public static function get_image_alt_by_id($image_id): string
    {
        // Check if the ID is valid
        if (!is_numeric($image_id)) {
            return '';
        }

        // Get the alt text using get_post_meta()
        $alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true);

        // Return the alt text or an empty string if none exists
        return !empty($alt_text) ? $alt_text : '';
    }


    public static function get_updated_component_order($component_id)
    {
        // Fetch stored order or use the default list
        $stored_order = get_post_meta($component_id, 'develux_components_order', true);
        $stored_order = \is_string($stored_order) ? explode(',', $stored_order) : [];

        // Full list of components
        $default_order = [
            'main_title',
            'banner',
            'description',
            'repeater',
            'repeater2',
            'file_repeater'
        ];

        // Ensure stored order has all components from the default list
        $updated_order = array_unique(array_merge($stored_order, $default_order));

        // If order was missing components, update and save
        if (array_diff($updated_order, $stored_order) || array_diff($stored_order, $updated_order)) {
            update_post_meta($component_id, 'develux_components_order', implode(',', $updated_order));
        }
        return get_post_meta($component_id, 'develux_components_order', true);
    }


}