	<?php
	/**
	* Created by PhpStorm.
	* User: ahmad
	* Date: 20/08/2019
	* Time: 11:48 AM
	*/

	require_once("../connection.php");
	
	$key=mysqli_real_escape_string($connect, $_GET['key']);
	
	$hariini	= gmdate("Y-m-d", time()+60*60*7);
	$getusers	= mysqli_query($connect,"SELECT * FROM users WHERE id_session='$key'");
	$u	   		= mysqli_fetch_array($getusers);
	$jumlah   	= mysqli_num_rows($getusers);
	
	
	$masterakun = mysqli_query($connect,"SELECT * FROM users WHERE phone_number='$u[master]'");
	$m=mysqli_fetch_array($masterakun);

	if ($jumlah > 0){

	$query = "SELECT * FROM purchasing_data WHERE user='$m[phone_number]' AND status='debt' ORDER BY due_date ASC";
	$hasil = mysqli_query($connect,$query);
	$jumlah_hutang = mysqli_num_rows($hasil);

	$datahutang = mysqli_query($connect,"SELECT SUM(totalorder) as total FROM purchasing_data WHERE user='$m[phone_number]' AND status='debt'");
	$n=mysqli_fetch_array($datahutang);

	$jatuhtempo 	= mysqli_query($connect,"SELECT * FROM purchasing_data WHERE user='$m[phone_number]' AND status='debt' AND due_date<='$hariini'");
	$jatuh_tempo	= mysqli_num_rows($jatuhtempo);
	if(mysqli_num_rows($hasil) > 0 ){
	$response = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Success'
	);
   
  $response["data"] = array();
   
  $datapiutang = array(
  'amount_debt' 	=> $jumlah_hutang,
  'nominal_debt' 	=> $n['total'],
  'due_date' 	=> $jatuh_tempo,
  'notyet_paidoff' 	=> $jumlah_hutang
  );
  
  $list = array();
  while($x = mysqli_fetch_array($hasil)){
	  
	$datasupplier = mysqli_query($connect,"SELECT name_supplier FROM supplier WHERE id_supplier='$x[id_supplier]'");
	$p=mysqli_fetch_array($datasupplier);

	  
    $h['id_supplier'] 	= $x["id_supplier"];
    $h['name_supplier'] 	= "$p[name_supplier] ($x[no_invoice])";
    $h['no_invoice'] 	= $x["no_invoice"];
    $h['date'] 		= $x["date"];
    $h['payment']	= $x["payment"];
    $h['note'] 	= $x["note"];
    $h['totalorder'] 	= $x["totalorder"];
	$h['totalpay'] 	= $x["totalpay"];
	$h['changepay'] 	= $x["changepay"];
    $h['status'] 		= $x["status"];
    $h['due_date'] 	= $x["due_date"];
    array_push($list, $h);
  }
  
  $response["data"] = array(
	'datapiutang' 	=> $datapiutang,
	'list' 			=> $list
  );
  
   array_push($response["data"]);
	
  echo json_encode($response);
	}else {
  $response = array(
    'status' 	=> 'true',
    'errCode' 	=> '02',
	'msg' 	=> 'no data'
   );
  echo json_encode($response);
	}


	}else{
	
	
	$json = array(
    'status' 	=> 'true',
    'errCode' 	=> '00',
	'msg' 		=> 'User Not Found'
	);

    echo json_encode($json);	
	}
	?>