<?php
/**
 * GGM Commerce Subscription AJAX Handlers
 * Frontend customer self-service actions.
 *
 * @package GGM_Commerce
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Subscription AJAX handler class.
 */
class GGM_Commerce_Subscription_Ajax {

	/**
	 * Singleton instance.
	 *
	 * @var GGM_Commerce_Subscription_Ajax
	 */
	private static $instance = null;

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

	/**
	 * Constructor — register AJAX hooks.
	 */
	private function __construct() {
		add_action( 'wp_ajax_ggmc_customer_subscription_action', array( $this, 'handle_customer_action' ) );
		add_action( 'wp_ajax_ggmc_get_customer_subscriptions', array( $this, 'get_customer_subscriptions' ) );
	}

	/**
	 * Handle a customer self-service subscription action.
	 */
	public function handle_customer_action() {
		// Verify nonce.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ggmc_subscription_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'ggm-commerce' ) ) );
			return;
		}

		// Must be logged in.
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => __( 'You must be logged in.', 'ggm-commerce' ) ) );
			return;
		}

		$subscription_id = isset( $_POST['subscription_id'] ) ? absint( $_POST['subscription_id'] ) : 0;
		$action          = isset( $_POST['subscription_action'] ) ? sanitize_text_field( wp_unslash( $_POST['subscription_action'] ) ) : '';

		if ( ! $subscription_id || ! $action ) {
			wp_send_json_error( array( 'message' => __( 'Invalid request.', 'ggm-commerce' ) ) );
			return;
		}

		$sub_manager  = GGM_Commerce_Subscriptions::instance();
		$subscription = $sub_manager->get_subscription( $subscription_id );

		if ( ! $subscription ) {
			wp_send_json_error( array( 'message' => __( 'Subscription not found.', 'ggm-commerce' ) ) );
			return;
		}

		// Verify ownership — customer can only manage their own subscriptions.
		$current_user = wp_get_current_user();
		if ( $current_user->user_email !== $subscription->customer_email && (int) $subscription->customer_id !== get_current_user_id() ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to manage this subscription.', 'ggm-commerce' ) ) );
			return;
		}

		// Check admin settings for what's allowed.
		$settings = GGM_Commerce_Subscriptions::get_settings();

		$result = false;

		switch ( $action ) {
			case 'pause':
				if ( ! $settings['allow_pause'] ) {
					wp_send_json_error( array( 'message' => __( 'Pausing subscriptions is not enabled.', 'ggm-commerce' ) ) );
					return;
				}
				$result = $sub_manager->pause_subscription( $subscription_id, 'customer' );
				break;

			case 'resume':
				$result = $sub_manager->resume_subscription( $subscription_id, 'customer' );
				break;

			case 'cancel':
				if ( ! $settings['allow_cancel'] ) {
					wp_send_json_error( array( 'message' => __( 'Cancelling subscriptions is not enabled.', 'ggm-commerce' ) ) );
					return;
				}

				// Handle cancellation behavior (end_of_period vs immediate).
				if ( 'end_of_period' === $settings['cancellation_behavior'] && in_array( $subscription->status, array( 'active', 'trial' ), true ) ) {
					// Set to pending_cancel — subscription remains active until next payment date.
					$sub_manager->update_subscription( $subscription_id, array( 'status' => 'pending_cancel' ) );
					$sub_manager->log_event(
						$subscription_id,
						'pending_cancellation',
						'Customer requested cancellation at end of billing period.',
						null,
						null,
						'customer'
					);
					$result = true;
				} else {
					$result = $sub_manager->cancel_subscription( $subscription_id, 'Customer self-service cancellation', 'customer' );
				}

				// Also cancel on the gateway side.
				if ( $result && 'paypal' === $subscription->payment_gateway && ! empty( $subscription->gateway_subscription_id ) ) {
					$gateway = ggm_commerce_gateways()->get_gateway( 'paypal' );
					if ( $gateway ) {
						$gateway->cancel_paypal_subscription( $subscription->gateway_subscription_id, 'Customer cancelled.' );
					}
				}
				break;

			case 'reactivate':
				if ( ! $settings['allow_reactivate'] ) {
					wp_send_json_error( array( 'message' => __( 'Reactivating subscriptions is not enabled.', 'ggm-commerce' ) ) );
					return;
				}
				$result = $sub_manager->activate_subscription( $subscription_id );

				// Reactivate on PayPal if applicable.
				if ( $result && 'paypal' === $subscription->payment_gateway && ! empty( $subscription->gateway_subscription_id ) ) {
					$gateway = ggm_commerce_gateways()->get_gateway( 'paypal' );
					if ( $gateway ) {
						$gateway->activate_paypal_subscription( $subscription->gateway_subscription_id );
					}
				}
				break;

			default:
				wp_send_json_error( array( 'message' => __( 'Invalid action.', 'ggm-commerce' ) ) );
				return;
		}

		if ( $result ) {
			wp_send_json_success( array( 'message' => __( 'Subscription updated.', 'ggm-commerce' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to update subscription.', 'ggm-commerce' ) ) );
		}
	}

	/**
	 * Get customer's subscriptions via AJAX.
	 */
	public function get_customer_subscriptions() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ggmc_subscription_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'ggm-commerce' ) ) );
			return;
		}

		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => __( 'You must be logged in.', 'ggm-commerce' ) ) );
			return;
		}

		$sub_manager  = GGM_Commerce_Subscriptions::instance();
		$current_user = wp_get_current_user();
		$subscriptions = $sub_manager->get_customer_subscriptions_by_email( $current_user->user_email );

		$data = array();
		foreach ( $subscriptions as $sub ) {
			$data[] = array(
				'id'                => $sub->id,
				'subscription_number' => $sub->subscription_number,
				'status'            => $sub->status,
				'recurring_total'   => $sub->recurring_total,
				'billing_period'    => $sub->billing_period,
				'billing_interval'  => $sub->billing_interval,
				'next_payment_date' => $sub->next_payment_date,
			);
		}

		wp_send_json_success( array( 'subscriptions' => $data ) );
	}
}
