<?php
namespace WoolentorPro\Modules\FreeShippingBar\Frontend;
use WooLentorPro\Traits\Singleton;
use WoolentorPro\Modules\FreeShippingBar\Free_Shipping_Bar_Pro;

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

class Multi_Bar {
    use Singleton;

    private function __construct() {}

    /**
     * Evaluate additional bars and return the first one matching the current
     * context (targeting, schedule, device). Returns null when none match.
     */
    public function get_best_bar() {
        $additional_bars = Free_Shipping_Bar_Pro::setting( 'additional_bars', [] );
        if ( empty( $additional_bars ) || ! is_array( $additional_bars ) ) {
            return null;
        }

        usort( $additional_bars, static function ( $a, $b ) {
            return (int) ( $a['bar_priority'] ?? 10 ) - (int) ( $b['bar_priority'] ?? 10 );
        } );

        foreach ( $additional_bars as $index => $bar ) {
            if ( ( $bar['bar_enabled'] ?? 'on' ) !== 'on' ) {
                continue;
            }

            // Schedule check
            if ( ( $bar['enable_schedule'] ?? 'off' ) === 'on' ) {
                $now   = time();
                $start = ! empty( $bar['schedule_start'] ) ? strtotime( $bar['schedule_start'] ) : 0;
                $end   = ! empty( $bar['schedule_end'] )   ? strtotime( $bar['schedule_end'] )   : 0;
                if ( $start && $now < $start ) continue;
                if ( $end   && $now > $end )   continue;
            }

            // User-role check
            $role = $bar['target_user_role'] ?? 'all';
            if ( $role === 'guest'     && is_user_logged_in() ) continue;
            if ( $role === 'logged_in' && ! is_user_logged_in() ) continue;

            // Page check — display_pages is an array of page IDs (ajaxselect, multiple)
            $display_pages = $bar['display_pages'] ?? [];
            if ( ! empty( $display_pages ) && is_array( $display_pages ) ) {
                $page_ids = array_filter( array_map( 'absint', $display_pages ) );
                if ( ! empty( $page_ids ) ) {
                    $current = \Woolentor\Modules\FreeShippingBar\Frontend\Bar_Renderer::get_current_page_id();
                    if ( ! in_array( $current, $page_ids, true ) ) {
                        continue;
                    }
                }
            }

            // Threshold for this bar
            $bar_threshold = (float) ( $bar['manual_threshold'] ?? 0 );
            if ( $bar_threshold <= 0 ) {
                $bar_threshold = \Woolentor\Modules\FreeShippingBar\Frontend\Bar_Renderer::get_threshold();
            }
            if ( $bar_threshold <= 0 ) {
                continue;
            }

            return [
                '_index'         => $index,
                'threshold'      => $bar_threshold,
                'msg_initial'    => $bar['msg_initial']    ?? esc_html__( 'Spend {amount} more to get FREE shipping!', 'woolentor-pro' ),
                'msg_success'    => $bar['msg_success']    ?? esc_html__( "🎉 You've unlocked FREE shipping!", 'woolentor-pro' ),
                'bar_position'   => $bar['bar_position']   ?? 'top',
                'show_on_device' => $bar['show_on_device'] ?? 'all',
                'bar_skin'       => $bar['bar_skin']       ?? 'default',
                'bar_bg_color'   => $bar['bar_bg_color']   ?? '',
                'bar_text_color' => $bar['bar_text_color'] ?? '',
                'bar_fill_color' => $bar['bar_fill_color'] ?? '',
                'enable_countdown'   => $bar['enable_countdown']   ?? 'off',
                'countdown_end_date' => $bar['countdown_end_date'] ?? '',
                'countdown_message'  => $bar['countdown_message']  ?? '',
            ];
        }

        return null;
    }
}
