<?php

namespace App\Models;

use CodeIgniter\Model;

class DistrictModel extends Model
{
    protected $table = 'district';
    protected $primaryKey = 'district_id';
    protected $allowedFields = ['district_name', 'district_key', 'district_status', 'article_like'];

    public function addParent($data)
    {
        return $this->insert($data) ? $this->getInsertID() : false;
    }

    public function getAllParent()
    {
        return $this->orderBy('district_id', 'DESC')->findAll();
    }

    public function getAllParentForSite()
    {
        return $this->where('district_status', 1)
                    ->orderBy('district_id', 'DESC')
                    ->findAll();
    }

    public function getAllTopParentForSite()
    {
        $districts = $this->where('district_status', 1)->findAll();
        return array_filter($districts, function($value) {
            return !empty($value['article_like']);
        });
    }

    public function getParentByKey($param)
    {
        return $this->where('district_key', $param)
                    ->orderBy('district_id', 'ASC')
                    ->first();
    }

    public function getParentByTitle($param)
    {
        return $this->like('district_name', $param)->first();
    }

    public function getAllParentByTitle($param)
    {
        return $this->like('district_name', $param)->findAll();
    }

    public function updateParentByKey($param, $data)
    {
        return $this->where('district_key', $param)->set($data)->update();
    }

    public function deleteParentByKey($param)
    {
        return $this->where('district_key', $param)->delete();
    }
}