<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Event\EventInterface;
use ArrayObject;

class DeliveryAddressesTable extends Table
{
	public function initialize(array $config): void
	{
		parent::initialize($config);

		$this->setTable('delivery_address');
		$this->setPrimaryKey('id');

		$this->belongsTo('Countries', [
			'foreignKey' => 'country_id',
			'joinType' => 'LEFT'
		]);
	}

	public function getDetails(int $id): array
	{
		$record = $this->find()
			->where(['id' => $id])
			->first();

		return $record ? $record->toArray() : [];
	}

	public function getUserDeliveryAddresses(int $user_id): array
	{
		return $this->find()
			->where(['user_id' => $user_id])
			->contain(['Countries.ShippingRates'])
			->orderDesc('id')
			->all()
			->toList();
	}

	public function checkDuplicity(int $user_id, int $place_id, int $id): int
	{
		return $this->find()
			->where([
				'user_id' => $user_id,
				'place_id' => $place_id,
				'id !=' => $id
			])
			->count();
	}

	public function getUserDefaultDeliveryAddresses(int $user_id): array
	{
		$record = $this->find()
			->where([
				'user_id' => $user_id,
				'default' => 1
			])
			->contain(['Countries.ShippingRates'])
			->orderDesc('id')
			->first();

		return $record ? $record->toArray() : [];
	}

	public function getAddressDetail(int $address_id): array
	{
		return $this->find()
			->where(['id' => $address_id])
			->all()
			->toList();
	}

	public function isDuplicateRecord(
		int $user_id,
		string $street,
		string $city,
		string $apartment,
		string $state,
		string $country
	): int {
		return $this->find()
			->where([
				'user_id' => $user_id,
				'street' => $street,
				'city' => $city,
				'apartment' => $apartment,
				'state' => $state,
				'country' => $country
			])
			->count();
	}

	public function beforeSave(EventInterface $event, $entity, ArrayObject $options): void
	{
		foreach (['street', 'city', 'apartment', 'state', 'country'] as $field) {
			if (!empty($entity->$field)) {
				$entity->$field = ucwords(strtolower($entity->$field));
			}
		}

		if (!empty($entity->street)) {
			$entity->name = ucwords(strtolower($entity->street));
		}
	}
}
