<?php
namespace ApproveOrders;

use ApproveOrders\Settings as AOFWC_Settings;
use ApproveOrders\Modules\PrePayGateway as AOFWC_PreOrderPay;
use ApproveOrders\Modules\Rules as AOFWC_Rules;
use ApproveOrders\Rest_API as AOFWC_Rest_API;
use ApproveOrders\Helper as AOFWC_Helper;

/**
 * The front-end plugin class for Approve Orders.
 */
class Frontend {
	/**
	 * Initialize the front-end functionality of the plugin.
	 */
	public function init() {

		// Add the PreOrderPay gateway to the list of available payment gateways
		add_filter( 'woocommerce_payment_gateways', array( $this, 'add_pre_order_gateway' ) );
		// Show Allowed Payment Gayeways
		add_filter( 'woocommerce_available_payment_gateways', array( $this, 'allowed_gateways' ) );
		// Add WooCommerce Thank You hook
		add_action( 'woocommerce_thankyou', array( $this, 'woocommerce_thankyou' ), 10, 1 );

		add_action( 'woocommerce_account_aofwc-mark_endpoint', array( $this, 'handle_mark_order_status' ) );
	}

	/**
	 * Add the PreOrderPay gateway to the list of available payment gateways.
	 *
	 * @param array $gateways The list of available payment gateways.
	 * @return array The list of available payment gateways with the PreOrderPay gateway added.
	 */
	public function add_pre_order_gateway( $gateways ) {
		$gateways[] = AOFWC_PreOrderPay::class;
		return $gateways;
	}

	/**
	 * Manage Allowed Payment Gateways.
	 *
	 * @param array $gateways The list of available payment gateways.
	 * @return array The list of available payment gateways with the PreOrderPay gateway added.
	 */
	public function allowed_gateways( $available_gateways ) {

		// If Approve Orders settings page then return
		if( isset( $_GET['page'] ) && 'approve-orders' === sanitize_text_field( $_GET['page'] ) ){ // phpcs:ignore
			return $available_gateways;
		}

		$settings          = AOFWC_Settings::get_instance();
		$options           = $settings->get();
		$selected_gateways = $options['selected_gateways'];
		$allowed_gateways  = array_intersect( $selected_gateways, array_keys( $available_gateways ) );
		$rules             = AOFWC_Rest_API::get_instance()->fetch_rules( 0 );
		$is_pre_order      = false;

		if ( is_checkout() && ! empty( $rules ) ) {
			$process_rules = aofwc_process_rules( WC()->cart, $rules );

			if ( ! empty( $process_rules['approvalAction'] ) && 'preOrder' === $process_rules['approvalAction'] ) {
				$is_pre_order = true;
			}
		}

		// Manage Pre Order payment gateway on Checkout and Order Pay Page
		foreach ( $available_gateways as $gateway_id => $gateway ) {
			if ( is_checkout_pay_page() ) {
				if ( in_array( $gateway_id, $allowed_gateways, true ) ) {
					unset( $available_gateways[ $gateway_id ] );
				}
			} elseif ( ( $is_pre_order || 'enabled' === $options['approval_workflow'] ) && ! empty( $allowed_gateways ) && ! in_array( $gateway_id, $allowed_gateways, true ) ) {
					unset( $available_gateways[ $gateway_id ] );
			}
		}

		return $available_gateways;
	}

	/**
	 * Add woocommerce_thankyou hook method
	 *
	 * @param string $order_id The list of available payment gateways.
	 */
	public function woocommerce_thankyou( $order_id ) {
		// Return early if the page is the Order Pay page or if no order ID is provided
		if ( is_checkout_pay_page() || ! $order_id ) {
			return;
		}

		$settings           = AOFWC_Settings::get_instance();
		$options            = $settings->get();
		$selected_gateways  = $options['selected_gateways'];
		$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
		$allowed_gateways   = array_intersect( $selected_gateways, array_keys( $available_gateways ) );

		// Get the order and current user
		$order        = wc_get_order( $order_id );
		$current_user = wp_get_current_user();

		$helper_instance = AOFWC_Helper::get_instance();

		if ( ao_fs()->is_paying_or_trial() ) {
			// Update Order based on Rules
			$saved_rules = AOFWC_Rest_API::get_instance()->fetch_rules( 0 );
			if ( 'disabled' === $options['approval_workflow'] && ! empty( $saved_rules ) ) {
				$processed_rules = AOFWC_Rules::get_instance()->process_rules( $order_id, $saved_rules );
				if ( $processed_rules ) {
					switch ( $processed_rules['approvalAction'] ) {
						case 'sendForApproval':
							$helper_instance->update_order_status( $order_id, 'awaiting-approval' );
							break;
						case 'autoRejectOrder':
							$helper_instance->update_order_status( $order_id, 'rejected' );
							break;
						case 'autoApproveOrder':
							$helper_instance->update_order_status( $order_id, 'approved' );
							break;
						default:
							break;

					}
				}
			}
		}

		// Check if approval workflow is enabled
		if ( 'enabled' === $options['approval_workflow'] ) {
			$should_update = false;

			// Check payment method
			if ( ! empty( $allowed_gateways ) && in_array( $order->get_payment_method(), $allowed_gateways, true ) ) {
				$should_update = true;
			}

			// Check user role
			if ( array_intersect( $options['selected_roles'], $current_user->roles ) ) {
				$should_update = true;
			}

			// Update order status if conditions are met
			if ( $should_update ) {
				$helper_instance->update_order_status( $order_id, 'awaiting-approval' );
			}
		}
	}

	/**
	 * Handle mark order status
	 *
	 * @param void
	 * @return void
	 *
	 * @since 1.0.4
	 */
	public function handle_mark_order_status() {
		global $wp_query;

		if ( ! isset( $wp_query->query_vars['aofwc-mark'] ) ) {
			return;
		}

		$order_id   = isset( $_GET['order_id'] ) ? absint( $_GET['order_id'] ) : 0; // phpcs:ignore
		$new_status = isset( $_GET['status'] ) ? sanitize_text_field( $_GET['status'] ) : ''; // phpcs:ignore

		if ( ! $order_id || ! $new_status ) {
			wc_add_notice( __( 'Missing order ID or status.', 'aofwc' ), 'error' );
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wc_add_notice( __( 'Invalid order.', 'aofwc' ), 'error' );
			return;
		}

		// Optional: Add capability check to restrict status updates
		if ( ! current_user_can( 'edit_shop_orders' ) && ! current_user_can( 'edit_shop_order' ) ) {
			wc_add_notice( __( 'You are not allowed to update this order.', 'aofwc' ), 'error' );
			return;
		}

		if ( in_array( $order->get_status(), array( 'awaiting-approval', 'pending' ), true ) ) {
			do_action( 'custom_before_order_status_change', $order, $new_status );

			$order->update_status( $new_status, 'Status updated via My Account link.' );

			do_action( 'custom_after_order_status_change', $order, $new_status );

			wc_add_notice( sprintf( __( 'Order #%1$d status updated to %2$s.', 'aofwc' ), $order_id, $new_status ), 'success' );

			wp_redirect( wc_get_account_endpoint_url( 'orders' ) );
			exit;
		} else {
			wc_add_notice( __( 'Invalid status value.', 'aofwc' ), 'error' );
		}
	}
}
