<?php
/**
 * AUTOWEARLK - Custom WordPress theme functions.
 * Replace the existing theme functions.php with this complete file.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Load the main theme stylesheet and Inter font.
 */
function autowearlk_enqueue_theme_assets() {
    wp_enqueue_style(
        'autowearlk-google-fonts',
        'https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap',
        array(),
        null
    );

    $style_path    = get_stylesheet_directory() . '/style.css';
    $style_version = file_exists( $style_path ) ? filemtime( $style_path ) : wp_get_theme()->get( 'Version' );

    wp_enqueue_style(
        'autowearlk-style',
        get_stylesheet_uri(),
        array( 'autowearlk-google-fonts' ),
        $style_version
    );
}
add_action( 'wp_enqueue_scripts', 'autowearlk_enqueue_theme_assets' );

/**
 * Register theme features and the primary navigation menu.
 */
function autowearlk_theme_setup() {
    add_theme_support( 'title-tag' );
    add_theme_support( 'post-thumbnails' );
    add_theme_support( 'woocommerce' );

    register_nav_menus(
        array(
            'primary' => __( 'Primary Menu', 'autowearlk' ),
        )
    );
}
add_action( 'after_setup_theme', 'autowearlk_theme_setup' );

/**
 * Keep the WooCommerce header cart count updated after AJAX add-to-cart.
 */
function autowearlk_cart_count_fragment( $fragments ) {
    $count = 0;

    if ( function_exists( 'WC' ) && WC()->cart ) {
        $count = WC()->cart->get_cart_contents_count();
    }

    $fragments['.aw-cart-count'] = '<span class="aw-cart-count">' . esc_html( $count ) . '</span>';

    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'autowearlk_cart_count_fragment' );

/**
 * Load the existing product sorting CSS, if the file exists.
 */
function autowearlk_enqueue_default_sorting_css() {
    $css_path = get_stylesheet_directory() . '/default-sorting.css';

    if ( file_exists( $css_path ) ) {
        wp_enqueue_style(
            'autowearlk-default-sorting',
            get_stylesheet_directory_uri() . '/default-sorting.css',
            array( 'autowearlk-style' ),
            filemtime( $css_path )
        );
    }
}
add_action( 'wp_enqueue_scripts', 'autowearlk_enqueue_default_sorting_css', 99 );

/**
 * SMTP configuration.
 * Add AUTOWEARLK_SMTP_PASSWORD to wp-config.php; never put the password here.
 */
function autowearlk_smtp_mailer_config( $phpmailer ) {
    if ( ! defined( 'AUTOWEARLK_SMTP_PASSWORD' ) || '' === AUTOWEARLK_SMTP_PASSWORD ) {
        return;
    }

    $phpmailer->isSMTP();
    $phpmailer->Host       = 'mail.autowearlk.com';
    $phpmailer->SMTPAuth   = true;
    $phpmailer->Port       = 465;
    $phpmailer->Username   = 'orders@autowearlk.com';
    $phpmailer->Password   = AUTOWEARLK_SMTP_PASSWORD;
    $phpmailer->SMTPSecure = 'ssl';
    $phpmailer->From       = 'orders@autowearlk.com';
    $phpmailer->FromName   = 'AUTOWEARLK';
    $phpmailer->Sender     = 'orders@autowearlk.com';
}
add_action( 'phpmailer_init', 'autowearlk_smtp_mailer_config' );

/**
 * Add the theme's existing meta description and Open Graph tags.
 */
function autowearlk_seo_and_og_tags() {
    global $post;

    $site_name    = 'AUTOWEARLK';
    $default_desc = 'Genuine & high-quality automotive spare parts, accessories, and maintenance essentials in Sri Lanka. Island-wide delivery available.';
    $default_img  = 'https://www.autowearlk.com/wp-content/uploads/2026/11/Logo-favicon-01.png';

    if ( is_singular() && isset( $post ) && is_object( $post ) ) {
        $title = wp_strip_all_tags( get_the_title( $post->ID ) ) . ' - ' . $site_name;
        $url   = get_permalink( $post->ID );

        $raw_desc = has_excerpt( $post->ID ) ? get_the_excerpt( $post->ID ) : $post->post_content;
        $desc     = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $raw_desc ) ), 25, '...' );

        if ( '' === trim( $desc ) ) {
            $desc = $default_desc;
        }

        $image = has_post_thumbnail( $post->ID )
            ? get_the_post_thumbnail_url( $post->ID, 'large' )
            : $default_img;

        if ( empty( $image ) ) {
            $image = $default_img;
        }

        $type = ( function_exists( 'is_product' ) && is_product() ) ? 'product' : 'article';
    } else {
        $title = $site_name . ' | Automotive Spare Parts & Accessories Sri Lanka';
        $url   = home_url( '/' );
        $desc  = $default_desc;
        $image = $default_img;
        $type  = 'website';
    }

    echo '<meta name="description" content="' . esc_attr( $desc ) . '" />' . "\n";
    echo '<meta property="og:site_name" content="' . esc_attr( $site_name ) . '" />' . "\n";
    echo '<meta property="og:type" content="' . esc_attr( $type ) . '" />' . "\n";
    echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
    echo '<meta property="og:description" content="' . esc_attr( $desc ) . '" />' . "\n";
    echo '<meta property="og:url" content="' . esc_url( $url ) . '" />' . "\n";

    if ( ! empty( $image ) ) {
        echo '<meta property="og:image" content="' . esc_url( $image ) . '" />' . "\n";
    }
}
add_action( 'wp_head', 'autowearlk_seo_and_og_tags', 5 );

/**
 * Format a product's price for the WhatsApp message.
 * Variable products show their available price range until a variation is selected.
 */
function autowearlk_get_whatsapp_product_price( $product ) {
    if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
        return 'Price on request';
    }

    if ( $product->is_type( 'variable' ) ) {
        $min_price = $product->get_variation_price( 'min', true );
        $max_price = $product->get_variation_price( 'max', true );

        if ( '' === $min_price || '' === $max_price ) {
            return 'Price on request';
        }

        if ( (float) $min_price === (float) $max_price ) {
            $price_html = wc_price( $min_price );
        } else {
            $price_html = wc_price( $min_price ) . ' – ' . wc_price( $max_price );
        }
    } elseif ( '' !== $product->get_price() ) {
        $price_html = wc_price( wc_get_price_to_display( $product ) );
    } else {
        return 'Price on request';
    }

    $charset = get_bloginfo( 'charset' );

    return html_entity_decode(
        wp_strip_all_tags( $price_html ),
        ENT_QUOTES,
        $charset ? $charset : 'UTF-8'
    );
}

/**
 * Render the WhatsApp order button immediately after WooCommerce's Add to Cart button.
 */
function autowearlk_render_product_whatsapp_button() {
    if ( ! function_exists( 'is_product' ) || ! is_product() || ! function_exists( 'wc_get_product' ) ) {
        return;
    }

    global $product;

    if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
        $product = wc_get_product( get_queried_object_id() );
    }

    if ( ! $product ) {
        return;
    }

    $phone_number = '94772926996';
    $product_name = wp_strip_all_tags( $product->get_name() );
    $product_url  = get_permalink( $product->get_id() );
    $price_text   = autowearlk_get_whatsapp_product_price( $product );

    $message = "Hello AutoWearLK!\n"
        . "I would like to order or inquire about this product.\n\n"
        . 'Product Name: ' . $product_name . "\n"
        . 'Product Price: ' . $price_text . "\n"
        . 'Product URL: ' . $product_url;

    $whatsapp_url = 'https://wa.me/' . $phone_number . '?text=' . rawurlencode( $message );
    ?>
    <div class="autowearlk-whatsapp-wrap">
        <a
            class="autowearlk-whatsapp-button"
            href="<?php echo esc_url( $whatsapp_url ); ?>"
            target="_blank"
            rel="noopener noreferrer"
            aria-label="<?php echo esc_attr( 'Order ' . $product_name . ' via WhatsApp' ); ?>"
            data-product-name="<?php echo esc_attr( $product_name ); ?>"
            data-product-url="<?php echo esc_url( $product_url ); ?>"
            data-default-price="<?php echo esc_attr( $price_text ); ?>"
            data-currency-symbol="<?php echo esc_attr( html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ) ); ?>"
            data-currency-position="<?php echo esc_attr( get_option( 'woocommerce_currency_pos', 'left' ) ); ?>"
            data-thousand-separator="<?php echo esc_attr( wc_get_price_thousand_separator() ); ?>"
            data-decimal-separator="<?php echo esc_attr( wc_get_price_decimal_separator() ); ?>"
            data-price-decimals="<?php echo esc_attr( wc_get_price_decimals() ); ?>"
        >Order via WhatsApp</a>
    </div>
    <?php
}
add_action( 'woocommerce_after_add_to_cart_button', 'autowearlk_render_product_whatsapp_button', 20 );

/**
 * Load the WhatsApp button CSS only on single product pages.
 * For variable products, update the WhatsApp message with the selected variation price.
 */
function autowearlk_enqueue_product_whatsapp_assets() {
    if ( ! function_exists( 'is_product' ) || ! is_product() ) {
        return;
    }

    $css_path = get_stylesheet_directory() . '/css/product-whatsapp.css';

    if ( file_exists( $css_path ) ) {
        wp_enqueue_style(
            'autowearlk-product-whatsapp',
            get_stylesheet_directory_uri() . '/css/product-whatsapp.css',
            array( 'autowearlk-style' ),
            filemtime( $css_path )
        );
    }

    global $product;

    if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
        $product = wc_get_product( get_queried_object_id() );
    }

    if ( ! $product || ! $product->is_type( 'variable' ) ) {
        return;
    }

    wp_enqueue_script( 'jquery' );

    $variation_js = <<<'JS'
(function ($) {
    'use strict';

    function formatVariationPrice(value, settings) {
        var amount = Number(value);

        if (!Number.isFinite(amount)) {
            return settings.defaultPrice || 'Price on request';
        }

        var decimals = parseInt(settings.priceDecimals, 10);
        if (!Number.isFinite(decimals)) {
            decimals = 2;
        }
        decimals = Math.max(0, Math.min(decimals, 6));

        var thousandSeparator = settings.thousandSeparator || ',';
        var decimalSeparator = settings.decimalSeparator || '.';
        var parts = amount.toFixed(decimals).split('.');

        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);

        var formattedNumber = parts.join(decimalSeparator);
        var symbol = settings.currencySymbol || '';

        switch (settings.currencyPosition) {
            case 'right':
                return formattedNumber + symbol;
            case 'left_space':
                return symbol + ' ' + formattedNumber;
            case 'right_space':
                return formattedNumber + ' ' + symbol;
            case 'left':
            default:
                return symbol + formattedNumber;
        }
    }

    function getSettings($link) {
        return {
            productName: $link.attr('data-product-name') || 'Product',
            productUrl: $link.attr('data-product-url') || window.location.href,
            defaultPrice: $link.attr('data-default-price') || 'Price on request',
            currencySymbol: $link.attr('data-currency-symbol') || '',
            currencyPosition: $link.attr('data-currency-position') || 'left',
            thousandSeparator: $link.attr('data-thousand-separator') || ',',
            decimalSeparator: $link.attr('data-decimal-separator') || '.',
            priceDecimals: $link.attr('data-price-decimals') || 2
        };
    }

    function updateWhatsAppLink($link, price) {
        var settings = getSettings($link);
        var message = [
            'Hello AutoWearLK!',
            'I would like to order or inquire about this product.',
            '',
            'Product Name: ' + settings.productName,
            'Product Price: ' + (price || settings.defaultPrice),
            'Product URL: ' + settings.productUrl
        ].join('\n');

        $link.attr(
            'href',
            'https://wa.me/94772926996?text=' + encodeURIComponent(message)
        );
    }

    $(document).on('found_variation', 'form.variations_form', function (event, variation) {
        var $link = $('.autowearlk-whatsapp-button').first();

        if (!$link.length || !variation || typeof variation.display_price === 'undefined') {
            return;
        }

        var settings = getSettings($link);
        var formattedPrice = formatVariationPrice(variation.display_price, settings);

        updateWhatsAppLink($link, formattedPrice);
    });

    $(document).on('reset_data hide_variation', 'form.variations_form', function () {
        var $link = $('.autowearlk-whatsapp-button').first();

        if ($link.length) {
            updateWhatsAppLink($link, getSettings($link).defaultPrice);
        }
    });

})(jQuery);
JS;

    wp_add_inline_script( 'jquery', $variation_js, 'after' );
}
add_action( 'wp_enqueue_scripts', 'autowearlk_enqueue_product_whatsapp_assets', 30 );

/**
 * Load the existing floating WhatsApp button stylesheet site-wide, if present.
 */
function autowearlk_enqueue_floating_whatsapp_css() {
    $css_path = get_stylesheet_directory() . '/css/whatsapp-button.css';

    if ( file_exists( $css_path ) ) {
        wp_enqueue_style(
            'autowearlk-floating-whatsapp',
            get_stylesheet_directory_uri() . '/css/whatsapp-button.css',
            array( 'autowearlk-style' ),
            filemtime( $css_path )
        );
    }
}
add_action( 'wp_enqueue_scripts', 'autowearlk_enqueue_floating_whatsapp_css', 99 );

/**
 * Display the floating WhatsApp contact button on all pages (with guaranteed inline & head styles).
 */
function autowearlk_whatsapp_floating_button() {
    $phone_number = '94772926996';
    $message      = 'Hello! AutoWearLK එකෙන් නේද? මට spare part එකක් ගැන විස්තර දැනගන්න පුලුවන්ද?';
    $whatsapp_url = 'https://wa.me/' . $phone_number . '?text=' . rawurlencode( $message );
    ?>
    <style>
        .aw-whatsapp-float {
            position: fixed !important;
            bottom: 24px !important;
            right: 24px !important;
            width: 56px !important;
            height: 56px !important;
            background-color: #25D366 !important;
            color: #FFFFFF !important;
            border-radius: 50% !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            box-shadow: 0 6px 20px rgba(37, 211, 102, 0.35) !important;
            z-index: 9999 !important;
            transition: transform 0.25s ease, box-shadow 0.25s ease, background-color 0.25s ease !important;
            text-decoration: none !important;
        }
        .aw-whatsapp-float svg {
            width: 28px !important;
            height: 28px !important;
            fill: #FFFFFF !important;
            display: block !important;
        }
        .aw-whatsapp-float:hover {
            transform: translateY(-4px) scale(1.05) !important;
            background-color: #20BA5A !important;
            box-shadow: 0 10px 25px rgba(37, 211, 102, 0.5) !important;
            color: #FFFFFF !important;
        }
        @media screen and (max-width: 600px) {
            .aw-whatsapp-float {
                bottom: 18px !important;
                right: 18px !important;
                width: 50px !important;
                height: 50px !important;
            }
            .aw-whatsapp-float svg {
                width: 25px !important;
                height: 25px !important;
            }
        }
    </style>
    <a href="<?php echo esc_url( $whatsapp_url ); ?>" class="aw-whatsapp-float" target="_blank" rel="noopener noreferrer" aria-label="Chat on WhatsApp" style="position:fixed;bottom:24px;right:24px;width:56px;height:56px;background:#25D366;color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;z-index:9999;">
        <svg width="28" height="28" viewBox="0 0 32 32" fill="#FFFFFF" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">
            <path d="M16.004 3.2c-7.06 0-12.8 5.74-12.8 12.8 0 2.256.59 4.46 1.71 6.404L3.09 29.06l6.826-1.79a12.75 12.75 0 0 0 6.088 1.55h.005c7.058 0 12.796-5.74 12.796-12.8 0-3.42-1.332-6.636-3.75-9.054A12.714 12.714 0 0 0 16.004 3.2zm0 23.458h-.004a10.62 10.62 0 0 1-5.414-1.482l-.388-.23-4.05 1.062 1.08-3.948-.252-.402a10.614 10.614 0 0 1-1.628-5.658c0-5.864 4.772-10.636 10.64-10.636 2.84 0 5.51 1.106 7.518 3.116a10.566 10.566 0 0 1 3.114 7.524c0 5.864-4.772 10.634-10.632 10.634zm5.834-7.968c-.32-.16-1.892-.934-2.186-1.04-.292-.106-.506-.16-.72.16-.212.32-.826 1.04-1.012 1.254-.186.212-.372.24-.692.08-.32-.16-1.35-.498-2.572-1.588-.95-.848-1.592-1.896-1.778-2.216-.186-.32-.02-.492.14-.652.144-.144.32-.372.48-.56.16-.186.212-.32.32-.532.106-.214.052-.4-.028-.56-.08-.16-.72-1.734-.986-2.374-.26-.624-.524-.54-.72-.55l-.614-.01c-.212 0-.56.08-.852.4-.294.32-1.12 1.094-1.12 2.668 0 1.574 1.146 3.094 1.306 3.308.16.212 2.256 3.444 5.466 4.83.764.33 1.36.526 1.824.674.766.244 1.464.21 2.016.126.614-.092 1.892-.774 2.158-1.52.266-.748.266-1.388.186-1.52-.08-.134-.292-.214-.612-.374z" />
        </svg>
    </a>
    <?php
}
add_action( 'wp_footer', 'autowearlk_whatsapp_floating_button' );

/**
 * Load the separate My Account stylesheet on account pages, excluding checkout.
 */
function autowearlk_enqueue_my_account_styles() {
    if ( function_exists( 'is_account_page' ) && is_account_page() && ! is_checkout() ) {
        $css_path = get_stylesheet_directory() . '/my-account.css';

        if ( file_exists( $css_path ) ) {
            wp_enqueue_style(
                'autowearlk-my-account',
                get_stylesheet_directory_uri() . '/my-account.css',
                array( 'autowearlk-style' ),
                filemtime( $css_path )
            );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'autowearlk_enqueue_my_account_styles', 99 );