<?php
/**
 * Shared helpers and source content extracted from the static HTML.
 *
 * @package ALFASMART
 */

if (! defined('ABSPATH')) {
    exit;
}

function alfasmart_asset($path)
{
    return ALFASMART_URI . '/assets/' . ltrim($path, '/');
}

function alfasmart_img($file)
{
    return ALFASMART_IMG_URI . ltrim($file, '/');
}

function alfasmart_url($slug)
{
    $page = get_page_by_path($slug);

    if ($page) {
        if (function_exists('pll_get_post') && function_exists('pll_current_language')) {
            $translated_id = pll_get_post($page->ID, pll_current_language('slug'));
            if ($translated_id) {
                return get_permalink($translated_id);
            }
        }

        return get_permalink($page);
    }

    return user_trailingslashit(home_url('/' . trim($slug, '/') . '/'));
}

function alfasmart_html($html)
{
    return wp_kses($html, array(
        'br'     => array(),
        'span'   => array('class' => true, 'aria-hidden' => true),
        'strong' => array('class' => true, 'aria-hidden' => true),
        'em'     => array(),
        'i'      => array('class' => true, 'aria-hidden' => true),
    ));
}

function alfasmart_highlight_text($text, $highlight)
{
    $text = (string) $text;
    $highlight = trim((string) $highlight);

    if ($highlight === '' || stripos($text, '<span') !== false) {
        return alfasmart_html($text);
    }

    $quoted = preg_quote($highlight, '/');
    $text = preg_replace('/(' . $quoted . ')/i', '<span>$1</span>', $text, 1);

    return alfasmart_html($text);
}

function alfasmart_get_option($key, $fallback = '')
{
    if (function_exists('get_field')) {
        $lang = function_exists('alfasmart_lang') ? alfasmart_lang() : '';

        if ('ar' === $lang) {
            foreach (array('option_' . $lang, 'options_' . $lang) as $localized_post_id) {
                $value = get_field($key, $localized_post_id);
                if ($value !== null && $value !== false && $value !== '') {
                    return $value;
                }
            }
        }

        foreach (array('option', 'options') as $option_post_id) {
            $value = get_field($key, $option_post_id);
            if ($value !== null && $value !== false && $value !== '') {
                return $value;
            }
        }

        if ($lang && 'ar' !== $lang) {
            foreach (array('option_' . $lang, 'options_' . $lang) as $localized_post_id) {
                $value = get_field($key, $localized_post_id);
                if ($value !== null && $value !== false && $value !== '') {
                    return $value;
                }
            }
        }
    }

    return $fallback;
}

function alfasmart_get_field($key, $fallback = '', $post_id = null)
{
    if (function_exists('get_field')) {
        $value = get_field($key, $post_id);
        if ($value !== null && $value !== false && $value !== '') {
            return alfasmart_prepare_field_output($key, $value);
        }
    }

    return $fallback;
}

function alfasmart_prepare_field_output($key, $value)
{
    if (is_string($value) && preg_match('/(?:^|_)url$/', (string) $key)) {
        return alfasmart_normalize_internal_url($value);
    }

    return $value;
}

function alfasmart_normalize_internal_url($url)
{
    $url = trim((string) $url);

    if ('' === $url) {
        return $url;
    }

    $home_host = wp_parse_url(home_url('/'), PHP_URL_HOST);
    $url_host  = wp_parse_url($url, PHP_URL_HOST);

    if ($url_host && $home_host && strtolower($url_host) !== strtolower($home_host)) {
        return $url;
    }

    $query = wp_parse_url($url, PHP_URL_QUERY);
    if (! $query) {
        return $url;
    }

    parse_str($query, $query_vars);

    if (! empty($query_vars['page_id'])) {
        $post_id = absint($query_vars['page_id']);

        if ($post_id && function_exists('pll_get_post') && function_exists('pll_current_language')) {
            $translated_id = pll_get_post($post_id, pll_current_language('slug'));
            if ($translated_id) {
                $post_id = (int) $translated_id;
            }
        }

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

        return $permalink ?: $url;
    }

    if (! empty($query_vars['post_type']) && post_type_exists($query_vars['post_type'])) {
        $archive = get_post_type_archive_link(sanitize_key($query_vars['post_type']));

        return $archive ?: $url;
    }

    return $url;
}

function alfasmart_post_matches_current_lang($post_id, $lang)
{
    if (! $post_id || ! $lang || ! function_exists('pll_get_post_language')) {
        return true;
    }

    return pll_get_post_language($post_id) === $lang;
}

function alfasmart_add_home_candidate(&$page_ids, $post_id, $lang)
{
    $post_id = absint($post_id);

    if ($post_id && 'page' === get_post_type($post_id) && alfasmart_post_matches_current_lang($post_id, $lang)) {
        $page_ids[] = $post_id;
    }
}

function alfasmart_get_home_field($key, $fallback = '')
{
    $front_page_id = (int) get_option('page_on_front');
    $current_id    = (int) get_queried_object_id();
    $current_lang  = function_exists('pll_current_language') ? pll_current_language('slug') : '';
    $page_ids      = array();

    alfasmart_add_home_candidate($page_ids, $current_id, $current_lang);

    if ($front_page_id && $current_lang && function_exists('pll_get_post')) {
        $translated_front_id = pll_get_post($front_page_id, $current_lang);
        alfasmart_add_home_candidate($page_ids, $translated_front_id, $current_lang);
    }

    foreach (array('ar' === $current_lang ? 'ar-home' : 'home', 'home', 'ar-home') as $home_slug) {
        $home_page = get_page_by_path($home_slug);
        if ($home_page) {
            alfasmart_add_home_candidate($page_ids, $home_page->ID, $current_lang);
        }
    }

    foreach (array_values(array_unique(array_filter(array_map('absint', $page_ids)))) as $page_id) {
        $page_value = alfasmart_get_field($key, null, $page_id);
        if ($page_value !== null && $page_value !== false && $page_value !== '') {
            return alfasmart_prepare_field_output($key, $page_value);
        }
    }

    $option_value = alfasmart_get_option($key, null);
    if ($option_value !== null && $option_value !== false && $option_value !== '') {
        return alfasmart_prepare_field_output($key, $option_value);
    }

    if (! $current_lang || 'en' === $current_lang) {
        $front_value = alfasmart_get_field($key, null, $front_page_id);
        if ($front_value !== null && $front_value !== false && $front_value !== '') {
            return alfasmart_prepare_field_output($key, $front_value);
        }
    }

    return alfasmart_get_field($key, $fallback);
}

function alfasmart_get_option_image_url($key, $fallback_file = '')
{
    $image = alfasmart_get_option($key);

    if (is_array($image) && ! empty($image['url'])) {
        return $image['url'];
    }

    if (is_numeric($image)) {
        $url = wp_get_attachment_image_url((int) $image, 'full');
        if ($url) {
            return $url;
        }
    }

    if (is_string($image) && filter_var($image, FILTER_VALIDATE_URL)) {
        return $image;
    }

    return $fallback_file ? alfasmart_img($fallback_file) : '';
}

function alfasmart_get_image_url($value, $fallback_file = '')
{
    if (is_array($value) && ! empty($value['url'])) {
        return $value['url'];
    }

    if (is_numeric($value)) {
        $url = wp_get_attachment_image_url((int) $value, 'full');
        if ($url) {
            return $url;
        }
    }

    if (is_string($value) && filter_var($value, FILTER_VALIDATE_URL)) {
        return $value;
    }

    return $fallback_file ? alfasmart_img($fallback_file) : '';
}

function alfasmart_normalize_icon_class($icon)
{
    if (is_array($icon)) {
        foreach (array('class', 'value', 'id', 'html', 'element') as $key) {
            if (! empty($icon[$key])) {
                return alfasmart_normalize_icon_class($icon[$key]);
            }
        }

        return '';
    }

    if (is_string($icon)) {
        $icon = trim($icon);

        if ($icon === '') {
            return '';
        }

        if (preg_match('/class=["\']([^"\']+)["\']/i', $icon, $matches)) {
            return sanitize_text_field($matches[1]);
        }

        $icon = wp_strip_all_tags($icon);
        $icon = html_entity_decode($icon, ENT_QUOTES, get_bloginfo('charset'));

        if (preg_match('/\b(?:fas|far|fab|fal|fad|fa-solid|fa-regular|fa-brands|fa-light|fa-duotone)\b/', $icon)) {
            return sanitize_text_field($icon);
        }

        if (preg_match('/\bfa-[a-z0-9-]+\b/i', $icon)) {
            return sanitize_text_field('fa-solid ' . $icon);
        }

        return sanitize_text_field($icon);
    }

    return '';
}

function alfasmart_render_icon($icon_type, $icon, $image = null, $wrapper_class = '', $fallback_icon = 'fa-solid fa-circle')
{
    $icon_type = $icon_type ?: 'icon';

    if ('image' === $icon_type) {
        $image_url = alfasmart_get_image_url($image);
        $image_alt = '';
        $width     = 48;
        $height    = 48;

        if (is_array($image)) {
            $image_alt = $image['alt'] ?? '';
            $width     = ! empty($image['width']) ? (int) $image['width'] : $width;
            $height    = ! empty($image['height']) ? (int) $image['height'] : $height;
        }

        if ($image_url) {
            printf(
                '<span class="%s"><img src="%s" alt="%s" width="%d" height="%d" loading="lazy" decoding="async"></span>',
                esc_attr($wrapper_class),
                esc_url($image_url),
                esc_attr($image_alt),
                esc_attr($width),
                esc_attr($height)
            );
            return;
        }
    }

    $icon_class = alfasmart_normalize_icon_class($icon) ?: $fallback_icon;
    printf(
        '<span class="%s"><i class="%s" aria-hidden="true"></i></span>',
        esc_attr($wrapper_class),
        esc_attr($icon_class)
    );
}

function alfasmart_company_items()
{
    return array(
        array(
            'title'       => 'MLS Technology Network',
            'category'    => 'Technology',
            'description' => 'Smart digital systems and business technology solutions.',
            'image'       => 'group1.webp',
            'url'         => get_post_type_archive_link('companies') ?: home_url('/companies/'),
        ),
        array(
            'title'       => 'My Game Sports Events Marketing',
            'category'    => 'Sports & Events',
            'description' => 'Event marketing, tournament organization, and professional sports services.',
            'image'       => 'group2.webp',
            'url'         => get_post_type_archive_link('companies') ?: home_url('/companies/'),
        ),
        array(
            'title'       => 'Alfa Smart for Investment',
            'category'    => 'Investment & Management',
            'description' => 'Strategic investment and enterprise management company.',
            'image'       => 'group3.webp',
            'url'         => get_post_type_archive_link('companies') ?: home_url('/companies/'),
        ),
        array(
            'title'       => 'Ashlar General Trading L.L.C',
            'category'    => 'General Trading',
            'description' => 'Sourcing, supply, and market-driven trading solutions.',
            'image'       => 'group4.webp',
            'url'         => get_post_type_archive_link('companies') ?: home_url('/companies/'),
        ),
    );
}

function alfasmart_service_items()
{
    return array(
        array('title' => 'General Trading', 'icon_type' => 'icon', 'icon' => 'fa-solid fa-chart-simple', 'description' => 'Managing the sourcing, movement, and supply of a wide range of products across different sectors.'),
        array('title' => 'Global Sourcing', 'icon_type' => 'icon', 'icon' => 'fa-solid fa-globe', 'description' => 'Connecting with trusted suppliers and identifying reliable procurement opportunities across international markets.'),
        array('title' => 'Supply Chain & Logistics', 'icon_type' => 'icon', 'icon' => 'fa-solid fa-truck', 'description' => 'Supporting efficient product flow through coordinated distribution, handling, and operational planning.'),
        array('title' => 'Business Partnerships', 'icon_type' => 'icon', 'icon' => 'fa-solid fa-briefcase', 'description' => 'Creating strong long-term relationships with clients, suppliers, and commercial collaborators.'),
        array('title' => 'Market Expansion', 'icon_type' => 'icon', 'icon' => 'fa-solid fa-bullseye', 'description' => 'Helping businesses approach new regions and opportunities with informed commercial direction.'),
        array('title' => 'Strategic Investment', 'icon_type' => 'icon', 'icon' => 'fa-solid fa-arrow-trend-up', 'description' => 'Identifying and capitalizing on high-value opportunities to drive sustainable long-term growth.'),
    );
}

function alfasmart_default_service_icon($title)
{
    $icons = array(
        'general trading'            => 'fa-solid fa-chart-simple',
        'global sourcing'            => 'fa-solid fa-globe',
        'supply chain & logistics'   => 'fa-solid fa-truck',
        'supply chain logistics'     => 'fa-solid fa-truck',
        'business partnerships'      => 'fa-solid fa-briefcase',
        'market expansion'           => 'fa-solid fa-bullseye',
        'strategic investment'       => 'fa-solid fa-arrow-trend-up',
    );

    $key = strtolower(wp_strip_all_tags((string) $title));
    $key = str_replace('&amp;', '&', $key);

    return $icons[$key] ?? 'fa-solid fa-chart-simple';
}

function alfasmart_presence_feature_items()
{
    return array(
        array('icon_type' => 'icon', 'icon' => 'fa-solid fa-shield-halved', 'title' => 'Luxury visual direction', 'description' => 'Dark sophisticated surfaces, elegant typography, and warm accent lighting that communicate high value.'),
        array('icon_type' => 'icon', 'icon' => 'fa-solid fa-globe', 'title' => 'Strong brand positioning', 'description' => 'A clean narrative structure designed to elevate perception and present ALPHA Smart as a premium business group.'),
        array('icon_type' => 'icon', 'icon' => 'fa-solid fa-bolt', 'title' => 'Executive-level presentation', 'description' => 'Thoughtful spacing, subtle animations, and visual restraint to create a calm and powerful user experience.'),
        array('icon_type' => 'icon', 'icon' => 'fa-solid fa-layer-group', 'title' => 'Modular company showcase', 'description' => 'Interactive company cards with popup details for each subsidiary, keeping the page rich yet controlled.'),
    );
}

function alfasmart_about_default_fields()
{
    return array(
        'about_hero_kicker'       => 'About Us',
        'about_hero_title'        => 'Driven by Smart Trading, <span>Defined by Value</span>',
        'about_hero_highlight_text' => 'Defined by Value',
        'about_hero_highlight_color' => '#f5b400',
        'about_hero_description'  => 'ALPHA Smart is a diversified business group built on strategic trading, investment insight, and operational excellence. We connect markets, industries, and opportunities to deliver sustainable growth and long-term value.',
        'about_who_title'         => 'Who We Are',
        'about_who_description'   => 'ALPHA Smart is a UAE-based holding group <br> specializing in general trading, investment, and business development across multiple sectors. With a flexible and market-driven approach, the company <br> operates through a network of specialized businesses, each contributing to a unified vision of growth, diversification, and innovation.',
        'about_intro_kicker'      => 'About Alpha Smart',
        'about_intro_title'       => 'A group built on trust, clarity, and commercial strength.',
        'about_intro_copy'        => '<p>ALPHA Smart is a Dubai-based trading group with a forward-looking mindset and a broad commercial scope.</p><p>Operating in general trading, the company is positioned to serve diverse industries through strategic sourcing, market insight, and value-driven execution.</p>',
        'about_intro_muted_copy'  => 'We specialize in a wide range of construction services, including residential, commercial, and industrial projects. From initial design to final inspection, we work closely with our clients to understand their unique needs and vision.',
        'about_intro_checklist'   => array(
            array('item' => 'Unmatched Expertise with Decades of Experience'),
            array('item' => 'Commitment to Quality and Precision'),
            array('item' => 'Sustainable and Responsible Building Practices'),
        ),
        'about_intro_slides'      => array(
            array('title' => '01 // The Vision', 'copy' => 'To become a leading regional trading group recognized for reliability, diversification, and strategic impact.', 'image' => ''),
            array('title' => '02 // Our Mission', 'copy' => 'To connect markets with intelligent trading solutions, transparent partnerships, and disciplined execution across every business sector.', 'image' => ''),
            array('title' => '03 // Our Values', 'copy' => 'To build long-term commercial value through trust, reliability, strategic diversification, and responsible business growth.', 'image' => ''),
        ),
        'about_info_cards'        => array(
            array('icon_type' => 'icon', 'icon' => 'fa-solid fa-arrow-trend-up', 'title' => 'Our Mission', 'description' => 'To drive value through intelligent trading, strong partnerships, and efficient business management, while continuously expanding into new opportunities and markets.', 'style_class' => 'as-about-info-card-mission'),
            array('icon_type' => 'icon', 'icon' => 'fa-solid fa-bullseye', 'title' => 'Our Vision', 'description' => 'To become a leading regional business group recognized for delivering smart trading solutions, strategic investments, and sustainable business growth.', 'style_class' => 'as-about-info-card-vision'),
        ),
        'about_what_title'        => 'What We Do',
        'about_what_description'  => 'We operate across key business areas to create a balanced and scalable business ecosystem.',
        'about_business_areas'    => array(
            array('label' => 'Investment & Business Development'),
            array('label' => 'General Trading & Distribution'),
            array('label' => 'Enterprise Management'),
            array('label' => 'Strategic Partnerships'),
            array('label' => 'Global Sourcing & Supply Chain'),
        ),
        'about_text_cards'        => array(
            array('title' => 'Our Business Model', 'description' => 'Our model is built on diversification and integration. By combining trading, investment, and operational management, ALPHA Smart creates a strong and adaptable business structure that responds effectively to market changes.'),
            array('title' => 'Growth & Expansion', 'description' => 'ALPHA Smart is continuously expanding its footprint by entering new markets, diversifying its investment portfolio, and building strong partnerships with global and regional players. We focus on identifying high-potential opportunities and transforming them into scalable and sustainable business ventures.'),
        ),
        'about_cta_title'         => 'Let\'s Build the Future Together',
        'about_cta_description'   => 'Partner with ALPHA Smart and be part of a business ecosystem designed for growth, innovation, and long-term success.',
        'about_cta_primary_text'  => 'Contact Us',
        'about_cta_primary_url'   => alfasmart_url('contact'),
        'about_cta_secondary_text'=> 'Explore Our Companies',
        'about_cta_secondary_url' => get_post_type_archive_link('companies') ?: home_url('/companies/'),
        'about_values_title'      => 'Our Core Values',
        'about_values'            => array(
            array('title' => 'Integrity', 'description' => 'We operate with transparency, trust, and accountability in every relationship and decision.'),
            array('title' => 'Excellence', 'description' => 'We are committed to delivering high-quality performance and measurable results.'),
            array('title' => 'Innovation', 'description' => 'We embrace smart, modern, and forward-looking solutions to create lasting impact.'),
            array('title' => 'Partnership', 'description' => 'We believe strong relationships are the foundation of long-term success.'),
            array('title' => 'Growth', 'description' => 'We focus on sustainable expansion and continuous value creation.'),
            array('title' => 'Integrity', 'description' => 'We operate with transparency, trust, and accountability in every relationship and decision.'),
        ),
    );
}

function alfasmart_get_about_field($key, $fallback = '')
{
    $defaults = alfasmart_about_default_fields();
    return alfasmart_get_field($key, $fallback ?: ($defaults[$key] ?? ''), get_the_ID());
}

function alfasmart_footer_links()
{
    return array(
        array('label' => alfasmart_text('About Us', 'من نحن'), 'url' => alfasmart_url('about')),
        array('label' => alfasmart_text('Services', 'الخدمات'), 'url' => get_post_type_archive_link('services') ?: home_url('/services/')),
        array('label' => alfasmart_text('Companies', 'الشركات'), 'url' => get_post_type_archive_link('companies') ?: home_url('/companies/')),
        array('label' => alfasmart_text('Contact Us', 'اتصل بنا'), 'url' => alfasmart_url('contact')),
    );
}

function alfasmart_lang()
{
    return function_exists('pll_current_language') ? pll_current_language('slug') : 'en';
}

function alfasmart_text($english, $arabic = '')
{
    return ('ar' === alfasmart_lang() && $arabic !== '') ? $arabic : $english;
}

function alfasmart_is_translated_page($slug)
{
    if (! is_page()) {
        return false;
    }

    $page = get_page_by_path($slug);
    if (! $page) {
        return false;
    }

    if (is_page($page->ID)) {
        return true;
    }

    if (function_exists('pll_get_post')) {
        $translated_id = pll_get_post($page->ID, alfasmart_lang());
        return $translated_id && is_page($translated_id);
    }

    return false;
}

function alfasmart_nav_links()
{
    return array(
        array('label' => alfasmart_text('Home', 'الرئيسية'), 'url' => function_exists('pll_home_url') ? pll_home_url(alfasmart_lang()) : home_url('/')),
        array('label' => alfasmart_text('About Us', 'من نحن'), 'url' => alfasmart_url('about')),
        array('label' => alfasmart_text('Companies', 'الشركات'), 'url' => get_post_type_archive_link('companies') ?: home_url('/companies/')),
        array('label' => alfasmart_text('Services', 'الخدمات'), 'url' => get_post_type_archive_link('services') ?: home_url('/services/')),
        array('label' => alfasmart_text('Contact', 'اتصل بنا'), 'url' => alfasmart_url('contact')),
    );
}

function alfasmart_query_posts_or_fallback($post_type, $fallback)
{
    $query = new WP_Query(array(
        'post_type'      => $post_type,
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'orderby'        => array('menu_order' => 'ASC', 'date' => 'ASC'),
        'no_found_rows'  => true,
    ));

    if (! $query->have_posts()) {
        return $fallback;
    }

    $items = array();
    while ($query->have_posts()) {
        $query->the_post();
        $items[] = array(
            'id'          => get_the_ID(),
            'title'       => get_the_title(),
            'category'    => alfasmart_get_field('company_category', '', get_the_ID()),
            'icon_type'   => alfasmart_get_field('icon_type', 'icon', get_the_ID()),
            'icon'        => alfasmart_get_field('service_icon', alfasmart_default_service_icon(get_the_title()), get_the_ID()),
            'icon_image'  => alfasmart_get_field('icon_image', '', get_the_ID()),
            'description' => get_the_excerpt() ?: wp_trim_words(wp_strip_all_tags(get_the_content()), 22),
            'image_url'   => get_the_post_thumbnail_url(get_the_ID(), 'full'),
            'url'         => get_permalink(),
        );
    }
    wp_reset_postdata();

    return $items;
}
