<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

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

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

		$this->belongsTo('Videos', [
			'foreignKey' => 'video_id',
		]);

		$this->belongsTo('Products', [
			'foreignKey' => 'product_id',
		]);

		// If you had a User association in 'contain', define it here as well:
		$this->belongsTo('Users', [
			'foreignKey' => 'user_id',
			'className' => 'Users', // adjust if actual class is different
			'joinType' => 'LEFT'
		]);
	}

	// Formerly 'custom_fields' — now use it directly in query with select()
	public array $customFields = [
		'Videos.id',
		'Videos.user_id',
		'Videos.description',
		'Videos.video',
		'Videos.thum',
		'Videos.thum_small',
		'Videos.gif',
		'Videos.view',
		'Videos.sound_id',
		'Videos.privacy_type',
		'Videos.allow_comments',
		'Videos.allow_duet',
		'Videos.duration',
		'Videos.promote',
		'Videos.pin_comment_id',
		'Videos.pin',
		'Videos.location_string',
		'Videos.location_id',
		'Videos.lat',
		'Videos.long',
		'Videos.width',
		'Videos.height',
		'Videos.user_thumbnail',
		'Videos.default_thumbnail',
		'VideoProducts.*'
	];

	public function getDetails(int $id): array
	{
		return $this->find()
			->where(['VideoProducts.id' => $id])
			->enableHydration(false)
			->first() ?? [];
	}

	public function getAllCron(): array
	{
		return $this->find()
			->where(['VideoProducts.updated_at <' => date('Y-m-d')])
			->order(['VideoProducts.id' => 'DESC'])
			->enableHydration(false)
			->all()
			->toList();
	}

	public function ifExist(array $data): array
	{
		return $this->find()
			->where([
				'VideoProducts.video_id' => $data['video_id'],
				'VideoProducts.product_id' => $data['product_id']
			])
			->enableHydration(false)
			->first() ?? [];
	}

	public function getDetailsAgainstVideo(int $video_id): array
	{
		return $this->find()
			->where(['VideoProducts.video_id' => $video_id])
			->contain(['Users']) // You must define belongsTo('Users') in initialize()
			->enableHydration(false)
			->first() ?? [];
	}

	public function getOnlyDetailsAgainstVideo(int $video_id): array
	{
		return $this->find()
			->where(['VideoProducts.video_id' => $video_id])
			->enableHydration(false)
			->first() ?? [];
	}

	public function getDetailsWithUser(int $id): array
	{
		return $this->find()
			->where(['Products.id' => $id])
			->contain(['Users'])
			->enableHydration(false)
			->first() ?? [];
	}

	public function getAll(): array
	{
		return $this->find()
			->enableHydration(false)
			->all()
			->toList();
	}

	public function deleteDataAgainstVideo(int $video_id): bool
	{
		return $this->deleteAll(['VideoProducts.video_id' => $video_id]) > 0;
	}
}
