<?php

namespace SugarCalendarBookings\Customers\Admin;

use SugarCalendarBookings\Customers\CustomerModel;
use SugarCalendarBookings\Support\Data\Countries;
use SugarCalendarBookings\Support\Tags\TagModel;

/**
 * Service for adding new and editing customer form.
 *
 * @since 1.0.0
 */
class CustomerFormService {

	/**
	 * Get sanitization and validation rules.
	 *
	 * @since 1.0.0
	 *
	 * @param array $additional_rules Additional rules.
	 *
	 * @return array
	 */
	public function rules( $additional_rules = [] ) {

		return array_merge(
			[
				'name'   => 'required|string|max:255',
				'email'  => 'email|max:255',
				'phone'  => 'string|max:30',
				'notes'  => 'string|max:1000',
				'tags'   => 'array',
				'tags.*' => 'id',
			],
			$additional_rules
		);
	}

	/**
	 * Get form meta data.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	private function get_form_meta_data() {

		$default_country_code = Countries::get_by_locale( get_locale() );

		// TODO: Add limit and implement load more functionality in the select.
		$tags = TagModel::query()
			->where( 'object_type', '=', 'customer', '%s' )
			->order_by( 'name' )
			->get();

		$data = [
			'default_country_code' => $default_country_code,
			'tags'                 => array_map(
				fn( $tag ) => [
					'id'   => $tag->id,
					'name' => $tag->name,
				],
				$tags
			),
		];

		return $data;
	}

	/**
	 * Get data for customer creation form.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	public function get_create_form_data() {

		return [
			'meta' => $this->get_form_meta_data(),
		];
	}

	/**
	 * Get data for customer edit form.
	 *
	 * @since 1.0.0
	 *
	 * @param CustomerModel $customer Customer model instance.
	 *
	 * @return array
	 */
	public function get_edit_form_data( $customer ) {

		$tags = array_map( fn( $tag ) => $tag->id, $customer->tags()->select( [ 'id' ] )->get() );

		$data = [
			'id'    => $customer->id,
			'name'  => $customer->name,
			'email' => $customer->email,
			'phone' => $customer->phone,
			'notes' => $customer->notes,
			'tags'  => $tags,
		];

		return [
			'customer' => $data,
			'meta'     => $this->get_form_meta_data(),
		];
	}
}
