<?php

class Hirosection2W extends \Elementor\Widget_Base {

    private static $hero_attachment_id = 0;
    private static $hero_href = '';
    private static $hero_mobile_href = '';

    public static function output_preload_in_head() {
        $sizes = '(max-width: 768px) 100vw, 792px';

        if (self::$hero_attachment_id) {
            $id = self::$hero_attachment_id;

            $desk_url = wp_get_attachment_image_url($id, '1536x1536') ?: wp_get_attachment_image_url($id, 'large');

            $mob_url = wp_get_attachment_image_url($id, 'medium_large') ?: wp_get_attachment_image_url($id, 'medium');

            if ($desk_url) {
                $type = str_ends_with(strtolower(parse_url($desk_url, PHP_URL_PATH) ?? ''), '.webp') ? ' type="image/webp"' : '';
                echo '<link rel="preload" as="image" media="(min-width:768px)" href="' . esc_url($desk_url) . '" fetchpriority="high"' . $type . '>' . "\n";
            }

            if ($mob_url) {
                $type = str_ends_with(strtolower(parse_url($mob_url, PHP_URL_PATH) ?? ''), '.webp') ? ' type="image/webp"' : '';
                echo '<link rel="preload" as="image" media="(max-width:767px)" href="' . esc_url($mob_url) . '" fetchpriority="high"' . $type . '>' . "\n";
            }
            return;
        }

        if (self::$hero_href) {
            $type = str_ends_with(strtolower(parse_url(self::$hero_href, PHP_URL_PATH) ?? ''), '.webp') ? ' type="image/webp"' : '';
            echo '<link rel="preload" as="image" media="(min-width:768px)" href="' . esc_url(self::$hero_href) . '" fetchpriority="high"' . $type . '>' . "\n";
        }
        if (self::$hero_mobile_href) {
            $type = str_ends_with(strtolower(parse_url(self::$hero_mobile_href, PHP_URL_PATH) ?? ''), '.webp') ? ' type="image/webp"' : '';
            echo '<link rel="preload" as="image" media="(max-width:767px)" href="' . esc_url(self::$hero_mobile_href) . '" fetchpriority="high"' . $type . '>' . "\n";
        }
    }

    public function get_name(): string { return 'hirosection2w'; }
    public function get_title(): string { return 'هیرو سکشن 2'; }
    public function get_icon(): string { return 'eicon-single-page'; }
    public function get_categories(): array { return [ 'exclusive-widget' ]; }
    public function get_keywords(): array { return [ 'هیرو سکشن' ]; }

    protected function register_controls() {
        $this->start_controls_section('Hirosection', [
            'label' => 'تنظیمات هیروسکشن',
            'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
        ]);
        $this->add_control('cofe_img', [
            'label'       => 'تصویر کافه',
            'description' => 'برای بهترین نتیجه از تصویر WebP فشرده‌شده (زیر 200KB) با عرض حداکثر 1536px برای دسکتاپ و 768px برای موبایل استفاده کنید.',
            'type'        => \Elementor\Controls_Manager::MEDIA,
            'default'     => [ 'url' => get_template_directory_uri() . '/assets/images/cofe/Cafe-store.webp' ],
        ]);

        $this->add_control('Hirosection_img', [
            'label'       => 'لوگو کافه یا رستوران',
            'description' => 'برای نتیجه بهتر از تصویر با فرمت SVG یا WebP با نسبت تصویر مربع استفاده کنید',
            'type'        => \Elementor\Controls_Manager::MEDIA,
            'default'     => [ 'url' => get_template_directory_uri() . '/assets/images/Logo/GhahveDar-logo.svg' ],
        ]);

        $this->add_control('Hirosection_name', [
            'type'        => \Elementor\Controls_Manager::TEXT,
            'label'       => 'نام کافه یا رستوران',
            'placeholder' => 'نام کافه',
            'default'     => 'کافیتو',
        ]);

        $this->add_control('caffito_settings_note', [
            'type'  => \Elementor\Controls_Manager::RAW_HTML,
            'raw'   => sprintf(
                '<div class="elementor-panel-alert elementor-panel-alert-info" dir="rtl" style="line-height:1.7">
            برای تعیین <b>باز / بسته بودن سفارش‌گیری</b> به
            <a href="%s" target="_blank" rel="noopener">بخش ساعت سفارش‌گیری</a>
            مراجعه کنید.
        </div>',
                esc_url( admin_url('admin.php?page=caffitooption') )
            ),
            'content_classes' => 'elementor-descriptor',
        ]);

        $this->end_controls_section();
    }

    protected function render() {
        $s = $this->get_settings_for_display();

        $orders_mode        = 'manual';
        $orders_open_manual = true;
        $open_time          = '09:00';
        $close_time         = '23:00';

        if ( function_exists('csf_get_option') ) {
            $orders_mode        = csf_get_option('caffitooption', 'orders_mode', 'manual');
            $orders_open_manual = (bool) csf_get_option('caffitooption', 'is_accepting_orders', true);
            $open_time          = csf_get_option('caffitooption', 'open_time', '09:00');
            $close_time         = csf_get_option('caffitooption', 'close_time', '23:00');
        } else {
            $opt = get_option('caffitooption');
            if ( is_array($opt) ) {
                $orders_mode        = $opt['orders_mode'] ?? 'manual';
                $orders_open_manual = isset($opt['is_accepting_orders']) ? (bool) $opt['is_accepting_orders'] : true;
                $open_time          = $opt['open_time']  ?? '09:00';
                $close_time         = $opt['close_time'] ?? '23:00';
            }
        }

        $orders_open = $orders_open_manual;
        if ( $orders_mode === 'auto' ) {
            $nowM   = $this->tehran_minutes_now();
            $openM  = $this->to_minutes($open_time);
            $closeM = $this->to_minutes($close_time);

            if ($openM !== null && $closeM !== null) {
                if ($openM === $closeM) {
                    $orders_open = false;
                } elseif ($openM < $closeM) {
                    $orders_open = ($nowM >= $openM && $nowM < $closeM);
                } else {
                    $orders_open = ($nowM >= $openM || $nowM < $closeM);
                }
            } else {
                $orders_open = $orders_open_manual;
            }
        }

        $bg_id     = intval($s['cofe_img']['id'] ?? 0);
        $bg_url    = esc_url($s['cofe_img']['url'] ?? '');
        $logo_url  = esc_url($s['Hirosection_img']['url'] ?? '');
        $name_attr = esc_attr(wp_strip_all_tags($s['Hirosection_name'] ?? ''));
        $name_html = esc_html($s['Hirosection_name'] ?? '');
        $desc_html = esc_html($s['Hirosection_description'] ?? '');
        $addr_html = esc_html($s['_address'] ?? '');

        if (!has_action('wp_head', [__CLASS__, 'output_preload_in_head'])) {
            if ($bg_id) {
                self::$hero_attachment_id = $bg_id;
                self::$hero_href = wp_get_attachment_image_url($bg_id, '1536x1536') ?: wp_get_attachment_image_url($bg_id, 'large') ?: '';
                self::$hero_mobile_href = wp_get_attachment_image_url($bg_id, 'medium_large') ?: wp_get_attachment_image_url($bg_id, 'medium') ?: '';
            } elseif ($bg_url) {
                self::$hero_href = $bg_url;
            }
            if (self::$hero_attachment_id || self::$hero_href || self::$hero_mobile_href) {
                add_action('wp_head', [__CLASS__, 'output_preload_in_head'], 0);
            }
        }

        $status_text = $orders_open ? 'سفارش می‌پذیریم' : 'موقتاً سفارش نمی‌پذیریم';
        $token       = $orders_open ? 'var(--green)' : 'var(--red)';
        $big_bg      = 'background-color: color-mix(in srgb, ' . $token . ' 40%, transparent);';
        $small_style = 'background-color: ' . $token . '; box-shadow: 0 0 5px ' . $token . ';';

        $big_bg_attr      = esc_attr($big_bg);
        $small_style_attr = esc_attr($small_style);
        $status_html      = esc_html($status_text);


        echo '<style>
            .hero-section2{position:relative; overflow:hidden; background-image:none !important; background-blend-mode:normal !important;}
            .hero-section2 .hero-section2-media{position:absolute; inset:0; display:block; z-index:0; block-size:100%; inline-size:100%;}
            .hero-section2 .hero-section2-media img{width:100%; height:100%; object-fit:cover; object-position:center; display:block;}
            .hero-section2-gradient{position:relative; z-index:1;}
        </style>' . "\n";

        $sizes_attr = '(max-width: 768px) 100vw, 792px';
        $picture_html = '';

        if ($bg_id) {
            $desk_src = wp_get_attachment_image_url($bg_id, '1536x1536') ?: wp_get_attachment_image_url($bg_id, 'large');
            $mob_src = wp_get_attachment_image_url($bg_id, 'medium_large') ?: wp_get_attachment_image_url($bg_id, 'medium');

            $full_dims = wp_get_attachment_image_src($bg_id, '1536x1536') ?: wp_get_attachment_image_src($bg_id, 'large');
            $w = !empty($full_dims[1]) ? intval($full_dims[1]) : 0;
            $h = !empty($full_dims[2]) ? intval($full_dims[2]) : 0;
            $wh_attr = ($w && $h) ? ' width="' . esc_attr($w) . '" height="' . esc_attr($h) . '"' : '';

            $img_src = $desk_src ?: $bg_url;
            $img_src_attr = esc_url($img_src);

            $picture_html = '<picture class="hero-section2-media" aria-hidden="true">';
            if ($mob_src) {
                $picture_html .= '<source media="(max-width:767px)" srcset="' . esc_url($mob_src) . '" sizes="100vw">';
            }
            $picture_html .= '<img class="hero-section2-bg" src="' . $img_src_attr . '" loading="eager" fetchpriority="high" decoding="async" alt=""' . $wh_attr . '>';
            $picture_html .= '</picture>';
        } elseif ($bg_url) {
            $picture_html = '<img class="hero-section2-media hero-section2-bg" src="' . esc_url($bg_url) . '" loading="eager" fetchpriority="high" decoding="async" alt="">';
        }

        echo <<<HTML
<section class="hero-section-container">
    <div class="hero-section2">
        {$picture_html}
        <div class="hero-section2-gradient">
            <div class="hero-section2-box">
                <div class="hero-section2-right">
                    <div class="hero-section2-img">
                        <img src="{$logo_url}" alt="{$name_attr}" />
                    </div>
                    <h1>{$name_html}</h1>
                </div>

                <div class="hero-section-pulsing-dot-order">
                    <div class="hero-section-pulsing-dot" aria-hidden="true">
                        <div class="hero-section-pulsing-dot-big" style="{$big_bg_attr}"></div>
                        <div class="hero-section-pulsing-dot-small" style="{$small_style_attr}"></div>
                    </div>
                    <span class="hero-section-order">{$status_html}</span>
                </div>
            </div>
        </div>
    </div>
</section>
HTML;
    }


    private function get_tehran_now(): \DateTime {
        $cache_key = 'caffito_tehran_now_ts';
        $cached    = get_transient($cache_key);
        if ($cached) {
            try {
                $tz = new \DateTimeZone('+03:30');
                return (new \DateTime('@' . (int)$cached))->setTimezone($tz);
            } catch (\Exception $e) {}
        }

        $resp = wp_remote_get('https://worldtimeapi.org/api/timezone/Asia/Tehran', [
            'timeout' => 3,
            'headers' => ['Accept' => 'application/json'],
        ]);

        if (!is_wp_error($resp) && wp_remote_retrieve_response_code($resp) === 200) {
            $data = json_decode(wp_remote_retrieve_body($resp), true);
            if (!empty($data['datetime'])) {
                try {
                    $dt = new \DateTime($data['datetime']);
                    set_transient($cache_key, $dt->getTimestamp(), 30);
                    return $dt;
                } catch (\Exception $e) {}
            } elseif (!empty($data['unixtime'])) {
                try {
                    $tz = new \DateTimeZone('+03:30');
                    $dt = (new \DateTime('@' . (int)$data['unixtime']))->setTimezone($tz);
                    set_transient($cache_key, $dt->getTimestamp(), 30);
                    return $dt;
                } catch (\Exception $e) {}
            }
        }

        try {
            $tz = new \DateTimeZone('+03:30');
            return new \DateTime('now', $tz);
        } catch (\Exception $e) {
            return new \DateTime();
        }
    }

    private function tehran_minutes_now(): int {
        $now = $this->get_tehran_now();
        return ((int)$now->format('H')) * 60 + (int)$now->format('i');
    }

    private function normalize_time(string $str): string {
        $s = trim($str);
        $map = ['۰'=>'0','۱'=>'1','۲'=>'2','۳'=>'3','۴'=>'4','۵'=>'5','۶'=>'6','۷'=>'7','۸'=>'8','۹'=>'9',
            '٠'=>'0','١'=>'1','٢'=>'2','٣'=>'3','٤'=>'4','٥'=>'5','٦'=>'6','٧'=>'7','٨'=>'8','٩'=>'9'];
        $s = strtr($s, $map);
        $s = str_replace(['٫','،','؛','.', '／','/','\\','|',' '], ':', $s);
        $s = preg_replace('/[^0-9:]/', '', $s);
        if (preg_match('/^\d{1,2}$/', $s)) $s .= ':00';
        return $s;
    }

    private function to_minutes($hhmm) : ?int {
        if (!is_string($hhmm)) return null;
        $t = $this->normalize_time($hhmm);
        if (!preg_match('/^(\d{1,2}):(\d{1,2})$/', $t, $m)) return null;
        $h=(int)$m[1]; $i=(int)$m[2];
        if ($h<0||$h>23||$i<0||$i>59) return null;
        return $h*60 + $i;
    }
}