<?php

class Countries {

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
    }

    public function setdata(array $data) {
        $this->info = $data;
        return $this;
    }

    public function getCities($countryId) {
        //$this->db->query("SET NAMES utf8;");
        //$this->db->query("SET CHARACTER_SET utf8;");
        $data = [];
        $query = $this->db->query('
                                    SELECT
                                        b.ID,
                                        b.Name
                                    FROM
                                        tbl_all_countries a
                                    LEFT JOIN
                                    tbl_all_cities b
                                    ON
                                    a.Code = b.CountryCode
                                    WHERE a.Country_ID = "' . $countryId . '"
                                ');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function viewCountries() {
        $org_country = smc_session()['org_detail']['Organization_Country'];
        $data = array();
        $query = $this->db->query('SELECT * FROM tbl_all_countries order by ' . (empty($org_country) ? "" : " (`Country_ID` = {$org_country}) desc, ") . ' Country_Name asc');
        while ($row = $this->db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public function addCities() {

        $query = $this->db->query('INSERT INTO 
									  tbl_all_cities
							   (   
							   		Name, 
									CountryCode
							   )  
							        VALUES 
							   (
									"' . $this->info['City_Name'] . '",
									"' . $this->info['Country_ID'] . '"
							   )
						 ');

        if ($query)
            return true;
        return false;
    }

}
