<?php
/**
 * LatePoint Create Customer Action
 *
 * Handles creating a new customer in LatePoint.
 *
 * @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 Customer Action Class
 *
 * @since 1.13.0
 */
class Create_Customer 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_customer';

	/**
	 * 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( 'OsCustomerModel' );
	}

	/**
	 * Execute LatePoint Create Customer action
	 *
	 * @param array $data Form submission data.
	 * @return array|\WP_Error Result of the action execution.
	 * @throws \Exception When customer creation/update fails.
	 * @since 1.13.0
	 */
	protected function execute( $data ) {
		// Check if this is test mode execution.
		$is_test_mode = isset( $data['_test_mode'] ) && true === $data['_test_mode'];

		// Remove test mode flags from data for processing.
		if ( $is_test_mode ) {
			unset( $data['_test_mode'] );
			// Add test identifier to mark it as a test customer.
			$data['admin_notes'] = ( $data['admin_notes'] ?? '' ) . __( "\n\n[TEST CUSTOMER - Created by SureForms workflow test]", 'sureforms-pro' );
		}

		// Validate required data.
		$required_fields = [ 'first_name', 'last_name', 'email' ];
		$validation      = $this->validate_required_fields( $data, $required_fields );

		if ( is_wp_error( $validation ) ) {
			return $validation;
		}

		try {
			// Check if customer already exists by email.
			$customer_model    = new \OsCustomerModel();
			$existing_customer = $customer_model->where( [ 'email' => $data['email'] ] )->set_limit( 1 )->get_results_as_models();

			if ( ! empty( $existing_customer ) ) {
				// Update existing customer with new data.
				$old_customer_data = $existing_customer->get_data_vars();

				$update_params = [
					'first_name'  => $data['first_name'],
					'last_name'   => $data['last_name'],
					'phone'       => $data['phone'] ?? $existing_customer->phone,
					'notes'       => $data['notes'] ?? $existing_customer->notes,
					'admin_notes' => $data['admin_notes'] ?? $existing_customer->admin_notes ?? '',
				];

				// Add custom fields if present.
				$custom_fields = LatePoint_Integration::extract_customer_custom_fields( $data );
				if ( ! empty( $custom_fields ) ) {
					$update_params['custom_fields'] = $custom_fields;
				}

				$existing_customer->set_data( $update_params );

				if ( ! $existing_customer->save() ) {
					$errors    = $existing_customer->get_error_messages();
					$error_msg = $errors[0] ?? __( 'Failed to update customer.', 'sureforms-pro' );
					throw new \Exception( $error_msg );
				}

				// Fire update hook - using LatePoint's native hook name for compatibility.
				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
				do_action( 'latepoint_customer_updated', $existing_customer, $old_customer_data );

				return [
					'success'     => true,
					'message'     => __( 'Customer updated successfully!', 'sureforms-pro' ),
					'customer_id' => $existing_customer->id,
					'is_new'      => false,
				];
			}

			// Create new customer.
			$customer_params = [
				'first_name'  => $data['first_name'],
				'last_name'   => $data['last_name'],
				'email'       => $data['email'],
				'phone'       => $data['phone'] ?? '',
				'notes'       => $data['notes'] ?? '',
				'admin_notes' => $data['admin_notes'] ?? '',
				'status'      => 'active',
			];

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

			$customer = new \OsCustomerModel();
			$customer->set_data( $customer_params );

			if ( ! $customer->save() ) {
				$errors    = $customer->get_error_messages();
				$error_msg = $errors[0] ?? __( 'Failed to create customer.', 'sureforms-pro' );
				throw new \Exception( $error_msg );
			}

			// Fire create hook - using LatePoint's native hook name for compatibility.
			// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
			do_action( 'latepoint_customer_created', $customer );

			return [
				'success'     => true,
				'message'     => __( 'Customer created successfully!', 'sureforms-pro' ),
				'customer_id' => $customer->id,
				'is_new'      => true,
			];

		} catch ( \Exception $e ) {
			return new \WP_Error(
				'customer_creation_failed',
				sprintf(
					// translators: %s: Error message.
					__( 'Customer creation failed: %s', 'sureforms-pro' ),
					$e->getMessage()
				)
			);
		}
	}

}

// Initialize the action when this file is loaded.
Create_Customer::get_instance();
