<?php

namespace Modules\AdministrativeUnits\Models;

use codeIgniter\Model;

class SubcountyModel extends Model
{
    private $tbl_district = "districts";
    private $tbl_county = "counties";
    public function __construct()
    {
        parent::__construct();

        $this->table = "subcounties";
        $this->primaryKey = "subcounty_id";
       
    }
    
    protected function initialize()
    {
        

        $this->validationRules    = [
            'subcounty_name'     => 'required|alpha_numeric_space|min_length[3]',
            
        ];

        
        $this->allowedFields = ['subcounty_name','county_id'];
    }
	public function getAll()
    {
        $builder = $this->db->table($this->table);
        return $result = $builder->get()->getResult();
    }
	public function findByName($name,$countyId)
    {
        $builder = $this->db->table($this->table);
        $builder->select('*');
        $builder->where("{$this->table}.subcounty_name",$name);
		$builder->where("{$this->table}.county_id",$countyId);
        return $builder->get()->getRowArray();
    }

    /**public function findAll(int $limit = 0, int $offset = 0)
    {
        $builder = $this->db->table($this->table);
        $builder->select('*');
        if($limit > 0){
            $builder->limit($limit, $offset);
        }
        $builder->join($this->tbl_county, "{$this->tbl_county}.county_id = {$this->table}.county_id");
        $builder->join($this->tbl_district, "{$this->tbl_district}.district_id = {$this->tbl_county}.district_id");
        return $builder->get()->getResultArray();
    }**/

    public function findByDistrictId($id)
    {
        $builder = $this->db->table($this->table);
        $builder->select('*');
        $builder->where("{$this->tbl_district}.district_id",$id);
        $builder->join($this->tbl_county, "{$this->tbl_county}.county_id = {$this->table}.county_id");
        $builder->join($this->tbl_district, "{$this->tbl_district}.district_id = {$this->tbl_county}.district_id");
        return $builder->get()->getResultArray();
    }
    

    public function findByCountyId($id)
    {
        $builder = $this->db->table($this->table);
        $builder->select('*');
        $builder->where("{$this->tbl_county}.county_id",$id);
        $builder->join($this->tbl_county, "{$this->tbl_county}.county_id = {$this->table}.county_id");
        $builder->join($this->tbl_district, "{$this->tbl_district}.district_id = {$this->tbl_county}.district_id");
        return $builder->get()->getResultArray();
    }
}