	<?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	= gmdate("Y-m-d");
	
	$setting = mysqli_query($connect,"SELECT * FROM setting");
	$sett=mysqli_fetch_array($setting);

	$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 * FROM label WHERE user='$m[phone_number]' ORDER BY id_label DESC LIMIT 1");
	$dp=mysqli_fetch_array($querydp);
	
	$datatoko = mysqli_query($connect,"SELECT * FROM store WHERE id_store='$u[id_store]'");
	$dt=mysqli_fetch_array($datatoko);

	if ($jumlah > 0){
	
	$date		= gmdate("dis");
	
	$nama = $dt['name_store'];
	$arr = explode(' ', $nama);
	$singkatan = "";
	foreach($arr as $kata)
	{
	$singkatan .= substr($kata, 0, 1);
	}
	
		$kode= strtoupper($singkatan);

	
	$no_invoice	= "$kode-$dp[id_label]$date";
	
	
	
	for($x = 0; $x<count($decoded["product"]); $x++)
        {
	$id_barang			= $decoded["product"][$x]["id_product"];
	$jumlah_barang		= $decoded["product"][$x]["amount_product"];

	mysqli_query($connect,"INSERT INTO label(id_product, amount, id_store, user, no_invoice, date) 
                    VALUES('$id_barang', '$jumlah_barang', '$u[id_store]', '$m[phone_number]', '$no_invoice', '$tanggal')");
		}
	
	$responses = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Success'
	);
   	
	$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);	
	}
	?>