<?php

namespace Hura8\Components\Province\Model;

use Hura8\Database\iConnectDB;
use Hura8\Interfaces\TableName;


class ProvinceModel
{

    /* @var  iConnectDB $db */
    protected  $db;

    protected $tb_province              = TableName::PROVINCE;
    protected $tb_province_district     = TableName::PROVINCE_DISTRICT;
    protected $tb_province_ward         = TableName::PROVINCE_WARD;

    public function __construct() {
        $this->db = get_db();
    }

    public function getProvinceInfo($id, $field="*") {
        if(!$id) return null;

        $query = $this->db->runQuery("SELECT ".$field." FROM `".$this->tb_province."` WHERE `id` = ? LIMIT 1 ", ['d'], [ $id ]);
        return $this->db->fetchAssoc($query);
    }

    public function getDistrictInfo($id, $field="*") {
        if(!$id) return null;

        $query = $this->db->runQuery("SELECT ".$field." FROM `".$this->tb_province_district."` WHERE `id` = ? LIMIT 1 ", ['d'], [ $id ]);
        return $this->db->fetchAssoc($query);
    }

    public function getWardInfo($id, $field="*") {
        if(!$id) return null;

        $query = $this->db->runQuery("SELECT ".$field." FROM `".$this->tb_province_ward."` WHERE `id` = ? LIMIT 1 ", ['d'], [ $id ]);
        return $this->db->fetchAssoc($query);
    }

    public function getProvinceList($field="*") {
        $query = $this->db->runQuery("SELECT ".$field." FROM `".$this->tb_province."` ORDER BY `id` ASC ");
        return $this->db->fetchAll($query);
    }

    public function getProvinceDistrictList($province_id, $field="*") {
        $query = $this->db->runQuery(
            "SELECT ".$field." FROM `".$this->tb_province_district."` WHERE `province_id` = ? ORDER BY `ordering` DESC ",
            ['d'], [ $province_id ]
        );

        return $this->db->fetchAll($query);
    }

    public function getAllDistrictList() {
        $query = $this->db->runQuery("SELECT * FROM `".$this->tb_province_district."` WHERE 1 ORDER BY id ASC ");
        return $this->db->fetchAll($query);
    }

    public function getDistrictWardList($district_id, $field="*") {
        $query = $this->db->runQuery(
            "SELECT ".$field." FROM `".$this->tb_province_ward."` WHERE `district_id` = ? ORDER BY `ordering` DESC ",
            ['d'],
            [ $district_id ]
        );

        return $this->db->fetchAll($query);
    }

}
