<?php

namespace SugarCalendarBookings\Locations\Admin;

use SugarCalendarBookings\Locations\LocationModel;
use SugarCalendarBookings\Support\Data\Countries;

/**
 * Service for adding new and editing location form.
 *
 * @since 1.0.0
 */
class LocationFormService {

	/**
	 * 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',
				'address'      => 'required|string|max:255',
				'address2'     => 'string|max:255',
				'city'         => 'required|string|max:100',
				'region'       => 'required|string|max:100',
				'postal_code'  => 'required|string|max:20',
				'country_code' => 'required|string|max:2',
				'phone'        => 'string|max:30',
				'website'      => 'string|max:255',
			],
			$additional_rules
		);
	}

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

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

		$data = [
			'countries'            => array_map(
				fn( $code, $name ) => [
					'code' => $code,
					'name' => $name,
				],
				array_keys( $countries ),
				$countries
			),
			'default_country_code' => $default_country_code,
		];

		return $data;
	}

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

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

	/**
	 * Get data for location edit form.
	 *
	 * @since 1.0.0
	 *
	 * @param LocationModel $location Location model instance.
	 *
	 * @return array
	 */
	public function get_edit_form_data( $location ) {

		$data = [
			'id'           => $location->id,
			'name'         => $location->name,
			'address'      => $location->address,
			'address2'     => $location->address2,
			'city'         => $location->city,
			'region'       => $location->region,
			'postal_code'  => $location->postal_code,
			'country_code' => $location->country_code,
			'phone'        => $location->phone,
			'website'      => $location->website,
		];

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