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

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

class Cart_Drawer {
    use Singleton;

    private function __construct() {
        add_action( 'after_setup_theme', [ $this, 'setup_hooks' ] );
    }

    public function setup_hooks() {
        if ( Free_Shipping_Bar_Pro::setting( 'enable_cart_drawer', 'off' ) !== 'on' ) {
            return;
        }

        $theme = Free_Shipping_Bar_Pro::setting( 'cart_drawer_theme', 'auto' );
        if ( $theme === 'auto' ) {
            $theme = $this->detect_theme();
        }

        switch ( $theme ) {
            case 'flatsome':
                add_action( 'flatsome_before_cart_items',        [ $this, 'render_bar' ], 5 );
                break;
            case 'astra':
                add_action( 'astra_woo_mini_cart_before_wrap',   [ $this, 'render_bar' ], 5 );
                break;
            case 'oceanwp':
                add_action( 'ocean_before_mini_cart_items',      [ $this, 'render_bar' ], 5 );
                break;
            case 'storefront':
                add_action( 'storefront_before_cart_link',       [ $this, 'render_bar' ], 5 );
                break;
            default:
                add_action( 'woocommerce_before_mini_cart_contents', [ $this, 'render_bar' ], 5 );
                break;
        }
    }

    public function render_bar() {
        if ( Free_Shipping_Bar_Pro::setting( 'enable_cart_drawer', 'off' ) !== 'on' ) {
            return;
        }
        $threshold = \Woolentor\Modules\FreeShippingBar\Frontend\Bar_Renderer::get_threshold();
        if ( $threshold <= 0 ) {
            return;
        }
        ?>
        <div class="wl-fsb-drawer-wrap" data-threshold="<?php echo esc_attr( $threshold ); ?>">
            <p class="wl-fsb-drawer-message"></p>
            <div class="wl-fsb-progress-track wl-fsb-drawer-track">
                <div class="wl-fsb-progress-fill"></div>
            </div>
        </div>
        <?php
    }

    private function detect_theme() {
        $map = [
            'flatsome'   => 'flatsome',
            'astra'      => 'astra',
            'oceanwp'    => 'oceanwp',
            'storefront' => 'storefront',
        ];
        return $map[ get_option( 'stylesheet' ) ] ?? 'generic';
    }
}
