<?php

namespace Services;

use Services\dtos\BannerDto;
use services\dtos\FarazSmsInfoDto;
use Services\dtos\IconDto;
use Services\dtos\ImageDto;
use Services\dtos\MenuItemDto;
use services\dtos\SocialLinkDto;
use Services\enums\SliderType;
use Services\dtos\CategoryDto;
use Services\dtos\PostDto;
use Services\dtos\PostDetailDto;
use Services\dtos\QaDto;
use Services\dtos\LinkDto;
use Services\dtos\FooterColumnDto;
use Services\dtos\FooterDto;
use Services\enums\SocialLinkType;
use WP_Exception;
use WP_Query;
use WPSEO_Breadcrumbs;

interface GeneralServiceInterface
{
    /* @return LinkDto[] */
    public function getBreadcrumb(): array;

    public function getLogo(): ImageDto;

    /* @return  BannerDto[] */
    public function getSlider(SliderType $type): array;

    /* @return  CategoryDto[] */
    public function getCategorySlider(SliderType $type): array;

    /* @return  BannerDto[] */
    public function getGridBanner(SliderType $type): array;

    /* @return  BannerDto[] */
    public function getFullWidthBanner(SliderType $type): array;

    /* @return  ImageDto[] */
    public function getBrandSlider(SliderType $type): array;

    /** @return QaDto[] */
    public function getQaFields(SliderType $type): array;

    public function getFooterLinks(SliderType $type): FooterDto;

    /** @return BannerDto[] */
    public function getSocialLinks(SliderType $type): array;

    /* @return  MenuItemDto[] */
    public function getMenu(string $theme_location): array;
}

class GeneralService implements GeneralServiceInterface
{
    public function getLogo(): ImageDto
    {
        $default_src = esc_url(get_stylesheet_directory_uri() . '/assets/image/logo.png');
        $default_alt = get_bloginfo('name');

        $custom_logo_id = get_theme_mod('custom_logo');

        return $custom_logo_id ?
            ImageDto::build($custom_logo_id, 'full', $default_alt) :
            new ImageDto($default_src, $default_alt);
    }

    public function getMenu(string $theme_location): array
    {
        $menu_id = get_nav_menu_locations()[$theme_location] ?? '';
        $menu_items = wp_get_nav_menu_items($menu_id) ?: [];

        /* @var MenuItemDto[] $items */
        $items = array();

        foreach ($menu_items as $menu_item) {
            $id = $menu_item->ID;
            $parent_id = $menu_item->menu_item_parent;
            $title = $menu_item->title;
            $url = $menu_item->url;

            $icon_id = get_post_meta($id, '_menu_item_icon', true);
            $icon = $icon_id ? IconDto::build($icon_id) : null;

            $items[] = new MenuItemDto($id, $parent_id, $title, $url, $icon);
        }

        return $this->crateMenuTree($items);
    }

    /* @param MenuItemDto[] $items
     * @return  MenuItemDto[]
     */
    private function crateMenuTree(array $items): array
    {
        /* @var MenuItemDto[] $new_items */
        $new_items = array();

        foreach ($items as $item1) {
            if ($item1->parent_id == 0) {
                $new_items[] = $item1;
                continue;
            }
            foreach ($items as $item2) {
                if ($item1->parent_id == $item2->id) {
                    $item2->addChild($item1);
                    break;
                }
            }
        }

        return $new_items;
    }

    /* @return BannerDto[] */
    public function getSlider(SliderType $type): array
    {
        $slider_id = $type->value;
        $slider = get_field($slider_id, 'option');

        /** @var BannerDto[] */
        $banners = [];

        if (!empty($slider) && is_array($slider)) {
            foreach ($slider as $row) {
                $first_slider = $row["hero-slider"];
                $photo_slider = $first_slider["picture"];
                $link_slider = $first_slider["link"]['url'];

                $image = new ImageDto($photo_slider['url'], $photo_slider['alt']);

                $banners[] = new BannerDto($image, $link_slider);
            }
        }

        return $banners;
    }

    public function getPhoneNumber(SliderType $type): string
    {
        $slider_id = $type->value;
        $phone_number = get_field($slider_id, 'option');

        return $phone_number;
    }

    public function getFarazSmsInfo(SliderType $type): ?FarazSmsInfoDto
    {
        $slider_id = $type->value;
        $info = get_field($slider_id, 'option');
        $username = $info["username"];
        $password = $info["password"];
        $pattern_code = $info["pattern-code"];
        $from = $info["from"];

        if (empty($username) || empty($password) || empty($pattern_code) || empty($from)) return null;

        return new FarazSmsInfoDto($username, $password, $pattern_code, $from);
    }


    /**
     * Get category slider based on the slider type.
     *
     * @param SliderType $type
     *
     * @return CategoryDto[]
     */
    public function getCategorySlider(SliderType $type): array
    {
        $slider_id_cat = $type->value; // pro-cat-slider-main
        $slider_cat = get_field($slider_id_cat, 'option');

        /** @var CategoryDto[] */
        $categories = [];

        if (!empty($slider_cat) && is_array($slider_cat)) {
            foreach ($slider_cat as $row) {
                $first_slider_cat = $row["pro-cat-slider-grp"] ?? [];
                $cat_info = $first_slider_cat["category"] ?? null;
                $photo_cat = $first_slider_cat["image"] ?? [];

                $image_url = $photo_cat["url"] ?? '';
                $image_alt = $photo_cat["alt"] ?? '';

                $link_cat = (is_object($cat_info) && isset($cat_info->term_id)) ? get_term_link($cat_info->term_id) : '';
                $title_cat = (is_object($cat_info) && isset($cat_info->name)) ? $cat_info->name : 'دسته‌بندی';

                if ($image_url && $link_cat !== '') {
                    $image = new ImageDto($image_url, $image_alt);
                    $categories[] = new CategoryDto($image, $link_cat, $title_cat);
                }
            }
        }

        return $categories;
    }

    /* @return BannerDto[] */
    public function getGridBanner(SliderType $type): array
    {
        $slider_id = $type->value;
        $slider = get_field($slider_id, 'option');

        /** @var BannerDto[] */
        $banners = [];

        if (!empty($slider) && is_array($slider)) {
            foreach ($slider as $row) {
                $first_slider = $row["banner_group"];
                $photo_slider = $first_slider["picture"];
                $link_slider = $first_slider["link"]['url'] ?? "";

                $image = new ImageDto($photo_slider['url'], $photo_slider['alt']);

                $banners[] = new BannerDto($image, $link_slider);
            }
        }

        return $banners;
    }

    /* @return BannerDto[] */
    public function getFullWidthBanner(SliderType $type): array
    {
        $slider_id = $type->value;
        $slider = get_field($slider_id, 'option');

        /** @var BannerDto[] */
        $banners = [];

        if (!empty($slider)) {
            foreach ($slider as $row) {
                $first_slider = $row["banner_group"];
                $photo_slider = $first_slider["picture"];
                $link_slider = $first_slider["link"]['url'];

                $image = new ImageDto($photo_slider['url'], $photo_slider['alt']);

                $banners[] = new BannerDto($image, $link_slider);
            }
        }

        return $banners;
    }

    /* @return ImageDto[] */
    public function getBrandSlider(SliderType $type): array
    {
        $slider_id = $type->value;
        $slider = get_field($slider_id, 'option');

        /** @var ImageDto[] */
        $image_logo = [];

        if (!empty($slider) && is_array($slider)) {
            foreach ($slider as $row) {
                $image_slider = $row['image-logo'] ?? null;
                if (!is_array($image_slider) || empty($image_slider['url'])) {
                    continue;
                }

                $src = is_string($image_slider['url']) ? $image_slider['url'] : '';
                $alt = is_string($image_slider['alt']) ? $image_slider['alt'] : 'Brand Logo';

                $image_logo[] = new ImageDto($src, $alt);
            }
        }

        return $image_logo;
    }

    /**
     * Get blog posts for a specific offset and number of posts.
     *
     * @param int $offset Number of posts to skip
     * @param int $posts_per_page Number of posts to retrieve
     *
     * @return array{PostDto[], int}
     */
    public function getBlogPosts(int $count = null): array
    {
        global $wp_query;

        $args = [
            'post_type' => 'post',
            'posts_per_page' => $count,
            'order' => 'DESC',
            'orderby' => 'date',
            'post_status' => 'publish',
        ];

        $query = new WP_Query($args);

        if (empty($count)) {
            $query = $wp_query;
        }

        /** @var PostDto[] */
        $result = [];

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $post_id = get_the_ID();

                $title = get_the_title() ?: 'بدون عنوان';
                $image_id = get_post_thumbnail_id($post_id);

                $image = empty($image_id) ? null : ImageDto::build($image_id, 'full', 'بلاگ');

                $link = get_permalink($post_id) ?: '';

                $categories = get_the_category();
                $category_name = '';
                $category_link = '';
                $categories_string = '';

                if (!empty($categories)) {
                    $category_name = esc_html($categories[0]->name);
                    $category_link = get_category_link($categories[0]->term_id);
                    $categories_string = implode(', ', array_map(function ($cat) {
                        return esc_html($cat->name);
                    }, $categories));
                }

                $time = get_post_time('d F Y', $post_id) ?: '';
                $excerpt = get_the_excerpt() ?: '';

                $blog_dto = new PostDto(
                    $title,
                    $image,
                    $link,
                    $categories_string,
                    $category_link,
                    $category_name,
                    $time,
                    $excerpt
                );
                $result[] = $blog_dto;
            }
            wp_reset_postdata();
        }

        $total_pages = $query->max_num_pages;

        return array("posts" => $result, "pages" => $total_pages);
    }

    /**
     * @return PostDetailDto
     */
    public function getPostDetail(): ?PostDetailDto
    {
        global $wp_query;
        $query = $wp_query;

        if ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();

            $title = get_the_title() ?: 'بدون عنوان';

            $image_id = get_post_thumbnail_id($post_id);
            $image = empty($image_id) ? null : ImageDto::build($image_id, 'full', 'بلاگ');

            $link = get_permalink($post_id) ?: '';

            $categories = get_the_category();
            $category_name = '';
            $category_link = '';
            $categories_string = '';

            if (!empty($categories)) {
                $category_name = esc_html($categories[0]->name);
                $category_link = get_category_link($categories[0]->term_id);
                $categories_string = implode(', ', array_map(function ($cat) {
                    return esc_html($cat->name);
                }, $categories));
            }

            $time = get_post_time('d F Y', $post_id) ?: '';
            $content = apply_filters('the_content', get_the_content() ?? '');
            $excerpt = get_the_excerpt($post_id) ?: '';
            $auth_id = get_the_author_meta('ID');
            $auth_name = get_the_author_meta('display_name');
            $auth_link = get_author_posts_url($auth_id);
            $auth_des = get_the_author_meta('description');

            // Get the next post
            $next_post = get_adjacent_post(true, '', false); // false for next post
            $next_post_dto = null;

            if ($next_post) {
                $next_post_id = $next_post->ID;
                $next_title = get_the_title($next_post_id) ?: 'بدون عنوان';

                $next_image_id = get_post_thumbnail_id($next_post_id);
                $next_image = empty($next_image_id) ? null : ImageDto::build($next_image_id, 'full', 'بلاگ');

                $next_link = get_permalink($next_post_id) ?: '';
                $next_categories = get_the_category($next_post_id);
                $next_category_name = '';
                $next_category_link = '';
                $next_categories_string = '';

                if (!empty($next_categories)) {
                    $next_category_name = esc_html($next_categories[0]->name);
                    $next_category_link = get_category_link($next_categories[0]->term_id);
                    $next_categories_string = implode(', ', array_map(function ($cat) {
                        return esc_html($cat->name);
                    }, $next_categories));
                }

                $next_time = get_the_date('d F Y', $next_post_id) ?: '';
                $next_excerpt = get_the_excerpt($next_post_id) ?: '';

                $next_post_dto = new PostDto(
                    $next_title,
                    $next_image,
                    $next_link,
                    $next_categories_string,
                    $next_category_link,
                    $next_category_name,
                    $next_time,
                    $next_excerpt
                );
            }

            $post_dto = new PostDetailDto(
                $title,
                $image,
                $link,
                $categories_string,
                $category_link,
                $category_name,
                $time,
                $content,
                $auth_id,
                $auth_name,
                $auth_link,
                $auth_des,
                $next_post_dto
            );

            wp_reset_postdata();
            return $post_dto;
        }

        return null;
    }


    /**
     * Get Q&A fields based on the slider type.
     *
     * @param SliderType $type
     *
     * @return QaDto[]
     */
    public function getQaFields(SliderType $type): array
    {
        $slider_id = $type->value;
        $repeater_qa = get_field($slider_id, 'option');

        /** @var QaDto[] */
        $qa_items = [];

        if (!empty($repeater_qa) && is_array($repeater_qa)) {
            foreach ($repeater_qa as $row) {
                $suggest_question = $row["question"] ?? '';
                $suggest_answer = $row["answer"] ?? '';

                if ($suggest_question && $suggest_answer) {
                    $qa_items[] = new QaDto($suggest_question, $suggest_answer);
                }
            }
        }

        return $qa_items;
    }

    public function getFooterLinks(SliderType $type): FooterDto
    {
        $slider_id = $type->value;
        $group = get_field($slider_id, 'option') ?: [];

        // Initialize defaults
        $column_one = new FooterColumnDto('', []);
        $column_two = new FooterColumnDto('', []);
        $column_three = null;
        $certificates = [];
        $show_latest_articles = true;

        if (is_array($group)) {
            // Column One
            if (isset($group['footer_col_one_group'])) {
                $col_one = $group['footer_col_one_group'];
                $title = $col_one['title_column'] ?? '';
                $links = [];

                if (!empty($col_one['footer_col_one_repeater']) && is_array($col_one['footer_col_one_repeater'])) {
                    foreach ($col_one['footer_col_one_repeater'] as $row) {
                        if (isset($row['link']) && is_array($row['link'])) {
                            $links[] = new LinkDto(
                                $row['link']['title'] ?? '',
                                $row['link']['url'] ?? '',
                                $row['link']['target'] ?? '_self'
                            );
                        }
                    }
                }
                $column_one = new FooterColumnDto($title, $links);
            }

            // Column Two
            if (isset($group['footer_col_two_group'])) {
                $col_two = $group['footer_col_two_group'];
                $title = $col_two['title_column'] ?? '';
                $links = [];

                if (!empty($col_two['footer_col_two_repeater']) && is_array($col_two['footer_col_two_repeater'])) {
                    foreach ($col_two['footer_col_two_repeater'] as $row) {
                        if (isset($row['link']) && is_array($row['link'])) {
                            $links[] = new LinkDto(
                                $row['link']['title'] ?? '',
                                $row['link']['url'] ?? '',
                                $row['link']['target'] ?? '_self'
                            );
                        }
                    }
                }
                $column_two = new FooterColumnDto($title, $links);
            }

            // Column Three (Articles)
            $show_latest_articles = isset($group['last_article_blog_footer']) ? (bool)$group['last_article_blog_footer'] : true;

            if (!$show_latest_articles && isset($group['footer_col_three_repeater']) && is_array($group['footer_col_three_repeater'])) {
                $links = [];
                foreach ($group['footer_col_three_repeater'] as $row) {
                    if (isset($row['link']) && is_array($row['link'])) {
                        $links[] = new LinkDto(
                            $row['link']['title'] ?? '',
                            $row['link']['url'] ?? '',
                            $row['link']['target'] ?? '_self'
                        );
                    }
                }
                $column_three = new FooterColumnDto('آخرین مقالات', $links);
            } elseif ($show_latest_articles) {
                // Fetch latest articles
                $args = [
                    'post_type' => 'post',
                    'posts_per_page' => 4, // Adjust as needed
                    'post_status' => 'publish',
                    'order' => 'DESC',
                    'orderby' => 'date',
                ];
                $query = new WP_Query($args);
                $links = [];

                if ($query->have_posts()) {
                    while ($query->have_posts()) {
                        $query->the_post();
                        $post_id = get_the_ID();
                        $links[] = new LinkDto(
                            get_the_title() ?: 'بدون عنوان',
                            get_permalink($post_id) ?: '',
                            '_self'
                        );
                    }
                    wp_reset_postdata();
                }
                $column_three = new FooterColumnDto('آخرین مقالات', $links);
            }

            // Certificates (using BannerDto)

            if (isset($group['certificates_links_repeater']) && is_array($group['certificates_links_repeater'])) {
                foreach ($group['certificates_links_repeater'] as $row) {
                    if (isset($row['certificate_group_items'])) {
                        $item = $row['certificate_group_items'];
                        $html_content = $item['html_content'] ?? '';
                        $link = '';
                        $image_src = '';
                        if (preg_match("/<a[^>]*href=['\"](.*?)['\"]/i", $html_content, $link_matches))
                            $link = $link_matches[1];
                        if (preg_match("/<img[^>]*src=['\"](.*?)['\"]/i", $html_content, $image_matches))
                            $image_src = $image_matches[1];

                        if (!empty($item['image']))
                            $image_src = $item['image'];

                        if (!empty($image_src)) {
                            $image = empty($item['image']) ?
                                new ImageDto($image_src, 'گواهی') :
                                ImageDto::build($image_src, 'full', 'گواهی');
                            $certificates[] = new BannerDto($image, $link);
                        }
                    }
                }
            }
        }

        $footer = new FooterDto(
            $column_one,
            $column_two,
            $column_three,
            $certificates,
            $show_latest_articles
        );

        return $footer;
    }


    /**
     * @return SocialLinkDto[]
     */
    public function getSocialLinks(SliderType $type): array
    {
        $social_links_id = $type->value;
        $social_items = get_field($social_links_id, 'option');

        /** @var SocialLinkDto[] $social_links */
        $social_links = [];

        foreach ($social_items as $item) {
            $url = $item['social-item-url'];
            $type = SocialLinkType::from($item['social-item-type']);

            if (!empty($url)) {
                $social_links[] = new SocialLinkDto($type, $url);
            }
        }

        return $social_links;
    }

    /**
     * @return LinkDto[]
     */
    public function getBreadcrumb(): array
    {
        if (class_exists('WPSEO_Breadcrumbs')) {
            $breadcrumbs_instance = WPSEO_Breadcrumbs::get_instance();
            $breadcrumb = $breadcrumbs_instance->get_links();
            $breadcrumb_data = array();

            foreach ($breadcrumb as $crumb) {
                $title = $crumb['text'] ?? '';
                $url = $crumb['url'] ?? '';
                $breadcrumb_data[] = new LinkDto($title, $url, '_self');
            }

            return $breadcrumb_data;
        }

        if ( class_exists( 'RankMath\Frontend\Breadcrumbs' ) ) {
            $rank_math_breadcrumbs = new \RankMath\Frontend\Breadcrumbs();
            $breadcrumbs = $rank_math_breadcrumbs->get_crumbs();

            $breadcrumb_data = array();

            if ( ! empty( $breadcrumbs ) ) {
                foreach ( $breadcrumbs as $crumb ) {
                    $title = $crumb[0] ?? '';
                    $url   = $crumb[1] ?? '';
                    $breadcrumb_data[] = new LinkDto( $title, $url, '_self' );
                }
            }

            return $breadcrumb_data;
        }

        return [];
    }

    public function getPost(int $post_id): PostDto
    {
        $title = get_the_title($post_id) ?: 'بدون عنوان';

        $image_id = get_post_thumbnail_id($post_id);
        $image = empty($image_id) ? null : ImageDto::build($image_id, 'full', 'بلاگ');

        $link = get_permalink($post_id) ?: '';

        $categories = get_the_category($post_id);
        $category_name = '';
        $category_link = '';
        $categories_string = '';

        if (!empty($categories)) {
            $category_name = esc_html($categories[0]->name);
            $category_link = get_category_link($categories[0]->term_id);
            $categories_string = implode(', ', array_map(function ($cat) {
                return esc_html($cat->name);
            }, $categories));
        }

        $time = get_post_time('d F Y', $post_id) ?: '';
        $excerpt = get_the_excerpt($post_id) ?: '';

        return new PostDto(
            $title,
            $image,
            $link,
            $categories_string,
            $category_link,
            $category_name,
            $time,
            $excerpt
        );
    }

    /**
     * @return array{PostDto[]}
     */
    public function getRelatedPosts(int $post_id): array
    {
        $categories = get_the_category($post_id);
        $category_ids = array();

        if (!empty($categories)) {
            foreach ($categories as $category) {
                $category_ids[] = $category->term_id;
            }
        }

        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => 3,
            'post__not_in' => array($post_id),
            'orderby' => 'date',
        );

        if (!empty($category_ids)) {
            $args['category__in'] = $category_ids;
        }

        $query = new WP_Query($args);

        if (!$query->have_posts() && !empty($category_ids)) {
            unset($args['category__in']);
            $query = new WP_Query($args);
        }

        $result = [];

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $post_id = get_the_ID();

                $title = get_the_title() ?: 'بدون عنوان';
                $image_id = get_post_thumbnail_id($post_id);

                $image = empty($image_id) ? null : ImageDto::build($image_id, 'full', 'بلاگ');

                $link = get_permalink($post_id) ?: '';

                $categories = get_the_category();
                $category_name = '';
                $category_link = '';
                $categories_string = '';

                if (!empty($categories)) {
                    $category_name = esc_html($categories[0]->name);
                    $category_link = get_category_link($categories[0]->term_id);
                    $categories_string = implode(', ', array_map(function ($cat) {
                        return esc_html($cat->name);
                    }, $categories));
                }

                $time = get_post_time('d F Y', $post_id) ?: '';
                $excerpt = get_the_excerpt() ?: '';

                $post_dto = new PostDto(
                    $title,
                    $image,
                    $link,
                    $categories_string,
                    $category_link,
                    $category_name,
                    $time,
                    $excerpt
                );
                $result[] = $post_dto;
            }
            wp_reset_postdata();
        }

        return $result;
    }


    /**
     * @throws WP_Exception
     */
    function login(string $username, string $password): void
    {
        $username = trim($username);
        $password = trim($password);

        if (empty($username))
            throw new WP_Exception('نام کاربری نمی‌تواند خالی باشد.');
        if (empty($password))
            throw new WP_Exception('رمز عبور نمی‌تواند خالی باشد.');

        $creds = array(
            'user_login' => sanitize_user($username),
            'user_password' => $password,
            'remember' => true
        );

        $user = wp_signon($creds, false);
        if (is_wp_error($user)) {
            throw new WP_Exception('نام کاربری یا رمز عبور نادرست است.');
        }
    }


    /**
     * @throws WP_Exception
     */
    function send_sms(string $recipient, string $otp_code): void
    {
        $url = 'https://ippanel.com/patterns/pattern';
        $faraz_info = $this->getFarazSmsInfo(SliderType::FarazSmsInfo);

        $data = [
            'username' => $faraz_info->username,
            'password' => $faraz_info->password,
            'from' => $faraz_info->from,
            'to' => $recipient,
            'pattern_code' => $faraz_info->pattern_code,
            'input_data' => json_encode(['code' => $otp_code]),
        ];

        $full_url = $url . '?' . http_build_query($data);

        $handler = curl_init($full_url);
        curl_setopt_array($handler, [
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 10,
        ]);

        $response = curl_exec($handler);
        $http_code = curl_getinfo($handler, CURLINFO_HTTP_CODE);

        if (curl_errno($handler)) {
            $error_msg = curl_error($handler);
            curl_close($handler);
            error_log('IPPANEL SMS cURL Error: ' . $error_msg);
            throw new WP_Exception('مشکلی در ارسال پیامک به وجود آمده است. لطفا دوباره تلاش کنید.');
        }

        curl_close($handler);

        if ($http_code !== 200) {
            error_log('Faraz SMS HTTP Error: ' . $http_code . ' | Response: ' . $response);
            throw new WP_Exception('سرویس پیامک با خطا مواجه شد. لطفا بعدا تلاش کنید.');
        }
    }

    /**
     * @throws WP_Exception
     */
    function sendOtp(string $mobile): void
    {
        $mobile = trim($mobile);
        if (empty($mobile) || !preg_match('/^09[0-9]{9}$/', $mobile)) {
            throw new WP_Exception('شماره موبایل وارد شده معتبر نیست.');
        }

        $otp_code = (string)mt_rand(10000, 99999);
        $transient_key = 'otp_for_' . $mobile;
        $otp_hash = password_hash($otp_code, PASSWORD_DEFAULT);
        set_transient($transient_key, $otp_hash, 180);

        $this->send_sms($mobile, $otp_code);
    }

    /**
     * @throws WP_Exception
     */
    function loginOtp(string $mobile, string $code): void
    {
        $mobile = trim($mobile);
        $code = trim($code);

        if (empty($mobile))
            throw new WP_Exception('موبایل نمی‌توانند خالی باشد.');
        if (empty($code))
            throw new WP_Exception('کد تایید نمی‌توانند خالی باشد.');

        $transient_key = 'otp_for_' . $mobile;
        $stored_hash = get_transient($transient_key);

        if ($stored_hash === false || !password_verify($code, $stored_hash)) {
            throw new WP_Exception('کد تایید نامعتبر است.');
        }

        $users = get_users([
            'meta_key' => 'mobile_number',
            'meta_value' => $mobile,
            'number' => 1,
            'count_total' => false,
        ]);

        $user = $users[0] ?? null;

        if (empty($user)) {
            $user_data = [
                'user_login' => $mobile,
                'user_pass' => wp_generate_password(24, true),
                'display_name' => $mobile,
                'role' => 'subscriber',
            ];

            $user_id = wp_insert_user($user_data);

            if (is_wp_error($user_id)) {
                error_log('Failed to create new user: ' . $user_id->get_error_message());
                throw new WP_Exception('خطایی در ایجاد حساب کاربری رخ داد.');
            }

            update_user_meta($user_id, 'mobile_number', $mobile);
            $user = get_user_by('id', $user_id);
        }

        wp_set_current_user($user->ID, $user->user_login);
        wp_set_auth_cookie($user->ID);
        do_action('wp_login', $user->user_login, $user);

        delete_transient($transient_key);
    }
}