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

$date_kirim = $_POST['date_kirim'];
$detail_po = $_POST['detail_po'];
$product = $_POST['product'];
$detail_ekspedisi = $_POST['detail_ekspedisi'];
$qty = $_POST['qty'];
$dn = $_POST['dn'];

if ($date_kirim == '') {
    $data['error']['date_kirim'] = 'Tanggal kirim tidak boleh kosong';
}

function weekOfYear($date) {
    $weekOfYear = intval(date("W", $date));
    if (date('n', $date) == "1" && $weekOfYear > 51) {
        // It's the last week of the previos year.
        return 0;
    }
    else if (date('n', $date) == "12" && $weekOfYear == 1) {
        // It's the first week of the next year.
        return 53;
    }
    else {
        // It's a "normal" week.
        return $weekOfYear;
    }
}

$week = weekOfYear(strtotime($date_kirim));

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

$data1 = mysqli_query ($koneksi, " select 
										BalancePO
                                from 
                                detail_po
								where DetailPO_ID ='$detail_po'");
$row = mysqli_fetch_array ($data1);
if ($qty > $row['BalancePO']) {
    $data['error']['qty'] = 'Quantity Tidak Boleh Lebih Dari PO';
}
$kurangpo = $row['BalancePO'] - $qty;


if (empty($data['error'])) {
    
        $query1 = "UPDATE detail_po SET
                                        BalancePO = '$kurangpo'
                                        WHERE DetailPO_ID = '$detail_po'
                                        ";

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

		$query = "insert INTO deliverytbl SET
										Datekirim = '$date_kirim',
										Week = '$week',
										DetailPO_ID = '$detail_po',
										DetailEkspedisi_ID = '$detail_ekspedisi',
										QtyKirim = '$qty',
										NoDN = '$dn'
										";

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

echo json_encode($data);


?>

