<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\Datasource\ResultSetInterface;

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

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

		$this->hasMany('CouponUsed', [
			'className' => 'App\Model\Table\CouponUsedTable',
			'foreignKey' => 'coupon_id',
		]);
	}

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

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

	public function isDuplicateRecord(int $restId, string $couponCode): int
	{
		return $this->find()
			->where(['coupon_code' => $couponCode])
			->count();
	}

	public function getAll(): array
	{
		return $this->find()
			->toArray();
	}

	public function getCouponDetails(string $couponCode): array
	{
		return $this->find()
			->where(['coupon_code' => $couponCode])
			->toArray();
	}

	public function isCouponCodeExist(string $couponCode): array
	{
		$record = $this->find()
			->where(['coupon_code' => $couponCode])
			->first();

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

	public function deleteCoupon(int $restaurantId, int $couponId): bool
	{
		return $this->deleteAll(['id' => $couponId]) > 0;
	}

	public function ifCouponUsed(int $userId, string $couponCode): int
	{
		return $this->find()
			->matching('CouponUsed', function (Query $q) use ($userId) {
				return $q->matching('Orders', function (Query $q2) use ($userId) {
					return $q2->where(['Orders.user_id' => $userId]);
				});
			})
			->where(['coupon_code' => $couponCode])
			->count();
	}
}
