<?php
include "../koneksi.php";

$stpj_id = $_POST['stpj_id'];
$plan_id = $_POST['plan_id'];
$del_id = $_POST['del_id'];
$prod_id = $_POST['prod_id'];
$kode = $_POST['kode'];
$nolot = $_POST['nolot'];
$qty = $_POST['qty'];

if ($qty == '') {
    $data['error']['qty'] = 'Quantity PO Tidak Boleh Kosong';
}

if (empty($data['error'])) {
 
	$data1 = mysqli_query ($koneksi, " SELECT 
											STPJ_ID,
											PlanID,
											Del_ID,
											Kode,
											NoLot,
											Qty
										FROM stpj 
										WHERE Kode='$kode' AND NoLot='$nolot' AND PlanID='$plan_id' AND Del_ID IS NULL");

	$row = mysqli_fetch_array ($data1);
	
	$data2 = mysqli_query ($koneksi, " SELECT 
											Qty
										FROM stpj 
										WHERE Kode='$kode' AND NoLot='$nolot' AND PlanID='$plan_id' AND Del_ID='$del_id'");

	$row2 = mysqli_fetch_array ($data2);

	$data4 = mysqli_query ($koneksi, " SELECT 
											sum(Qty) as jml
										FROM stpj 
										WHERE Kode='$kode' AND NoLot='$nolot' AND PlanID='$plan_id' AND Del_ID!='$del_id'");

	$row4 = mysqli_fetch_array ($data4);

	$data3 = mysqli_query ($koneksi, " SELECT 
											STPJ_ID
										FROM stpj 
										WHERE Kode='$kode' AND NoLot='$nolot' AND PlanID='$plan_id' AND Del_ID IS NOT NULL");


	$cekrow = mysqli_num_rows($data3);
	
	if ($cekrow > 1 && !empty($row)) {
		$kurangi = 15-$row4['jml']-$qty;
	} else if ($cekrow > 1) {
		$kurangi = $row2['Qty']-$qty;
	} else {
		$kurangi = 15-$qty;
	}

	if($kurangi<=0 && !empty($row)) {
		$id = $row['STPJ_ID'];
		$query2 = "DELETE FROM stpj 
							WHERE STPJ_ID ='$id'
								";

		mysqli_query($koneksi, $query2)
		or die ("Gagal Perintah SQL".mysql_error());
	}

	if(empty($row)) {
		$query1 = "insert INTO stpj SET
										PlanID = '$plan_id',
										Kode = '$kode',
										NoLot = '$nolot',
										Qty = '$kurangi'
										";

		mysqli_query($koneksi, $query1)
		or die ("Gagal Perintah SQL".mysql_error());	
	} else {
		$id = $row['STPJ_ID'];
		$query3 = "UPDATE stpj SET
											Qty = '$kurangi'
											WHERE STPJ_ID = '$id'
											";

			mysqli_query($koneksi, $query3)
			or die ("Gagal Perintah SQL".mysql_error());
	}

	$query = "UPDATE stpj SET
									Qty = '$qty'
									WHERE STPJ_ID = '$stpj_id'
									";

	mysqli_query($koneksi, $query)
	or die ("Gagal Perintah SQL".mysql_error());
		
    $data['hasil'] = 'sukses';
    
} else {
    
    $data['hasil'] = 'gagal';
}

echo json_encode($data);
header('Location:plist.php?id='.$del_id.'&prod='.$prod_id);

?>

