<?php
/**
 * LatePoint Create Agent Action
 *
 * Handles creating agents 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\WordPress_Action;
use SRFM_Pro\Inc\Traits\Get_Instance;

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

/**
 * Create Agent Action Class
 *
 * @since 1.13.0
 */
class Create_Agent 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_agent';

	/**
	 * Execute the create agent action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If agent creation fails.
	 * @since 1.13.0
	 */
	protected function execute( $data ) {

		try {
			// Process service IDs for agent-service connections.
			$services = [];
			if ( isset( $data['service_ids'] ) && is_array( $data['service_ids'] ) ) {
				foreach ( $data['service_ids'] as $service_id ) {
					$services[ 'service_' . $service_id ] = [
						'location_1' => [
							'connected' => 'yes',
						],
					];
				}
			}

			// Handle WordPress user ID.
			$wp_user_id = '';
			if ( isset( $data['wp_user_id'] ) ) {
				$wp_user_id = is_array( $data['wp_user_id'] ) && isset( $data['wp_user_id']['value'] )
					? $data['wp_user_id']['value']
					: $data['wp_user_id'];
			}

			$agent_params = [
				'first_name'   => $data['first_name'] ?? '',
				'last_name'    => $data['last_name'] ?? '',
				'display_name' => $data['display_name'] ?? '',
				'email'        => $data['email'] ?? '',
				'phone'        => $data['phone'] ?? '',
				'status'       => $data['status'] ?? 'active',
				'wp_user_id'   => $wp_user_id,
				'extra_emails' => $data['extra_emails'] ?? '',
				'extra_phones' => $data['extra_phones'] ?? '',
				'title'        => $data['title'] ?? '',
				'bio'          => $data['bio'] ?? '',
				'services'     => $services,
			];

			$agent = new \OsAgentModel();
			$agent->set_data( $agent_params );

			// Save agent and services/locations.
			if ( $agent->save() && ( empty( $agent_params['services'] ) || $agent->save_locations_and_services( $agent_params['services'] ) ) ) {
				// Get agent services for response.
				$agent_services     = $agent->get_services();
				$formatted_services = [];
				if ( is_array( $agent_services ) ) {
					foreach ( $agent_services as $service ) {
						$formatted_services[] = [
							'id'   => $service->id,
							'name' => $service->name,
						];
					}
				}

				$result_data             = $agent->get_data_vars();
				$result_data['services'] = $formatted_services;

				return [
					'success' => true,
					'message' => __( 'Agent created successfully.', 'sureforms-pro' ),
					'data'    => $result_data,
				];
			}
				$errors    = $agent->get_error_messages();
				$error_msg = $errors[0] ?? 'Agent could not be created.';
				throw new \Exception( $error_msg );

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to create agent: %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( 'OsAgentModel' );
	}
}

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