<?php

namespace Modules\Coupon\Models;

use CodeIgniter\Model;

class CouponModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'coupons';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'object';
	protected $useSoftDeletes       = true;
	protected $protectFields        = true;
	protected $allowedFields        = ['id','code','start_date','end_date','discount','discount_type','condition','coupon_for'];

	// 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 getCouponsWithDetails()
	{

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

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