<?php

namespace SugarCalendarBookings\Customers;

use SugarCalendarBookings\Appointments\AppointmentModel;
use SugarCalendarBookings\Support\Database\AbstractModel;
use SugarCalendarBookings\Support\Database\Relations\HasManyRelation;
use SugarCalendarBookings\Support\Database\Relations\BelongsToManyRelation;
use SugarCalendarBookings\Support\Tags\TagModel;

/**
 * Customer model.
 *
 * @since 1.0.0
 *
 * @property int                     $id
 * @property string                  $name
 * @property string                  $status
 * @property string                  $email
 * @property string                  $phone
 * @property string                  $notes
 * @property string                  $prev_status
 * @property string                  $created_at
 * @property string                  $updated_at
 * @property array<TagModel>         $tags
 * @property array<AppointmentModel> $appointments
 */
class CustomerModel extends AbstractModel {

	/**
	 * The database table name without prefix.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	protected static $table_name = 'customers';

	/**
	 * The model type identifier.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	protected static $type = 'customer';

	/**
	 * Column formats for the model.
	 *
	 * @since 1.0.0
	 *
	 * @var array<string, string>
	 */
	protected static $column_formats = [
		'id'         => '%d',
		'name'       => '%s',
		'status'     => '%s',
		'email'      => '%s',
		'phone'      => '%s',
		'created_at' => '%s',
		'updated_at' => '%s',
	];

	/**
	 * Meta keys for the model.
	 *
	 * @since 1.0.0
	 *
	 * @var array<string, mixed>
	 */
	protected static $meta_keys = [
		'notes',
		'prev_status',
		'_amelia_id',
	];

	/**
	 * The attributes and meta that should be cast.
	 *
	 * @since 1.0.0
	 *
	 * @var array<string, string>
	 */
	protected static $casts = [
		'id'         => 'integer',
		'created_at' => 'datetime',
		'updated_at' => 'datetime',
	];

	/**
	 * Column defaults for the model.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string, mixed>
	 */
	protected static function column_defaults() {

		return [
			'status' => 'enabled',
		];
	}

	/**
	 * Meta defaults for the model.
	 *
	 * @since 1.0.0
	 *
	 * @return array<string, mixed>
	 */
	protected static function meta_defaults() {

		return [
			'notes' => '',
		];
	}

	/**
	 * Get the appointments for the customer.
	 *
	 * @since 1.0.0
	 *
	 * @return HasManyRelation
	 */
	public function appointments() {

		return $this->has_many( AppointmentModel::class );
	}

	/**
	 * Get the tags relationship for the customer.
	 *
	 * @since 1.0.0
	 *
	 * @return BelongsToManyRelation
	 */
	public function tags() {

		return $this->belongs_to_many(
			TagModel::class,
			'tag_relationships',
			'object_id',
			'tag_id',
			[
				'object_type' => [
					'value'       => self::get_type(),
					'placeholder' => '%s',
				],
			]
		);
	}
}
