	<?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");
	//$time   	= gmdate("h:i");

	$timestamp = new DateTime(null, new DateTImeZone('Asia/Kolkata'));
	$tanggal = $timestamp->format('Y-m-d');
	$time = $timestamp->format('H:i');
	
	$setting = mysqli_query($connect,"SELECT * FROM setting");
	$sett=mysqli_fetch_array($setting);

	$id_pelanggans						= $decoded["id_customer"];
	$jatuh_tempo						= $decoded["due_date"];
	$jumlah_pembayaran					= $decoded["payment_amount"];
	$total_order						= $decoded["total_order"];
	$totalprice						    = $decoded["total_order"];
	$key								= $decoded["key"];
	$tipe_pembayaran					= $decoded["payment_type"];
	$service_charge						= $decoded["service_charge"];
	$pajak								= $decoded["tax"];
	$id_diskon							= $decoded["id_discount"];
	$card								= $decoded["card"];
	$latitude							= $decoded["latitude"];
	$longitude							= $decoded["longitude"];
	$keterangan							= $decoded["note"];
	$discounts							= $decoded["discount"];

	$getusers	= mysqli_query($connect,"SELECT * FROM users WHERE id_session='$key'");
	$u	   		= mysqli_fetch_array($getusers);
	$jumlah   	= mysqli_num_rows($getusers);

	$cust = mysqli_query($connect,"SELECT * FROM customer WHERE user='$u[master]' AND name_customer='CASH'");
	$c=mysqli_fetch_array($cust);

	if($id_pelanggans==""){
  	$id_pelanggan = $c['id_customer'];
	}else{
    $id_pelanggan = $id_pelanggans;
    }
	
	
	$masterakun = mysqli_query($connect,"SELECT * FROM users WHERE phone_number='$u[master]'");
	$m=mysqli_fetch_array($masterakun);

	$sumary = mysqli_query($connect,"SELECT * FROM sumary WHERE cashier_id='$u[phone_number]' AND create_at='$tanggal'");
	$ambil=mysqli_num_rows($sumary);
	if ($ambil > 0){
	}else{
		mysqli_query($connect,"INSERT INTO sumary(cashier_id,
								  create_at,
								  id_store,
								  user) 
                    VALUES('$u[phone_number]',
						   '$tanggal',
						   '$u[id_store]',
						   '$m[phone_number]')");
	}

	$querydp = mysqli_query($connect,"SELECT serial_number FROM salesreturn_data WHERE user='$m[phone_number]' ORDER BY serial_number 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);

	$datadiskon = mysqli_query($connect,"SELECT * FROM discount WHERE id_discount='$id_diskon'");
	$d=mysqli_fetch_array($datadiskon);
	
	if($d['type']=='prosentase'){
		$diskons=$total_order*$d['nominal']/100;
		$diskon=$diskons;
	}else{
		$diskon=$d['nominal'];
	}
	
	$hargasetelahdiskon=$total_order-$discounts;
	
    $nominalscc=$hargasetelahdiskon*$dt['service_charge']/100;
    $nominalsc=$nominalscc;
	$total_service_charge=$hargasetelahdiskon+$nominalsc;
	
	$nominalpajaks=$total_service_charge*$dt['tax']/100;
	$nominalpajak=$nominalpajaks;
	$total_bayar=$total_service_charge+$nominalpajak;

	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_sales_data]$date";
	

	$nourut = $dp['serial_number']+1; // kode_barang dengan angka terbesar
	$serial_number = $nourut; // mencetak no urut dengan 4 angka, lihat bedanya jika hanya menggunakan echo $nourut;
	$sn = sprintf("%04s", $nourut) ; // mencetak no urut dengan 4 angka, lihat bedanya jika hanya menggunakan echo $nourut;
	
	$no_invoice	= "$kode-$sn";
	
	if($tipe_pembayaran==1){
		$pembayaran="cash";
		$status="paid off";
		$dibayar=$jumlah_pembayaran;
		
		$kembalian	= $dibayar-$total_bayar;
      
      
      $balances	= $total_bayar-$dibayar;
      
      
      $customerok = mysqli_query($connect,"SELECT * FROM customer WHERE id_customer = '$id_pelanggan'");
		$cs=mysqli_fetch_array($customerok);
		
		$balance= $cs['balance']+$balances;
		
		mysqli_query($connect,"UPDATE customer SET balance = '$balance'
                             WHERE id_customer = '$id_pelanggan'");

	
	
	for($x = 0; $x<count($decoded["product"]); $x++)
        {
	$id_barang			= $decoded["product"][$x]["id_product"];
	$jumlah_barang		= $decoded["product"][$x]["amount_product"];
	$price			= $decoded["product"][$x]["new_price"];
	$catatan			= $decoded["product"][$x]["notes"];



	$barang = mysqli_query($connect,"SELECT * FROM product WHERE id_product='$id_barang'");
	$b=mysqli_fetch_array($barang);
      
    $datastok = mysqli_query($connect,"SELECT * FROM stock WHERE id_product='$id_barang' AND id_store='$u[id_store]'");
	$s=mysqli_fetch_array($datastok);
	
	$totalharga	=$price*$jumlah_barang;
    $tax= $s['taxvalue']*$jumlah_barang;
	$stok		=$b['stock']+$jumlah_barang;
	
    $stoknya		=$s['stock']+$jumlah_barang;
    if($b['tax']=="0"){
     $gst		= "0.00";
    }else{
     $gst		= $tax;
    }

	mysqli_query($connect,"INSERT INTO salesreturn(id_product, amount, id_customer, id_store, user, no_invoice, status, price, totalprice, date, note, rest_stock, gst) 
                    VALUES('$id_barang', '$jumlah_barang', '$id_pelanggan', '$u[id_store]', '$m[phone_number]', '$keterangan', '$status', '$price', '$totalharga', '$tanggal', '$catatan', '$stoknya', '$gst')");
  
			mysqli_query($connect,"UPDATE product SET stock   = '$stok' WHERE id_product  = '$id_barang'");
			if($b['have_stock']=='1'){
			
			mysqli_query($connect,"UPDATE stock SET stock   = '$stoknya' WHERE id_product  = '$id_barang' AND id_store='$u[id_store]'");
	mysqli_query($connect,"INSERT INTO history_stock(id_product,
								  id_store,
								  stock,
								  detail,
								  status,
								  date,
                                  user) 
					VALUES('$id_barang',
						   '$u[id_store]',
						   '$jumlah_barang',
						   'Sales Return  $no_invoice',
						   '0',
						   '$tanggal',
                           '$m[phone_number]')");
			}
		}
		
	

	mysqli_query($connect,"INSERT INTO salesreturn_data(id_customer,
								  no_invoice,
								  serial_number,
								  date,
                                  hour,
								  id_store,
								  payment,
								  totalorder,
								  totalpay,
								  totalprice,
								  changepay,
								  status,
								  due_date,
								  operator,
								  tax,
								  discount,
								  service_charge,
								  location,
								  shift,
                                  user) 
                    VALUES('$id_pelanggan',
						   '$keterangan',
						   '$serial_number',
						   '$tanggal',
                           '$time',
						   '$u[id_store]',
						   '$pembayaran',
						   '$total_bayar',
						   '$dibayar',
						   '$totalprice',
						   '$kembalian',
						   '$status',
						   '$jatuh_tempo',
						   '$u[phone_number]',
						   '$nominalpajak',
						   '$discounts',
						   '$nominalsc',
						   '$latitude, $longitude',
						   '$u[shift]',
                           '$m[phone_number]')");
						   
	

	}
	

	
  

	$responses = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Success'
	);
   
	$responses["data"] = array();

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

	echo json_encode($responses);


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

    echo json_encode($json);	
	}
	?>