<?php

require_once "db_connect.php";
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$start = $_GET['start_date'];
$end = $_GET['end_date'];

$output = array();
$queryIs = "select rl.province_id, COALESCE(count(rl.province_id),0) as count,COUNT(CASE WHEN rd.violent_nonviolent ='violent' THEN 1 END) AS violent,COUNT(CASE WHEN rd.violent_nonviolent ='nonviolent' THEN 1 END) AS nonviolent from reports_details rd join reports_tags rt on rd.report_id = rt.report_id join reports r on r.id = rd.report_id join reports_locations rl on rl.report_id = r.id where rt.tag_id = 20 and r.eventdate between $start and $end";
if($_GET['type'] == 'lock'){

   $queryIs = $queryIs." and rd.secondary_cause_code='Solidarity'";
} else if($_GET['type'] == 'qua'){
   $queryIs =  $queryIs." and rd.secondary_cause_code='Dialogue'";
} else if($_GET['type'] == 'rel'){

   $queryIs =  $queryIs." and rd.secondary_cause_code='Safety'";
} else if($_GET['type'] == 'irr'){

   $queryIs =  $queryIs." and rd.secondary_cause_code='Association'";
} else if($_GET['type'] == 'pre'){

   $queryIs =  $queryIs." and rd.secondary_cause_code='Assembly'";
} else if($_GET['type'] == 'hea'){

   $queryIs =  $queryIs." and rd.secondary_cause_code='Expression'";
}
$queryIs = $queryIs." group by rl.province_id";
$query = mysqli_query($db,$queryIs);

$jsonObj = '{"Closed":"#e71d26", "Obstructed": "#f6ab17", "Open": "#009d5c", "Narrowed": "#acaf3d", "Repressed": "#e46c16"}';

$colorMap = json_decode($jsonObj);


$province_name = "";
$colorCode = "";
$myObj = new stdClass();
while($row = mysqli_fetch_assoc($query)){
  //$myObj->id = $row['id'];
  //$myObj->title = $row['title'];
  if($row['province_id'] == 1){
     $province_name = 'Province 1';
     $colorCode = 'Closed';
  } else if($row['province_id'] == 2){
     $province_name = 'Province 2';
     $colorCode = 'Repressed';
  } else if($row['province_id'] == 3){
  	 $province_name = 'Bagmati';
    $colorCode = 'Obstructed';
  } else if($row['province_id'] == 4){
  	  $province_name = 'Gandaki';
     $colorCode = 'Narrowed';
  } else if($row['province_id'] == 5){
  	 $province_name = 'Province 5';
    $colorCode = 'Open';
  } else if($row['province_id'] == 6){
  	 $province_name = 'Karnali';
    $colorCode = 'Repressed';
  } else if($row['province_id'] == 7){
  	 $province_name = 'Sudur Paschim';
    $colorCode = 'Closed';
  }
  if ($province_name != ""){
  $output[] = ['province' => (int)$row['province_id'], 'province_name' => $province_name, 'count' => (int)$row['count'], 'violent' => (int)$row['violent'], 'nonviolent'=> (int)$row['nonviolent'], 'color_code'=> $colorCode, 'color' => $colorMap->$colorCode, 'description' => "Some desc for" . $province_name ];
  }
}

$myObj->results = $output;
$myObj->type = $_GET['type'];
echo json_encode($myObj);

?>
