<?php
namespace Lean_CSNS;

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

/**
 * WC_Integration
 */
class WC_Integration {
    /**
     * Singleton instance
     */
    private static $instance = null;

    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Private constructor to prevent direct instantiation
     */
    private function __construct() {
        $this->init();
    }
    
    /**
     * Initialize base functionality
     */
    private function init() {
        $this->init_hooks();
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        // Frontend hooks
        // Register the correct WC action hook based on the admin's button position setting.
        $position = lean_csns_get_option( 'cart_share.button_position', 'default' );
        $hook_map = [
            'default'       => 'woocommerce_cart_coupon',
            'after_table'   => 'woocommerce_after_cart_table',
            'before_totals' => 'woocommerce_before_cart_totals',
        ];
        add_action( $hook_map[ $position ] ?? 'woocommerce_cart_coupon', [ $this, 'add_cart_buttons' ] );
        add_action('wp_footer', [$this, 'render_popup_template']);
        
        // My Account integration — only when Save Cart is enabled
        if (lean_csns_get_option('cart_save.enable', '1')) {
            add_action('init', [$this, 'add_my_account_endpoint']);
            add_filter('woocommerce_account_menu_items', [$this, 'add_my_account_menu_item']);
            add_action('woocommerce_account_saved-carts_endpoint', [$this, 'my_account_saved_carts_content']);
            add_action('init', [$this, 'handle_saved_cart_deletion']);
        }
    }
    
    /**
     * Add cart share/save buttons to cart page (classic themes)
     */
    public function add_cart_buttons() {
        echo $this->get_buttons_html();
    }
    
    /**
     * Get buttons HTML (single source of truth)
     * Used by both classic themes and Cart Blocks
     * 
     * @return string Button HTML or empty string if no buttons should show
     */
    public function get_buttons_html() {
        $share_enabled = lean_csns_get_option('cart_share.enable', '1');
        $save_enabled = lean_csns_get_option('cart_save.enable', '1');
        
        if (!$share_enabled && !$save_enabled) {
            return '';
        }
        
        $position = lean_csns_get_option( 'cart_share.button_position', 'default' );
        $html = '<div class="lean-csns-buttons-wrapper lean-csns-position--' . esc_attr( $position ) . '">';
        
        if ($share_enabled) {
            // Use custom label if admin set one, otherwise fall back to default.
            $share_label = lean_csns_get_option( 'cart_share.share_button_label', '' );
            $share_label = ( '' !== trim( $share_label ) ) ? $share_label : __( 'Share Cart', 'lean-cart-share-and-save' );
            $html .= '<button type="button" class="wp-element-button button lean-csns-share-btn">' . esc_html( $share_label ) . '</button>';
        }

        if ($save_enabled && is_user_logged_in()) {
            // Use custom label if admin set one, otherwise fall back to default.
            $save_label = lean_csns_get_option( 'cart_save.save_button_label', '' );
            $save_label = ( '' !== trim( $save_label ) ) ? $save_label : __( 'Save Cart', 'lean-cart-share-and-save' );
            $html .= '<button type="button" class="wp-element-button button lean-csns-save-btn">' . esc_html( $save_label ) . '</button>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Render popup template in footer (for both classic and block carts)
     */
    public function render_popup_template() {
        // Only render on pages where WooCommerce is active
        if (!function_exists('WC') || !WC()->cart) {
            return;
        }
        
        include LEAN_CSNS_PL_DIR . 'templates/popup.php';
    }
    
    /**
     * Add My Account endpoint for saved carts
     */
    public function add_my_account_endpoint() {
        add_rewrite_endpoint('saved-carts', EP_ROOT | EP_PAGES);
    }
    
    /**
     * Add menu item to My Account navigation
     * 
     * @param array $items Existing menu items
     * @return array Modified menu items
     */
    public function add_my_account_menu_item($items) {
        $new_items = [];
        foreach ($items as $key => $item) {
            $new_items[$key] = $item;
            if ($key === 'orders') {
                $new_items['saved-carts'] = __('Saved Carts', 'lean-cart-share-and-save');
            }
        }
        return $new_items;
    }
    
    /**
     * Display saved carts content in My Account
     */
    public function my_account_saved_carts_content() {
        include LEAN_CSNS_PL_DIR . 'templates/my-account/saved-carts.php';
    }
    
    /**
     * Handle saved cart deletion from My Account page
     */
    public function handle_saved_cart_deletion() {
        if (!isset($_GET['action']) || $_GET['action'] !== 'delete_saved_cart') {
            return;
        }
        
        if (!isset($_GET['cart_id']) || !isset($_GET['_wpnonce'])) {
            return;
        }
        
        $cart_id = absint($_GET['cart_id']);
        $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce']));
        
        if (!wp_verify_nonce($nonce, 'delete_cart_' . $cart_id)) {
            wc_add_notice(__('Security verification failed.', 'lean-cart-share-and-save'), 'error');
            return;
        }
        
        if (!is_user_logged_in()) {
            wc_add_notice(__('Please log in to delete cart.', 'lean-cart-share-and-save'), 'error');
            return;
        }
        
        $user_id = get_current_user_id();
        
        // Verify ownership
        if (!Database::get_instance()->verify_cart_ownership($cart_id, $user_id)) {
            wc_add_notice(__('You are not authorized to delete this cart.', 'lean-cart-share-and-save'), 'error');
            return;
        }
        
        $result = Database::get_instance()->delete_cart($cart_id);
        
        if ($result) {
            wc_add_notice(__('Cart deleted successfully!', 'lean-cart-share-and-save'), 'success');
        } else {
            wc_add_notice(__('Failed to delete cart.', 'lean-cart-share-and-save'), 'error');
        }
        
        wp_redirect(wc_get_account_endpoint_url('saved-carts'));
        exit;
    }
}

WC_Integration::get_instance();