<?php

/**
 * @author : Kadian Salmon
 * Purpose : This contains classes for php backend mannipulation
 *
 * @param Database : For setting up and maintaining Database Connection
 * @param DatabaseResult : Is a return type for Database methods : not used directly
 * @param HostInfo : Holds information about the current client
 *
 *
 */

/**
* @subpackage : Database
*   Date : Sep 18, 2019
*   @uses : Maintains communication to a defined mysql database
*   @param DB_USERNAME : This is the USERNAME for the database
*   @param DB_PASSWORD : This is the PASSWORD for the database
*   @param DB_NAME : This is the NAME for the active database
*   @param DB_HOST : This is the HOST_NAME for the DB server. If None = "localhost"
*
*   @method0 connect_error : returns any errors encountered during the connection of the database
*   @method0 query($) : processes the passed string sql query and returns a : DatabaseResult Object
*   @method0 getUsername : returns database USERNAME
*   @method0 getPassword : returns database PASSWORD
*   @method0 getDatabase : returns database NAME
*   @method0 getHost : returns database HOST_NAME
*   @method0 getConnector : returns the LINK to the database
*   @method0 @setters for above
*
*   @example-new_instance_1 : $mydb = new Database("minuteman","mintemanid24","secret_info","29.panel.db.com");
*   @example-new_instance_2 : $mydb = new Database("minuteman","mintemanid24","secret_info");
*
*   @example-select_query_db : $result_s = $mydb->query("SELECT * FROM my_table WHERE u_id = 'jhfdghvdsgdsv' "); : DatabaseResult
*   @example-check_result : $result_s->is_row_found() : Boolean
*   @example-view_result_1 : $result_s->fetch_array() : Associated array
*   @example-view_result_2 : while($row = $result_s->fetch_array()) : Associated array
*
*   @example-update_query_db : $result_u = $mydb->query("UPDATE my_table SET age = 22 WHERE u_id = 'jhfdghvdsgdsv' "); : DatabaseResult
*   @example-check_result : $result_u->is_row_affected() : Boolean
*/
class Database {

    private $username;
    private $password;
    private $database;
    private $host;
    private $connector;

    public function __construct($username = "", $password = "", $database = "", $host = "") {
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;

        if ($this->host == "") {
            $this->host = "localhost";
        }

        $this->connector = mysqli_connect($this->host, $this->username, $this->password, $this->database);


    }

    public function connect_error() {

        return mysqli_connect_errno();
    }


    public function query($sql) {

        /*
          mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);//must be called in order to enforce try error block
            try {
            $query_result = mysqli_query($this->connector, $sql);

        }
        catch (Exception $exc) {
            echo 'dsjbhubwsjb';
            return null;
        }*/
        $query_result = mysqli_query($this->connector, $sql);

        if($query_result != false){
            return new DatabaseResult($query_result,$this->connector);
        }

        return null;//false is returned on error not empty result

    }

    public function getUsername() {
        return $this->username;
    }

    public function getPassword() {
        return $this->password;
    }

    public function getDatabase() {
        return $this->database;
    }

    public function getHost() {
        return $this->host;
    }

    public function getConnector() {
        return $this->connector;
    }

    public function setUsername($username) {
        $this->username = $username;
    }

    public function setPassword($password) {
        $this->password = $password;
    }

    public function setDatabase($database) {
        $this->database = $database;
    }

    public function setHost($host) {
        $this->host = $host;
    }

    public function setConnector($connector) {
        $this->connector = $connector;
    }

}

/**
*  @subpackage @internal : This is the USERNAME for the database
*   Date : Sep 18, 2019
*   @param DB_PASSWORD : This is the PASSWORD for the database
*   @param DB_NAME : This is the NAME for the active database
*   @param DB_HOST : This is the HOST_NAME for the DB server. If None = "localhost"
*
*   @method0 fetch_array : return results in the form of an associated array
*   @method0 rows_count : returns a count after a select query
*   @method0 rows_affected : returns a count after an update query
*   @method0 is_row_affected : returns true if a row was affected after an update query
*   @method0 is_row_found : returns true if 1 or more records were found after a select query
*   @method0 insert_id : returns the last inserted id if success or false if failed
*   @method0 get_result : returns the raw db stream to be used in a mysql func => mysqli_affected_rows(result_here)
*   @method0 set_result($) : sets the raw db stream
*
*/
class DatabaseResult {

    private $query_result;
    private $connector;

    public function __construct($query_result,$conn) {
        $this->query_result = $query_result;

        $this->connector = $conn;
    }

    public function fetch_array() {
        return mysqli_fetch_array($this->query_result);
    }
    public function rows_count() {
        //this can be use after a select query
        return mysqli_num_rows($this->query_result);//number of rows returned
    }
    public function rows_affected() {
        //this can be used after an update query
        return mysqli_affected_rows($this->connector);//number of rows changed
    }
    public function is_row_affected() {
        //this can be used after an update query
        if(mysqli_affected_rows($this->connector) > 0){
            //yes indeed ; rows were affected

            return true;
        }

        return false;
    }
    public function is_row_found() {
        //this can be use after a select query
        if(mysqli_num_rows($this->query_result) > 0){
            //yes indeed ; rows were affected

            return true;
        }

        return false;
    }
    public function insert_id() {
        //get the last inserted id of the table has auto increment

        $last_id = mysqli_insert_id($this->connector);
        //this can be use after a insert query
        if($last_id != false){
            //yes indeed ; rows were affected

            return $last_id;
        }

        return false;
    }

    function get_result() {
        return $this->query_result;
    }

    function set_result($query_result) {
        $this->query_result = $query_result;
    }

}

/**
* @subpackage : HostInfoLocalization
*   Date : Oct 25, 2019
*   @uses : This packages information related to the connected Host based on the clients ip address
*   @uses : It relies on the localization api data
*
*   @param DB_HANDLE : This is a handle to a Database instance
*   @return ip_address|country_name|country_code|area_code|currency
*
*
*   @method0 getIp_address : returns the ip address of this client => x.x.x.x
*   @method0 getCountry_name : returns the country name for this client => jamaica
*   @method0 getCountry_code : returns the 2 character country code for client => JM
*   @method0 getArea_code : returns the area code => 1876
*   @method0 getCurrency : returns the currency for that country => JMD
*   @method0 getDb : returns the handle for the database that contains the IP-RANGE => COUNTRY map
*   @method @internal set_host_data() : set host properties based on host data
*   @method @internal get_ip() : returns the client ip to be used by internal methods
*   @method @internal get_data_from_ip($) : this logic pulls db data based on the client's ip address
*   @method @internal @return get_data_from_ip($) : {country_name|country_code|area_code|currency}
*
*   @NOTE get_data_from_ip - [its currently rigged]
 *
 * @how_to_use
 * $client = new HostInfoLocalization($db);
 * $ip = $_REQUEST["ip"];
 * if($ip != "my_ip"){
 * $client->setIp_address($ip);
 * }
*/

class HostInfoLocalization{
    private $ip_address = null;//x.x.x.x
    private $country_name = null;//jamaica
    private $country_code = null;//JM
    private $area_code = null;//1876
    private $currency = null;//JMD
    private $db = null;//db connector

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

        $this->set_host_data();//assign data to variables
    }


    public function getIp_address() {
        return $this->ip_address;
    }

    public function getCountry_name() {
        return $this->country_name;
    }

    public function getCountry_code() {
        return $this->country_code;
    }

    public function getArea_code() {
        return $this->area_code;
    }

    public function getCurrency() {
        return $this->currency;
    }

    public function getDb() {
        return $this->db;
    }

    public function setIp_address($ip_address) {
        $this->ip_address = $ip_address;
        $this->set_host_data();
    }
    public function default_ip() {
        $this->ip_address = $this->get_ip();
        $this->set_host_data();
    }

    public function setCountry_name($country_name) {
        $this->country_name = $country_name;
    }

    public function setCountry_code($country_code) {
        $this->country_code = $country_code;
    }

    public function setArea_code($area_code) {
        $this->area_code = $area_code;
    }

    public function setCurrency($currency) {
        $this->currency = $currency;
    }

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

    private function set_host_data(){
        if($this->ip_address == null){
            $this->ip_address = $this->get_ip();
        }

        $host_detail = $this->get_data_from_ip($this->ip_address);

        $this->country_name = $host_detail["country_name"];
        $this->country_code = $host_detail["country_code"];
    }

    private function get_ip(){
        if (!empty($_SERVER['HTTP_CLIENT_IP'])){//check ip from share internet
          $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else{
          $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    private function get_data_from_ip($ip){
        //use default
        //$data["country_name"] = "Jamaica";
        //$data["country_code"] = "JM";

        $data["country_name"] = null;
        $data["country_code"] = null;

        $proper_address = ip2long($ip);
        $sql = "select * from ip_country_wide_list where ip_from <= $proper_address and ip_to >= $proper_address";

        $result = $this->db->query($sql);
        if($row = $result->fetch_array()){
            $name = $row["country_name"] == "-" ? null : $row["country_name"];
            $code = $row["country_code"] == "-" ? null : $row["country_code"];

            $data["country_name"] = $name;
            $data["country_code"] = $code;
        }

        return $data;

    }

}















//
