<?php

namespace Modules\Offer\Models;

use CodeIgniter\Model;

class OfferModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'offers';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'object';
	protected $useSoftDeletes       = true;
	protected $protectFields        = true;
	protected $allowedFields        = ['id','code','offer_title','offer_description','start_date','end_date','booking_start_date','booking_end_date','travel_start_date','travel_end_date','min_passengers','discount','discount_type','discount_cap','min_discount','max_discount','condition','offer_for','offer_image','seat_class','trip_category'];

	// Dates
	protected $useTimestamps        = true;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = true;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];


	public function getOffersWithDetails()
	{

		$roleId     = session()->get("role_id");
        $companyId  = session()->get("company_id");
        $user_id    = session()->get("user_id");

        if($roleId == 1){
			return $this->select('
					offers.*,
					GROUP_CONCAT(DISTINCT companies.name SEPARATOR ", ") AS company_names
				')
				->join('offer_details', 'offer_details.offer_id = offers.id', 'left')
				->join('companies', 'FIND_IN_SET(companies.id, offer_details.company_id)', 'left')
				->groupBy('offers.id')
				->asObject()
				->findAll();
		}else{
			return $this->select('
					offers.*,
					GROUP_CONCAT(DISTINCT companies.name SEPARATOR ", ") AS company_names
				')
				->join('offer_details', 'offer_details.offer_id = offers.id', 'left')
				->join('companies', 'FIND_IN_SET(companies.id, offer_details.company_id)', 'left')
				->where('companies.id',$companyId)
				->groupBy('offers.id')
				->asObject()
				->findAll();
		}
	}
}
