<?php
declare(strict_types=1);
/**
 * File responsible for Controller methods that handle fulfillment type selection.
 *
 * Author: Uriahs Victor
 * Created on: 07/11/2025 (d/m/y)
 *
 * @link    https://uriahsvictor.com
 * @package \OrderTypeSelection
 * @since   1.5.0
 */

namespace Lpac_DPS\Controllers\Features;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Lpac_DPS\Helpers\Logger;
use Lpac_DPS\Models\PluginSettings\OrderType;

/**
 * Class which defines methods that handle fulfillment type selection.
 *
 * @package \Lpac_DPS\Controllers\Features\OrderTypeSelection
 * @since   1.5.0
 */
class FulfillmentTypeSelectionController {

	/**
	 * Listen to when the user selects a fulfillment type.
	 *
	 * @return void
	 * @since 1.5.0
	 */
	public function listenToFulfillmentTypeSelection() {

		$nonce = $_REQUEST['nonce'] ?? '';

		$varified = wp_verify_nonce( $nonce, 'chwazi_fulfillment_selection_nonce' );
		if ( $varified === false ) {
			wp_send_json_error( __( 'Invalid nonce. Please try again or contact us if the issue persists.', 'delivery-and-pickup-scheduling-for-woocommerce' ), 400 );
		}

		$fulfillment_type = $_REQUEST['fulfillmentType'] ?? '';
		if ( empty( $fulfillment_type ) ) {
			( new Logger() )->logCritical( 'Failed to retrieve fulfillment_type from request. Request dump:' . json_encode( $_REQUEST ) );
			$fulfillment_type = OrderType::getDefaultOrderType();
		}

		$current_session_fulfillment_type = WC()->session->get( 'chwazi_selected_fulfillment_type' );
		if ( $current_session_fulfillment_type === $fulfillment_type ) {
			wp_send_json_success();
		}

		$this->addFulfillmentTypeToSession( $fulfillment_type );

		wp_send_json_success();
	}

	/**
	 * Add the fulfillment type to the WC session.
	 *
	 * @param string $fulfillment_type
	 *
	 * @return void
	 * @since 1.5.0
	 */
	private function addFulfillmentTypeToSession( string $fulfillment_type ): void {
		// Check if WC() is available.
		if ( function_exists( 'WC' ) === false ) {
			( new Logger() )->logCritical( 'WC() is not available. Cannot add fulfillment type to WC session.' );
			return;
		}

		WC()->session->set( 'chwazi_selected_fulfillment_type', $fulfillment_type );
	}
}
