<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use App\Utility\SchemaUtility;

/**
 * Banners Model
 *
 * @property \App\Model\Table\SectionBannerAssocTable&\Cake\ORM\Association\HasMany $SectionBannerAssoc
 *
 * @method \App\Model\Entity\Banner newEmptyEntity()
 * @method \App\Model\Entity\Banner newEntity(array $data, array $options = [])
 * @method \App\Model\Entity\Banner[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Banner get($primaryKey, $options = [])
 * @method \App\Model\Entity\Banner findOrCreate($search, ?callable $callback = null, $options = [])
 * @method \App\Model\Entity\Banner patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\Banner[] patchEntities(iterable $entities, array $data, array $options = [])
 * @method \App\Model\Entity\Banner|false save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Banner saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Banner[]|\Cake\Datasource\ResultSetInterface|false saveMany(iterable $entities, $options = [])
 * @method \App\Model\Entity\Banner[]|\Cake\Datasource\ResultSetInterface saveManyOrFail(iterable $entities, $options = [])
 * @method \App\Model\Entity\Banner[]|\Cake\Datasource\ResultSetInterface|false deleteMany(iterable $entities, $options = [])
 * @method \App\Model\Entity\Banner[]|\Cake\Datasource\ResultSetInterface deleteManyOrFail(iterable $entities, $options = [])
 */
class BannersTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('banners');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        $this->hasMany('SectionBannerAssoc', [
            'foreignKey' => 'banner_id',
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->scalar('title')
            ->maxLength('title', 255)
            ->allowEmptyString('title');

        $validator
            ->scalar('description')
            ->maxLength('description', 255)
            ->allowEmptyString('description');

        $validator
            ->scalar('image_path')
            ->maxLength('image_path', 255)
            ->allowEmptyFile('image_path');

        $validator
            ->integer('status')
            ->notEmptyString('status');

        $validator
            ->scalar('url_link')
            ->maxLength('url_link', 500)
            ->allowEmptyString('url_link');

        $validator
            ->integer('order_value')
            ->notEmptyString('order_value');

        $validator
            ->integer('section_id')
            ->notEmptyString('section_id');

        return $validator;
    }

    public function getHomeBanners()
    {
        $conditions = ['status' => 1];
    
        // Add section_id condition if the column exists
        if (SchemaUtility::hasColumn('Banners', 'section_id')) {
            $conditions['section_id'] = 1;
        }
    
        $query = $this->find()
            ->where($conditions);
    
        // Dynamic order clause based on schema
        if (SchemaUtility::hasColumn('Banners', 'order_value')) {
            $query->order(['Banners.order_value' => 'ASC']);
        } else {
            $query->order(['Banners.id' => 'ASC']);
        }
    
        return $query->all()->toArray();
    }
    

    public function getSectionBannerAssoc($menuDetails)
    {
        $query = $this->find('all', [
            'conditions' => [
                'status' => 6
            ]
        ])
            ->order(['rand()'])
            ->limit(1)
            ->matching('SectionBannerAssoc', function ($q) use ($menuDetails) {
                return $q->where(['SectionBannerAssoc.section_id' => $menuDetails->id]);
            });
            
        return $query->toArray();

    }

    public function getSectionTopBanners()
    {
        $conditions = [];

        if (SchemaUtility::hasColumn('Banners', 'section_id')) {
            $conditions['section_id'] = 2;
            $conditions['status'] = 1;
        } else {
            $conditions['status'] = 5;
        }

        $query = $this->find('all')
            ->where($conditions)
            ->order(['rand()'])
            ->limit(1)
            ->toArray();

        return $query;
    }
}
