<?php
/**
 * LatePoint Create Order Action
 *
 * Handles creating orders in LatePoint through SureForms.
 *
 * @package SureForms
 * @since 1.13.0
 */

namespace SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\LatePoint\Actions;

use SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\LatePoint\LatePoint_Integration;
use SRFM_Pro\Inc\Pro\Native_Integrations\WordPress_Action;
use SRFM_Pro\Inc\Traits\Get_Instance;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Create Order Action Class
 *
 * @since 1.13.0
 */
class Create_Order extends WordPress_Action {
	use Get_Instance;

	/**
	 * Integration name
	 *
	 * @var string
	 * @since 1.13.0
	 */
	protected $integration = 'latepoint';

	/**
	 * Action name
	 *
	 * @var string
	 * @since 1.13.0
	 */
	protected $action = 'create_order';

	/**
	 * Execute the create order action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If order creation fails.
	 * @since 1.13.0
	 */
	protected function execute( $data ) {
		try {
			$customer_type  = $data['customer_type'] ?? 'new';
			$customer_email = null;

			if ( 'existing' === $customer_type ) {
				$customer_email = $data['customer_email'] ?? null;
				if ( ! $customer_email ) {
					throw new \Exception( 'Customer email not provided for existing customer.' );
				}
			}

			// Handle customer creation or selection.
			if ( 'new' === $customer_type ) {
				$customer_params = [
					'first_name' => $data['customer_first_name'] ?? '',
					'last_name'  => $data['customer_last_name'] ?? '',
					'email'      => $data['customer_email'] ?? '',
					'phone'      => $data['customer_phone'] ?? '',
					'notes'      => $data['customer_notes'] ?? '',
				];

				$customer          = new \OsCustomerModel();
				$existing_customer = $customer->where( [ 'email' => $customer_params['email'] ] )->set_limit( 1 )->get_results_as_models();

				if ( isset( $existing_customer->id ) && ! empty( $existing_customer->id ) ) {
					$customer = new \OsCustomerModel( $existing_customer->id );
				} else {
					$customer = new \OsCustomerModel();
				}

				// Handle customer custom fields.
				$customer_custom_fields = LatePoint_Integration::extract_customer_custom_fields( $data );
				if ( ! empty( $customer_custom_fields ) ) {
					$customer_params['custom_fields'] = $customer_custom_fields;
				}

				$customer->set_data( $customer_params );
				if ( ! $customer->save() ) {
					$errors    = $customer->get_error_messages();
					$error_msg = $errors[0] ?? 'Customer could not be created.';
					throw new \Exception( $error_msg );
				}
			} else {
				// Find existing customer by email.
				$customer_model    = new \OsCustomerModel();
				$existing_customer = $customer_model->where( [ 'email' => $customer_email ] )->set_limit( 1 )->get_results_as_models();

				if ( empty( $existing_customer ) ) {
					throw new \Exception( 'Customer with email "' . $customer_email . '" not found.' );
				}

				$customer = new \OsCustomerModel( $existing_customer->id );
			}

			// Create order.
			$order                     = new \OsOrderModel();
			$order->status             = $data['order_status'] ?? \OsOrdersHelper::get_default_order_status();
			$order->fulfillment_status = $data['fulfillment_status'] ?? $order->get_default_fulfillment_status();
			$order->customer_id        = $customer->id;
			$order->payment_status     = $data['payment_status'] ?? 'not_paid';

			if ( ! $order->save() ) {
				$errors    = $order->get_error_messages();
				$error_msg = $errors[0] ?? 'Order could not be created.';
				throw new \Exception( $error_msg );
			}

			// Handle bundle order if bundle_id is provided.
			if ( ! empty( $data['bundle_id'] ) ) {
				$bundle = new \OsBundleModel( $data['bundle_id'] );

				if ( ! $bundle->id ) {
					throw new \Exception( 'Invalid bundle ID provided.' );
				}

				$order_item_model           = new \OsOrderItemModel();
				$order_item_model->variant  = defined( 'LATEPOINT_ITEM_VARIANT_BUNDLE' ) ? LATEPOINT_ITEM_VARIANT_BUNDLE : 'bundle';
				$order_item_model->order_id = $order->id;

				if ( ! $order_item_model->save() ) {
					$errors    = $order_item_model->get_error_messages();
					$error_msg = $errors[0] ?? 'Order Item could not be created.';
					throw new \Exception( $error_msg );
				}

				$bundle_data = [
					'bundle_id' => $bundle->id,
				];

				$order_item_model->item_data = wp_json_encode( $bundle_data );
				$order_item_model->recalculate_prices();

				$order->total    = $order_item_model->total;
				$order->subtotal = $order_item_model->subtotal;
				$order->save();
				$order_item_model->save();
			}

			// Trigger action.
			do_action( 'latepoint_order_created', $order ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- LatePoint action.

			$return_data             = $order->get_data_vars();
			$return_data['customer'] = $customer->get_data_vars();

			if ( ! empty( $data['bundle_id'] ) && isset( $bundle ) ) {
				$return_data['bundle'] = $bundle->get_data_vars();
			}

			return [
				'success' => true,
				'message' => __( 'Order created successfully.', 'sureforms-pro' ),
				'data'    => $return_data,
			];

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to create order: %s', 'sureforms-pro' ),
					$e->getMessage()
				),
			];
		}
	}

	/**
	 * Check if LatePoint plugin is active
	 *
	 * @return bool True if LatePoint is active, false otherwise.
	 * @since 1.13.0
	 */
	protected function is_plugin_active() {
		return class_exists( 'OsOrderModel' ) && class_exists( 'OsCustomerModel' ) && class_exists( 'OsOrderItemModel' );
	}

}

// Initialize the class.
Create_Order::get_instance();
