<?php
/**
 * Cart Page Base Class
 * Singleton render engine for all cart page widget styles.
 *
 * @package WooLentor Pro
 */

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

class WooLentor_Cart_Page_Base {

    private static $_instance = null;

    // Whitelisted widget types — prevents directory traversal
    private $allowed_widget_types = [
        'cart-table',
        'cart-total',
        'cart-cross-sells',
        'cart-empty',
    ];

    // Whitelisted styles
    private $allowed_styles = [
        'aura', 'noir', 'canvas', 'prism', 'clay',
        'forge', 'pulse', 'bento', 'ether', 'lux',
    ];

    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Main render entry point — called by each widget's render() method.
     *
     * @param string $widget_type  One of the allowed widget types.
     * @param string $style        One of the allowed style keys.
     * @param array  $settings     Elementor settings prepared by the widget.
     */
    public function render( $widget_type, $style, $settings ) {
        $widget_type = sanitize_key( $widget_type );
        $style       = sanitize_key( $style );

        if ( ! in_array( $widget_type, $this->allowed_widget_types, true ) ) {
            return;
        }

        if ( ! in_array( $style, $this->allowed_styles, true ) ) {
            $style = 'aura';
        }

        $template_path = $this->get_template_path( $widget_type, $style );

        if ( empty( $template_path ) || ! file_exists( $template_path ) ) {
            return;
        }

        // Make WooCommerce helpers available to the template
        $cart_base  = $this;
        $cart_items = $this->get_cart_items();

        include $template_path;
    }

    /**
     * Build and validate the template path.
     * Returns empty string if the resolved path escapes the base directory.
     */
    private function get_template_path( $widget_type, $style ) {
        $base_dir  = wp_normalize_path( WOOLENTOR_ADDONS_PL_PATH_PRO . 'wl-woo-templates/cart-page/' );
        $candidate = wp_normalize_path( $base_dir . $widget_type . '/' . $style . '.php' );

        // Verify the file exists before calling realpath
        if ( ! file_exists( $candidate ) ) {
            return '';
        }

        $real_base   = wp_normalize_path( realpath( $base_dir ) );
        $real_target = wp_normalize_path( realpath( $candidate ) );

        if ( ! $real_target || strpos( $real_target, $real_base ) !== 0 ) {
            return '';
        }

        return apply_filters( 'woolentor_cart_page_template_path', $real_target, $widget_type, $style );
    }

    // ─── WooCommerce helper methods (used inside templates) ──────────────────

    public function is_cart_empty() {
        return ! WC()->cart || WC()->cart->is_empty();
    }

    public function get_cart_items() {
        if ( ! WC()->cart ) {
            return [];
        }
        return WC()->cart->get_cart();
    }

    public function get_cross_sell_products() {
        if ( ! WC()->cart ) {
            return [];
        }
        return array_filter(
            array_map( 'wc_get_product', WC()->cart->get_cross_sells() ),
            function( $product ) {
                return $product && $product->is_visible();
            }
        );
    }

    public function get_cart_shipping_packages() {
        if ( ! WC()->shipping() ) {
            return [];
        }
        return WC()->shipping()->get_packages();
    }

    /**
     * Return saving amount for a cart item (regular - sale price × qty).
     * Returns 0.0 if the product is not on sale.
     */
    public function get_item_saving( $product, $quantity ) {
        if ( ! $product->is_on_sale() ) {
            return 0.0;
        }
        $regular = (float) $product->get_regular_price();
        $sale    = (float) $product->get_sale_price();
        return ( $regular - $sale ) * absint( $quantity );
    }

}

WooLentor_Cart_Page_Base::instance();
