<?php
$start_date=$_POST['start_date'];
$end_date=$_POST['end_date'];
$data = array();
require 'config.php';
$sql= "select coalesce(sum(total),0) as total, coalesce(sum(male),0) as male, coalesce(sum(female),0) as female, coalesce(sum(minors),0) as minors, coalesce(sum(children_male),0) as children_male,coalesce(sum(children_female),0) as children_female,coalesce(sum(unspecified_male),0) as unspecified_male,coalesce(sum(unspecified_female),0) as unspecified_female,coalesce(sum(voluntaryreturns),0) as voluntaryreturns, coalesce(sum(involuntaryreturns),0) as involuntaryreturns from ksa where registration_date between :start_date and :end_date";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':start_date', $start_date, PDO::PARAM_STR);
$stmt->bindParam(':end_date', $end_date, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
if($total > 0){
while ($row = $stmt->fetchObject()) {
	$total=$row->total;
	$involuntaryreturns = $row->involuntaryreturns;
	$male=$row->male;
	$female=$row->female;
	$children_male=$row->children_male;
	$children_female=$row->children_female;
	$unspecified_male=$row->unspecified_male;
	$unspecified_female=$row->unspecified_female;
	if($involuntaryreturns!=0 && $total!=0)
	{
	$involuntarypercentage=round((($involuntaryreturns/$total)*100),0);
	}
	else
	{
		$involuntarypercentage=0;
	}
	$total_male=($male+$children_male+$unspecified_male);
	$total_female=($female+$children_female+$unspecified_female);
	
	if($total_male != 0 && $total_female != 0) {
	$malepercentage=round((($total_male/$total)*100),0);
	$femalepercentage=round((($total_female/$total)*100),0);
	}
	else
	{
		$malepercentage=0;
		$femalepercentage=0;
	}
	
	$data['status'] = 'ok';
	$data['result'] = array(
          "total" => $row->total,
		  "minors"=> $row->minors,
		  "voluntaryreturns"=> $row->voluntaryreturns,
	      "involuntaryreturns"=> $row->involuntaryreturns,
		  "involuntarypercentage" => $involuntarypercentage,
		  "malepercentage" =>$malepercentage,
		  "femalepercentage" =>$femalepercentage,
        );
}
}
else{
        $data['status'] = 'err';
        $data['result'] = '';
    }
	//returns data as JSON format
    echo json_encode($data);
 ?>