<?php
defined( 'ABSPATH' ) || exit;

class Woocom_Pay_Product {

	public static function init(): void {
		// Product meta tab.
		add_filter( 'woocommerce_product_data_tabs', [ __CLASS__, 'add_product_tab' ] );
		add_action( 'woocommerce_product_data_panels', [ __CLASS__, 'render_product_panel' ] );
		add_action( 'woocommerce_process_product_meta', [ __CLASS__, 'save_product_meta' ] );

		// Product page.
		add_action( 'woocommerce_before_add_to_cart_button', [ __CLASS__, 'render_product_payment_options' ] );
		add_filter( 'woocommerce_add_to_cart_validation', [ __CLASS__, 'validate_payment_option_selected' ], 10, 3 );
		add_filter( 'woocommerce_add_cart_item_data', [ __CLASS__, 'add_cart_item_data' ], 10, 3 );

		// Cart display.
		add_filter( 'woocommerce_get_item_data', [ __CLASS__, 'display_cart_item_data' ], 10, 2 );

		// Cart totals override.
		add_action( 'woocommerce_before_calculate_totals', [ __CLASS__, 'adjust_cart_item_price' ], 20 );

		// Checkout display.
		add_action( 'woocommerce_review_order_before_submit', [ __CLASS__, 'render_checkout_summary' ] );

		// Save payment meta to order.
		add_action( 'woocommerce_checkout_create_order_line_item', [ __CLASS__, 'save_order_item_meta' ], 10, 4 );
		add_action( 'woocommerce_checkout_order_created', [ __CLASS__, 'save_order_payment_meta' ] );

		// Tutor LMS integration — show payment options on course pages.
		if ( function_exists( 'tutor' ) ) {
			add_action( 'tutor_course/single/before_enroll', [ __CLASS__, 'render_tutor_payment_options' ] );
			add_action( 'wp_footer', [ __CLASS__, 'inject_tutor_enroll_script' ] );
		}
	}

	// -------------------------------------------------------------------------
	// Product admin tab
	// -------------------------------------------------------------------------

	public static function add_product_tab( array $tabs ): array {
		$tabs['woocom_pay'] = [
			'label'    => __( 'Woocom-Pay', 'woocom-pay' ),
			'target'   => 'woocom_pay_product_data',
			'class'    => [ 'show_if_simple', 'show_if_variable' ],
			'priority' => 75,
		];
		return $tabs;
	}

	public static function render_product_panel(): void {
		global $post;
		$product_id    = $post->ID;
		$payment_mode  = get_post_meta( $product_id, '_wcp_payment_mode', true ) ?: 'full';
		$partial_type  = get_post_meta( $product_id, '_wcp_partial_type', true ) ?: 'fixed';
		$partial_value = get_post_meta( $product_id, '_wcp_partial_value', true ) ?: '';
		?>
		<div id="woocom_pay_product_data" class="panel woocommerce_options_panel">
			<div class="options_group">
				<p class="form-field">
					<label for="_wcp_payment_mode"><?php esc_html_e( 'Payment Options', 'woocom-pay' ); ?></label>
					<select name="_wcp_payment_mode" id="_wcp_payment_mode" class="select short">
						<option value="full" <?php selected( $payment_mode, 'full' ); ?>><?php esc_html_e( 'Full Payment Only', 'woocom-pay' ); ?></option>
						<option value="partial" <?php selected( $payment_mode, 'partial' ); ?>><?php esc_html_e( 'Partial Payment Only', 'woocom-pay' ); ?></option>
						<option value="both" <?php selected( $payment_mode, 'both' ); ?>><?php esc_html_e( 'Full + Partial Payment', 'woocom-pay' ); ?></option>
					</select>
				</p>
			</div>
			<div class="options_group wcp-partial-options" style="<?php echo in_array( $payment_mode, [ 'partial', 'both' ], true ) ? '' : 'display:none'; ?>">
				<p class="form-field">
					<label for="_wcp_partial_type"><?php esc_html_e( 'Partial Payment Type', 'woocom-pay' ); ?></label>
					<select name="_wcp_partial_type" id="_wcp_partial_type" class="select short">
						<option value="fixed" <?php selected( $partial_type, 'fixed' ); ?>><?php esc_html_e( 'Fixed Amount (₹)', 'woocom-pay' ); ?></option>
						<option value="percentage" <?php selected( $partial_type, 'percentage' ); ?>><?php esc_html_e( 'Percentage (%)', 'woocom-pay' ); ?></option>
					</select>
				</p>
				<p class="form-field">
					<label for="_wcp_partial_value"><?php esc_html_e( 'Partial Payment Value', 'woocom-pay' ); ?></label>
					<input type="number" name="_wcp_partial_value" id="_wcp_partial_value" value="<?php echo esc_attr( $partial_value ); ?>" step="0.01" min="0" class="short">
					<span class="description"><?php esc_html_e( 'Enter amount (e.g. 2000) or percentage (e.g. 25)', 'woocom-pay' ); ?></span>
				</p>
			</div>
		</div>
		<script>
		jQuery( function( $ ) {
			$( '#_wcp_payment_mode' ).on( 'change', function() {
				var val = $( this ).val();
				if ( val === 'partial' || val === 'both' ) {
					$( '.wcp-partial-options' ).show();
				} else {
					$( '.wcp-partial-options' ).hide();
				}
			} );
		} );
		</script>
		<?php
	}

	public static function save_product_meta( int $post_id ): void {
		update_post_meta( $post_id, '_wcp_payment_mode', sanitize_text_field( $_POST['_wcp_payment_mode'] ?? 'full' ) );
		update_post_meta( $post_id, '_wcp_partial_type', sanitize_text_field( $_POST['_wcp_partial_type'] ?? 'fixed' ) );
		update_post_meta( $post_id, '_wcp_partial_value', sanitize_text_field( $_POST['_wcp_partial_value'] ?? '' ) );
	}

	// -------------------------------------------------------------------------
	// Helpers
	// -------------------------------------------------------------------------

	public static function get_product_payment_mode( int $product_id ): string {
		$mode = get_post_meta( $product_id, '_wcp_payment_mode', true );
		if ( $mode ) {
			return $mode;
		}
		$global = get_option( 'woocom_pay_settings', [] );
		if ( ! empty( $global['enable_partial'] ) ) {
			return 'both';
		}
		return 'full';
	}

	public static function calc_partial_amount( int $product_id, float $price ): float {
		$product_type  = get_post_meta( $product_id, '_wcp_partial_type', true );
		$product_value = (float) get_post_meta( $product_id, '_wcp_partial_value', true );

		// Fall back to global default if product has no value set.
		if ( $product_value > 0 && $product_type ) {
			$type  = $product_type;
			$value = $product_value;
		} else {
			$global = get_option( 'woocom_pay_settings', [] );
			$type   = $global['partial_default_type'] ?? 'percentage';
			$value  = (float) ( $global['partial_default_value'] ?? 50 );
		}

		if ( $type === 'percentage' ) {
			return round( $price * $value / 100, wc_get_price_decimals() );
		}
		return min( $value, $price );
	}

	// -------------------------------------------------------------------------
	// Product page
	// -------------------------------------------------------------------------

	public static function render_product_payment_options(): void {
		global $product;
		if ( ! $product ) {
			return;
		}

		$mode       = self::get_product_payment_mode( $product->get_id() );
		$full_price = (float) $product->get_price();

		if ( in_array( $mode, [ 'full', 'both' ], true ) && ! in_array( $mode, [ 'partial' ], true ) ) {
			// Full payment only — no radio needed, just display price note.
			if ( $mode === 'full' ) {
				return;
			}
		}

		$partial_amount = self::calc_partial_amount( $product->get_id(), $full_price );
		$balance        = $full_price - $partial_amount;

		wp_nonce_field( 'wcp_product_payment_nonce', 'wcp_nonce' );
		?>
		<div class="wcp-payment-options" style="margin-bottom:20px; padding:16px; border:1px solid #ddd; border-radius:6px; background:#fafafa;">
			<p style="margin:0 0 12px; font-weight:600; font-size:15px;"><?php esc_html_e( 'Payment Options', 'woocom-pay' ); ?></p>

			<?php if ( in_array( $mode, [ 'full', 'both' ], true ) ) : ?>
			<label class="wcp-option" style="display:flex; align-items:center; gap:10px; margin-bottom:10px; cursor:pointer;">
				<input type="radio" name="wcp_payment_type" value="full" <?php echo $mode === 'full' || $mode === 'both' ? 'checked' : ''; ?>>
				<span>
					<?php esc_html_e( 'Full Payment', 'woocom-pay' ); ?> &nbsp;
					<strong><?php echo wc_price( $full_price ); ?></strong>
				</span>
			</label>
			<?php endif; ?>

			<?php if ( in_array( $mode, [ 'partial', 'both' ], true ) ) : ?>
			<label class="wcp-option" style="display:flex; align-items:flex-start; gap:10px; cursor:pointer;">
				<input type="radio" name="wcp_payment_type" value="partial" <?php echo $mode === 'partial' ? 'checked' : ''; ?>>
				<span>
					<?php esc_html_e( 'Advance Payment', 'woocom-pay' ); ?> &nbsp;
					<strong><?php echo wc_price( $partial_amount ); ?></strong>
					<br>
					<small style="color:#666;"><?php echo esc_html( sprintf( __( 'Balance Due: %s', 'woocom-pay' ), strip_tags( wc_price( $balance ) ) ) ); ?></small>
				</span>
			</label>
			<?php endif; ?>
		</div>
		<?php
	}

	public static function validate_payment_option_selected( bool $passed, int $product_id, int $quantity ): bool {
		$mode = self::get_product_payment_mode( $product_id );

		if ( $mode === 'full' ) {
			return $passed;
		}

		// No nonce means the item was added from outside our product page form
		// (Tutor LMS enroll button, direct add-to-cart URL, etc.) — allow through.
		if ( empty( $_POST['wcp_nonce'] ) ) {
			return $passed;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( $_POST['wcp_nonce'] ), 'wcp_product_payment_nonce' ) ) {
			wc_add_notice( __( 'Security check failed. Please try again.', 'woocom-pay' ), 'error' );
			return false;
		}

		if ( empty( $_POST['wcp_payment_type'] ) ) {
			wc_add_notice( __( 'Please select a payment option before adding to cart.', 'woocom-pay' ), 'error' );
			return false;
		}

		return $passed;
	}

	public static function add_cart_item_data( array $cart_item_data, int $product_id, int $variation_id ): array {
		$mode = self::get_product_payment_mode( $product_id );

		if ( $mode === 'full' ) {
			$cart_item_data['wcp_payment_type'] = 'full';
			return $cart_item_data;
		}

		// Use $_REQUEST so GET params from Tutor LMS enroll links are also captured.
		$requested = sanitize_text_field( $_REQUEST['wcp_payment_type'] ?? '' );

		// Enforce mode: partial-only products always pay partial regardless of request.
		if ( $mode === 'partial' ) {
			$type = 'partial';
		} elseif ( $requested === 'partial' ) {
			$type = 'partial';
		} else {
			$type = 'full';
		}

		$product    = wc_get_product( $product_id );
		$full_price = (float) $product->get_price();

		$cart_item_data['wcp_payment_type']    = $type;
		$cart_item_data['wcp_full_price']      = $full_price;

		if ( $type === 'partial' ) {
			$partial = self::calc_partial_amount( $product_id, $full_price );
			$cart_item_data['wcp_partial_amount'] = $partial;
			$cart_item_data['wcp_balance_amount'] = $full_price - $partial;
		}

		return $cart_item_data;
	}

	// -------------------------------------------------------------------------
	// Cart display
	// -------------------------------------------------------------------------

	public static function display_cart_item_data( array $item_data, array $cart_item ): array {
		if ( empty( $cart_item['wcp_payment_type'] ) ) {
			return $item_data;
		}

		$type = $cart_item['wcp_payment_type'];

		if ( $type === 'partial' ) {
			$item_data[] = [
				'key'   => __( 'Payment Type', 'woocom-pay' ),
				'value' => __( 'Advance Payment', 'woocom-pay' ),
			];
			if ( isset( $cart_item['wcp_partial_amount'] ) ) {
				$item_data[] = [
					'key'   => __( 'Paying Now', 'woocom-pay' ),
					'value' => wc_price( $cart_item['wcp_partial_amount'] ),
				];
				$item_data[] = [
					'key'   => __( 'Balance Due', 'woocom-pay' ),
					'value' => wc_price( $cart_item['wcp_balance_amount'] ),
				];
			}
		} else {
			$item_data[] = [
				'key'   => __( 'Payment Type', 'woocom-pay' ),
				'value' => __( 'Full Payment', 'woocom-pay' ),
			];
		}

		return $item_data;
	}

	// -------------------------------------------------------------------------
	// Price override
	// -------------------------------------------------------------------------

	public static function adjust_cart_item_price( WC_Cart $cart ): void {
		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
			return;
		}
		foreach ( $cart->get_cart() as $key => $item ) {
			if ( ! empty( $item['wcp_payment_type'] ) && $item['wcp_payment_type'] === 'partial' && isset( $item['wcp_partial_amount'] ) ) {
				$item['data']->set_price( $item['wcp_partial_amount'] / max( 1, $item['quantity'] ) );
			}
		}
	}

	// -------------------------------------------------------------------------
	// Checkout
	// -------------------------------------------------------------------------

	public static function render_checkout_summary(): void {
		$has_partial = false;
		$total_full  = 0.0;
		$total_pay   = 0.0;
		$total_bal   = 0.0;

		foreach ( WC()->cart->get_cart() as $item ) {
			if ( isset( $item['wcp_payment_type'] ) && $item['wcp_payment_type'] === 'partial' ) {
				$has_partial  = true;
				$full         = (float) $item['wcp_full_price'] * $item['quantity'];
				$partial      = (float) $item['wcp_partial_amount'] * $item['quantity'];
				$total_full  += $full;
				$total_pay   += $partial;
				$total_bal   += ( $full - $partial );
			}
		}

		if ( ! $has_partial ) {
			return;
		}
		?>
		<div class="wcp-checkout-summary" style="background:#f9f9f9; border:1px solid #ddd; padding:14px 18px; border-radius:6px; margin-bottom:20px; font-size:14px;">
			<p style="font-weight:600; margin:0 0 8px;"><?php esc_html_e( 'Payment Summary', 'woocom-pay' ); ?></p>
			<table style="width:100%; border-collapse:collapse;">
				<tr><td><?php esc_html_e( 'Product Total', 'woocom-pay' ); ?></td><td style="text-align:right;"><?php echo wc_price( $total_full ); ?></td></tr>
				<tr><td><?php esc_html_e( 'Paying Now (Advance)', 'woocom-pay' ); ?></td><td style="text-align:right;color:#27ae60;font-weight:600;"><?php echo wc_price( $total_pay ); ?></td></tr>
				<tr><td><?php esc_html_e( 'Balance Due Later', 'woocom-pay' ); ?></td><td style="text-align:right;color:#e74c3c;"><?php echo wc_price( $total_bal ); ?></td></tr>
			</table>
		</div>
		<?php
	}

	// -------------------------------------------------------------------------
	// Order meta
	// -------------------------------------------------------------------------

	public static function save_order_item_meta( WC_Order_Item_Product $item, string $cart_item_key, array $values, WC_Order $order ): void {
		if ( isset( $values['wcp_payment_type'] ) ) {
			$item->add_meta_data( '_wcp_payment_type', $values['wcp_payment_type'], true );
		}
		if ( isset( $values['wcp_full_price'] ) ) {
			$item->add_meta_data( '_wcp_full_price', $values['wcp_full_price'], true );
		}
		if ( isset( $values['wcp_partial_amount'] ) ) {
			$item->add_meta_data( '_wcp_partial_amount', $values['wcp_partial_amount'], true );
		}
		if ( isset( $values['wcp_balance_amount'] ) ) {
			$item->add_meta_data( '_wcp_balance_amount', $values['wcp_balance_amount'], true );
		}
	}

	// -------------------------------------------------------------------------
	// Tutor LMS integration
	// -------------------------------------------------------------------------

	public static function render_tutor_payment_options(): void {
		$course_id  = get_the_ID();
		$product_id = (int) get_post_meta( $course_id, '_tutor_course_product_id', true );

		if ( ! $product_id ) {
			return;
		}

		$mode = self::get_product_payment_mode( $product_id );
		if ( $mode === 'full' ) {
			return;
		}

		$product = wc_get_product( $product_id );
		if ( ! $product ) {
			return;
		}

		$full_price     = (float) $product->get_price();
		$partial_amount = self::calc_partial_amount( $product_id, $full_price );
		$balance        = $full_price - $partial_amount;

		wp_enqueue_style( 'woocom-pay-public', WOOCOM_PAY_PLUGIN_URL . 'public/css/public.css', [], WOOCOM_PAY_VERSION );
		?>
		<div class="wcp-payment-options wcp-tutor-payment-options" style="margin-bottom:20px; padding:16px; border:1px solid #ddd; border-radius:6px; background:#fafafa;">
			<p style="margin:0 0 12px; font-weight:600; font-size:15px;"><?php esc_html_e( 'Payment Options', 'woocom-pay' ); ?></p>

			<?php if ( in_array( $mode, [ 'full', 'both' ], true ) ) : ?>
			<label class="wcp-option" style="display:flex; align-items:center; gap:10px; margin-bottom:10px; cursor:pointer;">
				<input type="radio" name="wcp_payment_type" value="full" checked>
				<span>
					<?php esc_html_e( 'Full Payment', 'woocom-pay' ); ?> &nbsp;
					<strong><?php echo wc_price( $full_price ); ?></strong>
				</span>
			</label>
			<?php endif; ?>

			<?php if ( in_array( $mode, [ 'partial', 'both' ], true ) ) : ?>
			<label class="wcp-option" style="display:flex; align-items:flex-start; gap:10px; cursor:pointer;">
				<input type="radio" name="wcp_payment_type" value="partial" <?php echo $mode === 'partial' ? 'checked' : ''; ?>>
				<span>
					<?php esc_html_e( 'Advance Payment', 'woocom-pay' ); ?> &nbsp;
					<strong><?php echo wc_price( $partial_amount ); ?></strong>
					<br>
					<small style="color:#666;"><?php echo esc_html( sprintf( __( 'Balance Due: %s', 'woocom-pay' ), strip_tags( wc_price( $balance ) ) ) ); ?></small>
				</span>
			</label>
			<?php endif; ?>
		</div>
		<?php
	}

	public static function inject_tutor_enroll_script(): void {
		if ( ! is_singular( 'courses' ) ) {
			return;
		}
		?>
		<script>
		( function ( $ ) {
			'use strict';

			// Intercept add-to-cart anchor links (Tutor LMS enroll button with WooCommerce).
			$( document ).on( 'click', 'a[href*="add-to-cart"]', function ( e ) {
				var $options = $( 'input[name="wcp_payment_type"]' );
				if ( ! $options.length ) {
					return;
				}
				var paymentType = $options.filter( ':checked' ).val() || 'full';
				var href = $( this ).attr( 'href' );
				var sep  = ( href.indexOf( '?' ) !== -1 ) ? '&' : '?';
				e.preventDefault();
				window.location.href = href + sep + 'wcp_payment_type=' + encodeURIComponent( paymentType );
			} );

			// Intercept add-to-cart form submissions (some Tutor LMS themes use a form).
			$( document ).on( 'submit', 'form.cart, form[action*="add-to-cart"]', function () {
				var $options = $( 'input[name="wcp_payment_type"]' );
				if ( ! $options.length ) {
					return;
				}
				var paymentType = $options.filter( ':checked' ).val() || 'full';
				if ( ! $( this ).find( 'input[name="wcp_payment_type"]' ).length ) {
					$( this ).append( $( '<input>' ).attr( { type: 'hidden', name: 'wcp_payment_type', value: paymentType } ) );
				}
			} );
		} )( jQuery );
		</script>
		<?php
	}

	// -------------------------------------------------------------------------

	public static function save_order_payment_meta( WC_Order $order ): void {
		$has_partial  = false;
		$total_full   = 0.0;
		$total_pay    = 0.0;
		$total_bal    = 0.0;

		foreach ( $order->get_items() as $item ) {
			$type = $item->get_meta( '_wcp_payment_type' );
			if ( $type === 'partial' ) {
				$has_partial  = true;
				$qty          = (int) $item->get_quantity();
				$full         = (float) $item->get_meta( '_wcp_full_price' ) * $qty;
				$partial      = (float) $item->get_meta( '_wcp_partial_amount' ) * $qty;
				$total_full  += $full;
				$total_pay   += $partial;
				$total_bal   += ( $full - $partial );
			}
		}

		if ( $has_partial ) {
			$order->update_meta_data( '_wcp_has_partial', '1' );
			$order->update_meta_data( '_wcp_product_total', $total_full );
			$order->update_meta_data( '_wcp_paid_amount', $total_pay );
			$order->update_meta_data( '_wcp_balance_amount', $total_bal );
			$order->save();
		}
	}
}
