<?php
/**
 * Product handler class
 * Manages WooCommerce product integration and subscription buttons
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class STRP_SUB_Product_Handler {
    
    /**
     * Single instance
     */
    private static $instance = null;
    
    /**
     * Get instance
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Add custom product meta boxes
        add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
        add_action( 'save_post', array( $this, 'save_product_meta' ) );

        // Add subscription button to product pages
        add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'add_subscription_button' ) );

        // Add shortcode for subscription button
        add_shortcode( 'strp_sub_subscribe_button', array( $this, 'subscription_button_shortcode' ) );
    }

    private function __clone() {}

    public function __wakeup() {
        throw new \RuntimeException( 'Cannot unserialize singleton.' );
    }

    /**
     * Add product meta boxes
     */
    public function add_meta_boxes() {
        add_meta_box(
            'strp_sub_product_settings',
            __( 'Stripe Subscription Settings', 'subscription-manager-for-stripe' ),
            array( $this, 'render_product_meta_box' ),
            'product',
            'normal',
            'high'
        );
    }
    
    /**
     * Render product meta box
     */
    public function render_product_meta_box( $post ) {
        wp_nonce_field( 'strp_sub_product_meta', 'strp_sub_product_meta_nonce' );

        $enabled = get_post_meta( $post->ID, '_strp_sub_enabled', true );
        $subscription_type = get_post_meta( $post->ID, '_strp_sub_subscription_type', true );

        // Test mode IDs
        $test_stripe_price_id = get_post_meta( $post->ID, '_strp_sub_test_stripe_price_id', true );
        $test_stripe_product_id = get_post_meta( $post->ID, '_strp_sub_test_stripe_product_id', true );

        // Live mode IDs
        $live_stripe_price_id = get_post_meta( $post->ID, '_strp_sub_live_stripe_price_id', true );
        $live_stripe_product_id = get_post_meta( $post->ID, '_strp_sub_live_stripe_product_id', true );

        // Tier weight
        $tier_weight = get_post_meta( $post->ID, '_strp_sub_tier_weight', true );
        $tier_weight = empty( $tier_weight ) ? 10 : $tier_weight;
        ?>
        <div class="strp-sub-product-settings">
            <p>
                <label>
                    <input type="checkbox" name="_strp_sub_enabled" value="yes" <?php checked( $enabled, 'yes' ); ?> />
                    <?php esc_html_e( 'Enable Stripe Billing for this product', 'subscription-manager-for-stripe' ); ?>
                </label>
            </p>

            <p>
                <label for="_strp_sub_subscription_type"><?php esc_html_e( 'Subscription Type', 'subscription-manager-for-stripe' ); ?></label>
                <select name="_strp_sub_subscription_type" id="_strp_sub_subscription_type">
                    <option value="monthly" <?php selected( $subscription_type, 'monthly' ); ?>><?php esc_html_e( 'Monthly Recurring', 'subscription-manager-for-stripe' ); ?></option>
                    <option value="annual" <?php selected( $subscription_type, 'annual' ); ?>><?php esc_html_e( 'Annual Recurring', 'subscription-manager-for-stripe' ); ?></option>
                    <?php if ( function_exists( 'strp_sub_fs' ) && strp_sub_fs() && strp_sub_fs()->is__premium_only() ) : ?>
                    <option value="lifetime" <?php selected( $subscription_type, 'lifetime' ); ?>><?php esc_html_e( 'Lifetime (One-time)', 'subscription-manager-for-stripe' ); ?></option>
                    <?php endif; ?>
                </select>
            </p>

            <p>
                <label for="_strp_sub_tier_weight"><?php esc_html_e( 'Tier Weight (Numeric)', 'subscription-manager-for-stripe' ); ?></label>
                <input type="number" name="_strp_sub_tier_weight" id="_strp_sub_tier_weight" value="<?php echo esc_attr( $tier_weight ); ?>" class="regular-text" style="width: 80px;" />
                <span class="description"><?php esc_html_e( 'Relative upgrade weight (e.g. 10 for Monthly, 20 for Annual). Used to calculate if a subscription change is an upgrade.', 'subscription-manager-for-stripe' ); ?></span>
            </p>

            <hr style="margin: 20px 0;" />

            <h4><?php esc_html_e( 'Test Mode Stripe IDs', 'subscription-manager-for-stripe' ); ?></h4>

            <p>
                <label for="_strp_sub_test_stripe_product_id"><?php esc_html_e( 'Test Stripe Product ID', 'subscription-manager-for-stripe' ); ?></label>
                <input type="text" name="_strp_sub_test_stripe_product_id" id="_strp_sub_test_stripe_product_id" value="<?php echo esc_attr( $test_stripe_product_id ); ?>" class="regular-text" />
                <span class="description"><?php esc_html_e( 'Enter the Stripe Product ID from test mode (e.g., prod_xxxxx)', 'subscription-manager-for-stripe' ); ?></span>
            </p>

            <p>
                <label for="_strp_sub_test_stripe_price_id"><?php esc_html_e( 'Test Stripe Price ID', 'subscription-manager-for-stripe' ); ?></label>
                <input type="text" name="_strp_sub_test_stripe_price_id" id="_strp_sub_test_stripe_price_id" value="<?php echo esc_attr( $test_stripe_price_id ); ?>" class="regular-text" />
                <span class="description"><?php esc_html_e( 'Enter the Stripe Price ID from test mode (e.g., price_xxxxx)', 'subscription-manager-for-stripe' ); ?></span>
            </p>

            <hr style="margin: 20px 0;" />

            <h4><?php esc_html_e( 'Live Mode Stripe IDs', 'subscription-manager-for-stripe' ); ?></h4>

            <p>
                <label for="_strp_sub_live_stripe_product_id"><?php esc_html_e( 'Live Stripe Product ID', 'subscription-manager-for-stripe' ); ?></label>
                <input type="text" name="_strp_sub_live_stripe_product_id" id="_strp_sub_live_stripe_product_id" value="<?php echo esc_attr( $live_stripe_product_id ); ?>" class="regular-text" />
                <span class="description"><?php esc_html_e( 'Enter the Stripe Product ID from live mode (e.g., prod_xxxxx)', 'subscription-manager-for-stripe' ); ?></span>
            </p>

            <p>
                <label for="_strp_sub_live_stripe_price_id"><?php esc_html_e( 'Live Stripe Price ID', 'subscription-manager-for-stripe' ); ?></label>
                <input type="text" name="_strp_sub_live_stripe_price_id" id="_strp_sub_live_stripe_price_id" value="<?php echo esc_attr( $live_stripe_price_id ); ?>" class="regular-text" />
                <span class="description"><?php esc_html_e( 'Enter the Stripe Price ID from live mode (e.g., price_xxxxx)', 'subscription-manager-for-stripe' ); ?></span>
            </p>

            <p class="description">
                <?php esc_html_e( 'Create products and prices in both test and live Stripe Dashboard, then enter the IDs here. The system will automatically use the correct IDs based on test mode setting.', 'subscription-manager-for-stripe' ); ?>
            </p>
        </div>
        <?php
    }
    
    /**
     * Save product meta
     */
    public function save_product_meta( $post_id ) {
        // Check nonce
        if ( ! isset( $_POST['strp_sub_product_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['strp_sub_product_meta_nonce'] ) ), 'strp_sub_product_meta' ) ) {
            return;
        }
        
        // Check autosave
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        
        // Check permissions
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
        
        // Save enabled status
        if ( isset( $_POST['_strp_sub_enabled'] ) ) {
            update_post_meta( $post_id, '_strp_sub_enabled', 'yes' );
        } else {
            update_post_meta( $post_id, '_strp_sub_enabled', 'no' );
        }
        
        // Save subscription type
        if ( isset( $_POST['_strp_sub_subscription_type'] ) ) {
            update_post_meta( $post_id, '_strp_sub_subscription_type', sanitize_text_field( wp_unslash( $_POST['_strp_sub_subscription_type'] ) ) );
        }

        // Save tier weight
        if ( isset( $_POST['_strp_sub_tier_weight'] ) ) {
            update_post_meta( $post_id, '_strp_sub_tier_weight', intval( wp_unslash( $_POST['_strp_sub_tier_weight'] ) ) );
        }

        // Save Test Stripe IDs
        if ( isset( $_POST['_strp_sub_test_stripe_price_id'] ) ) {
            $price_id = sanitize_text_field( wp_unslash( $_POST['_strp_sub_test_stripe_price_id'] ) );
            update_post_meta( $post_id, '_strp_sub_test_stripe_price_id', $price_id );
            if ( ! empty( $price_id ) && 0 !== strpos( $price_id, 'price_' ) ) {
                STRP_SUB_Logger::warning( 'Product ' . $post_id . ': Test Stripe price ID may be incorrect (expected price_ prefix): ' . $price_id );
            }
        }

        if ( isset( $_POST['_strp_sub_test_stripe_product_id'] ) ) {
            $product_id_val = sanitize_text_field( wp_unslash( $_POST['_strp_sub_test_stripe_product_id'] ) );
            update_post_meta( $post_id, '_strp_sub_test_stripe_product_id', $product_id_val );
            if ( ! empty( $product_id_val ) && 0 !== strpos( $product_id_val, 'prod_' ) ) {
                STRP_SUB_Logger::warning( 'Product ' . $post_id . ': Test Stripe product ID may be incorrect (expected prod_ prefix): ' . $product_id_val );
            }
        }

        // Save Live Stripe IDs
        if ( isset( $_POST['_strp_sub_live_stripe_price_id'] ) ) {
            $price_id = sanitize_text_field( wp_unslash( $_POST['_strp_sub_live_stripe_price_id'] ) );
            update_post_meta( $post_id, '_strp_sub_live_stripe_price_id', $price_id );
            if ( ! empty( $price_id ) && 0 !== strpos( $price_id, 'price_' ) ) {
                STRP_SUB_Logger::warning( 'Product ' . $post_id . ': Live Stripe price ID may be incorrect (expected price_ prefix): ' . $price_id );
            }
        }

        if ( isset( $_POST['_strp_sub_live_stripe_product_id'] ) ) {
            $product_id_val = sanitize_text_field( wp_unslash( $_POST['_strp_sub_live_stripe_product_id'] ) );
            update_post_meta( $post_id, '_strp_sub_live_stripe_product_id', $product_id_val );
            if ( ! empty( $product_id_val ) && 0 !== strpos( $product_id_val, 'prod_' ) ) {
                STRP_SUB_Logger::warning( 'Product ' . $post_id . ': Live Stripe product ID may be incorrect (expected prod_ prefix): ' . $product_id_val );
            }
        }
    }
    
    /**
     * Add subscription button to product pages
     */
    public function add_subscription_button() {
        global $product;
        
        if ( ! $product ) {
            return;
        }
        
        $enabled = get_post_meta( $product->get_id(), '_strp_sub_enabled', true );
        
        if ( $enabled !== 'yes' ) {
            return;
        }
        
        $this->render_subscription_button( $product->get_id() );
    }
    
    /**
     * Render subscription button
     */
    private function render_subscription_button( $product_id ) {
        $subscription_type = get_post_meta( $product_id, '_strp_sub_subscription_type', true );
        $stripe_price_id = self::get_stripe_price_id( $product_id );

        if ( empty( $stripe_price_id ) ) {
            return;
        }
        
        // Get button text based on subscription type
        $button_text = '';
        switch ( $subscription_type ) {
            case 'monthly':
                $button_text = __( 'Subscribe Monthly', 'subscription-manager-for-stripe' );
                break;
            case 'annual':
                $button_text = __( 'Subscribe Annually', 'subscription-manager-for-stripe' );
                break;
            case 'lifetime':
                $button_text = __( 'Buy Lifetime', 'subscription-manager-for-stripe' );
                break;
            default:
                $button_text = __( 'Subscribe Now', 'subscription-manager-for-stripe' );
                break;
        }
        
        ?>
        <div class="strp-sub-subscription-button-wrapper">
            <button type="button" class="strp-sub-subscribe-button button alt" data-product-id="<?php echo esc_attr( $product_id ); ?>" data-price-id="<?php echo esc_attr( $stripe_price_id ); ?>" data-subscription-type="<?php echo esc_attr( $subscription_type ); ?>">
                <?php echo esc_html( $button_text ); ?>
            </button>
        </div>
        <?php
    }
    
    /**
     * Subscription button shortcode
     */
    public function subscription_button_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'product_id' => 0,
        ), $atts );
        
        $product_id = intval( $atts['product_id'] );
        
        if ( $product_id <= 0 ) {
            return '';
        }
        
        ob_start();
        $this->render_subscription_button( $product_id );
        return ob_get_clean();
    }
    
    /**
     * Check if product is a subscription product
     */
    public static function is_subscription_product( $product_id ) {
        $enabled = get_post_meta( $product_id, '_strp_sub_enabled', true );
        return $enabled === 'yes';
    }
    
    /**
     * Check if product is a lifetime product
     */
    public static function is_lifetime_product( $product_id ) {
        $subscription_type = get_post_meta( $product_id, '_strp_sub_subscription_type', true );
        return $subscription_type === 'lifetime';
    }
    
    /**
     * Get Stripe Price ID for product (test or live based on mode)
     */
    public static function get_stripe_price_id( $product_id ) {
        if ( STRP_SUB_Settings::is_test_mode() ) {
            return get_post_meta( $product_id, '_strp_sub_test_stripe_price_id', true );
        }
        return get_post_meta( $product_id, '_strp_sub_live_stripe_price_id', true );
    }

    /**
     * Get Stripe Product ID for product (test or live based on mode)
     */
    public static function get_stripe_product_id( $product_id ) {
        if ( STRP_SUB_Settings::is_test_mode() ) {
            return get_post_meta( $product_id, '_strp_sub_test_stripe_product_id', true );
        }
        return get_post_meta( $product_id, '_strp_sub_live_stripe_product_id', true );
    }
    
    /**
     * Get subscription type for product
     */
    public static function get_subscription_type( $product_id ) {
        return get_post_meta( $product_id, '_strp_sub_subscription_type', true );
    }

    /**
     * Get tier weight for product
     */
    public static function get_tier_weight( $product_id ) {
        $weight = get_post_meta( $product_id, '_strp_sub_tier_weight', true );
        return empty( $weight ) ? 10 : intval( $weight );
    }
}
