<?php
namespace App\Models;
use CodeIgniter\Model;

class PresellSection extends Model
{
    protected $table            = 'epos_cms';
    protected $primaryKey       = 'id';
    protected $useTimestamps    = false;

    public function getActiveSections()
    {
        $organization_id = session()->get('organization_id');
        $branch = session()->get('branch');
        $now = date('Y-m-d H:i:s');
        $builder = $this->where('type', 'presell_section')
            ->where('deleted', 0)
            ->where('active', 1)
            ->where('start_date <=', $now)
            ->where('end_date >=', $now);
        if (!empty($organization_id)) {
            $builder->groupStart()
                ->where('organization_id', $organization_id)
                ->orWhere('organization_id', null)
            ->groupEnd();
        }
        if (!empty($branch)) {
            $builder->groupStart()
                ->like('branches', (string)$branch)
                ->orWhere('branches', null)
                ->orWhere('branches', '')
            ->groupEnd();
        }
        $userPriceLists = session()->get('user_price_lists');
        if (!empty($userPriceLists)) {
            $builder->groupStart()
                ->where('price_list IS NULL', null, false)
                ->orWhere('price_list', '')
                ->orGroupStart();
            foreach ($userPriceLists as $pl) {
                $padded = str_pad($pl, 3, '0', STR_PAD_LEFT);
                $builder->orWhere("(FIND_IN_SET('$pl', price_list) > 0 OR FIND_IN_SET('$padded', price_list) > 0)", null, false);
            }
            $builder->groupEnd()
                ->groupEnd();
        }
        return $builder->orderBy('page_pos', 'ASC')->findAll();
    }

    public function getSectionByPromotionId($promotion_id)
    {
        return $this->where('type', 'presell_section')
            ->where('deleted', 0)
            ->where('active', 1)
            ->where('promotion_id', $promotion_id)
            ->first();
    }
}
