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

	require_once("../connection.php");
	$content 	= trim(file_get_contents("php://input"));
	$decoded 	= json_decode($content, true);



	$tanggal = $decoded["date"];
	$jumlahnya = $decoded["amount"];
	$key = $decoded["key"];

	$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);

	$querydp = mysqli_query($connect,"SELECT id_spending_data FROM spending_data WHERE user='$m[phone_number]' ORDER BY id_spending_data DESC LIMIT 1");
	$dp=mysqli_fetch_array($querydp);

	if ($jumlah > 0){
	$date				= gmdate("dHi");
	$nama = $u['full_name'];
	$arr = explode(' ', $nama);
	$singkatan = "";
	foreach($arr as $kata)
	{
	$singkatan .= substr($kata, 0, 1);
	}
	
		$kode= strtoupper($singkatan);
	$no_invoice			="$kode-$dp[id_spending_data]$date";
	
	
	for($x = 0; $x<count($decoded["spending"]); $x++)
        {
	$nama_pengeluaran			= $decoded["spending"][$x]["name_spending"];
	$nominal					= $decoded["spending"][$x]["nominal"];

	mysqli_query($connect,"INSERT INTO spending(name_spending, user, no_invoice, nominal, date) 
                    VALUES('$nama_pengeluaran', '$m[phone_number]', '$no_invoice', '$nominal', '$tanggal')");
		} 
		
	mysqli_query($connect,"INSERT INTO spending_data(no_invoice,
								  date,
								  operator,
								  totalnominal,
								  id_store,
                                  user) 
                    VALUES('$no_invoice',
						   '$tanggal',
						   '$u[phone_number]',
						   '$jumlahnya',
						   '$u[id_store]',
                           '$m[phone_number]')");
						   
	$responses = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Success'
	);
   
	$responses["data"] = array();

  
	$responses["data"] = array(
	'invoice' => $no_invoice
	);
  
	array_push($responses["data"]);

	echo json_encode($responses);


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

    echo json_encode($json);	
	}
	?>