<?php
include '../db_api.php';
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

$url="https://".$_SERVER['HTTP_HOST']."/api/user/profile";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "X-Api-Key: ".$_GET['X-Api-Key'],
   "X-Token: ".$_GET['X-Token'],
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);

$re= json_decode($resp, true);

$re= json_decode($resp, true);

if ($re['status']==1){

$total="a";
$vente="a";
$hay_kg="a";
$hay_chkara="a";
$nchira_kg="a";
$nchira_chkara="a";
$total3="a";
$sum_nbr_pieds="a";


// Perform query
mysqli_set_charset($conn,"utf8mb4");
	
$sql = "SELECT * FROM `agritun_transport`";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
$cout_trensporteur_total=0;

  while($row = $result->fetch_assoc()) {	
	$cout_trensporteur_total += intval($row["cout"]);
  }

} else {
  
}


$sql = "SELECT * FROM `agritun_masra_sortant`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

$masra_sor_cout=0;

  while($row = $result->fetch_assoc()) {
	$masra_sor_cout += intval($row['cout']);
  }
} else {
  
}

$sql = "SELECT * FROM `agritun_recolte`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

$cout3=0;
$hay_kg=0;$nchira_kg=0;$hay_chkara=0;$nchira_chkara=0;$total3;

  while($row = $result->fetch_assoc()) {
	  $total3 += $row['nbr_pieds']; 

	$cout3 += intval($row['cout']);
	
		if ($row['q_unite']=="كغ"){
		$hay_kg += $row['hay']; 
		$nchira_kg += $row['nchira']; 
	}
	if ($row['q_unite']=="شكارة"){
		$hay_chkara += $row['hay']; 
		$nchira_chkara += $row['nchira']; 
	}
	
  }
} else {
  
}

$sql = "SELECT * FROM `agritun_vente`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

$rev_tot=0;

  while($row = $result->fetch_assoc()) {
	$rev_tot += intval($row['montant']);
  }
} else {
  
}

$sql = "SELECT * FROM `parcels`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

$sum_nbr_pieds=0;

  while($row = $result->fetch_assoc()) {
	$sum_nbr_pieds += intval($row['nbr_pieds']);

  }
} else {
  
}

$conn -> close();






$total_total_cout=$cout_trensporteur_total+$masra_sor_cout+$cout3;

$rev=intval($rev_tot)-intval($total_total_cout);


echo '{"total":"'.$total_total_cout.'","vente":"'.$rev_tot.'","rev":"'.$rev.'","hay_kg":"'.$hay_kg.'","hay_chkara":"'.$hay_chkara.'","nchira_kg":"'.$nchira_kg.'","nchira_chkara":"'.$nchira_chkara.'","nbr_p_r":"'.$total3.'","nbr_p_t":"'.$sum_nbr_pieds.'"}';

}
?>