<?php

class Ahapaybuynowpaylater_Status_Handler
{
	/**
	 * Ahapaybuynowpaylater gateway instance
	 *
	 * @var $gateway
	 */
	private $gateway;


	/**
	 * Constructor
	 *
	 * @param Ahapaybuynowpaylater_WC_Gateway $gateway The Ahapaybuynowpaylater gateway instance
	 * @throws \RuntimeException If the Ahapaybuynowpaylater gateway class is not found
	 * @throws \InvalidArgumentException If the provided gateway is not an instance of the expected gateway class
	 */
	public function __construct($gateway)
	{
		// Allow either the new or legacy gateway class during the rename transition
		if (!class_exists('Ahapaybuynowpaylater_WC_Gateway')) {
			throw new \RuntimeException('Ahapaybuynowpaylater gateway class not found. Please ensure the plugin is installed and activated.');
		}
		if (!$gateway instanceof Ahapaybuynowpaylater_WC_Gateway) {
			throw new \InvalidArgumentException('Expected an instance of Ahapaybuynowpaylater_WC_Gateway');
		}
		$this->gateway = $gateway;
	}


	/**
	 * Handle the payment status update from Ahapaybuynowpaylater
	 *
	 * @param WC_Order $order The WooCommerce order object
	 * @param string $status The payment status from Ahapaybuynowpaylater
	 * @param string $transaction_id The transaction ID from Ahapaybuynowpaylater
	 * @return bool True on success, false on failure
	 */
	public function handle_status($order, $status, $transaction_id)
	{
		// Validate the order object
		if (!$order instanceof WC_Order) {
			throw new \InvalidArgumentException('Expected a WC_Order object');
		}

		$this->log_info('Status handler invoked', [
			'order_id' => $order->get_id(),
			'current_status' => $order->get_status(),
			'incoming_status' => (string) $status,
			'transaction_id' => (string) $transaction_id,
		]);

		// if an order is refunded, no further action needed
		if ($order->get_status() === 'refunded') {
			$this->log_info('Order already refunded - skipping', [
				'order_id' => $order->get_id()
			]);
			return true;
		}
		try {
			switch ($status) {
				case 'PAYMENT_SUCCESSFUL':
					$this->log_info('Applying PAYMENT_SUCCESSFUL', [ 'order_id' => $order->get_id() ]);
					$order->payment_complete($transaction_id);
					$order->add_order_note('Payment completed via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					break;

				case 'CANCELLED':
					$this->log_info('Applying CANCELLED', [ 'order_id' => $order->get_id() ]);
					$order->add_order_note('Payment cancelled via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					$order->update_status('cancelled', 'Payment cancelled via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					break;


				case 'UNAVAILABLE':
					$this->log_info('Applying UNAVAILABLE (failed)', [ 'order_id' => $order->get_id() ]);
					$order->add_order_note('Payment failed via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					$order->update_status('failed', 'Payment failed via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					break;

				case 'PAYMENT_IN_PROGRESS':
					$this->log_info('Applying PAYMENT_IN_PROGRESS (on-hold)', [ 'order_id' => $order->get_id() ]);
					$order->add_order_note('Payment pending via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					$order->update_status('on-hold', 'Payment pending via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					break;
				case 'REFUNDED':
					$this->log_info('Applying REFUNDED', [ 'order_id' => $order->get_id() ]);
					$order->add_order_note('Payment refunded via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					$order->update_status('refunded', 'Payment refunded via Ahapaybuynowpaylater. Transaction ID: ' . $transaction_id);
					break;

				default:
					$this->log_error('Unhandled status received', [
						'order_id' => $order->get_id(),
						'incoming_status' => (string) $status
					]);
					return false;
			}

			$order->save();
			$this->log_info('Order saved after status update', [
				'order_id' => $order->get_id(),
				'final_status' => $order->get_status()
			]);

		} catch (Exception $e) {
			$this->log_error('Status handler error', [ 'exception' => $e->getMessage() ]);
			return false;
		}


		return true;
	}

	/**
	 * Helper: info log
	 */
	private function log_info($message, array $context = []) {
		if (method_exists($this->gateway, 'log')) {
			$this->gateway->log($this->format_log($message, $context), 'info');
		}
	}

	/**
	 * Helper: error log
	 */
	private function log_error($message, array $context = []) {
		if (method_exists($this->gateway, 'log')) {
			$this->gateway->log($this->format_log($message, $context), 'error');
		}
	}

	/**
	 * Helper: format log line
	 */
	private function format_log($message, array $context = []) {
		if (empty($context)) {
			return (string) $message;
		}
		return (string) $message . ' | context=' . wp_json_encode($context);
	}
}