<?php
date_default_timezone_set('Asia/Jakarta');
header('Content-Type: application/json'); 
include_once 'connection/connect.php';

// get the input
$nomor  = $_POST['nomor'];
$waktu  = date('Y-m-d H:i');
$status = "menunggu";


$tanggal = date('Y-m-d');
$kuota = mysqli_query($mysqli, "
   SELECT kuota FROM kuota WHERE DATE(tanggal)='$tanggal' LIMIT 1
");

if (mysqli_num_rows($kuota) == 0) {
 	$quota = 0;
	$is_quota = false;
} else {
 foreach ($kuota as $key => $value) {
   $quota = (int)$value['kuota'];
	$is_quota = true;
 }
}

if ($is_quota){
	if ($nomor > $quota) {
		$is_lanjut = false;
	}else{
		$is_lanjut = true;
	}
}else{
	$is_lanjut = true;
}





if ($is_lanjut) {
	$result = mysqli_query($mysqli, "
	   INSERT INTO antrian(nomor, waktu, status) values('$nomor', '$waktu', '$status')
	");
    $ch = curl_init('https://antrian.casie.cloud:3000');
	//$ch = curl_init('http://localhost:8080');
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

	$result_id = mysqli_insert_id($mysqli);
	$data = mysqli_query($mysqli, "
	   SELECT (SELECT COUNT(id) AS total_antrian FROM antrian where DATE(waktu)='$tanggal') AS total_antrian,(SELECT COUNT(id) AS total_menunggu FROM antrian where DATE(waktu)='$tanggal' AND status='menunggu') AS total_menunggu,(SELECT COUNT(id) AS total_selesai FROM antrian where DATE(waktu)='$tanggal' AND status='selesai') AS total_selesai");
	foreach ($data as $key => $value) {
		$total_antrian  = $value['total_antrian'];
		$total_menunggu = $value['total_menunggu'];
		$total_selesai  = $value['total_selesai'];
	}


	$jsonData = json_encode([
		'id'     => $result_id,
		'nomor'  => $nomor,
		'waktu'  => $waktu,
		'status' => $status,
		'is_update' => false,
		'total_antrian' => $total_antrian,
		'total_menunggu' => $total_menunggu,
		'total_selesai' => $total_selesai,
	]);
	$query = http_build_query(['data' => $jsonData]);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	curl_close($ch);



$base_url = "https://antrian.casie.cloud/assets/img_print/";
//$base_url = "http://192.168.1.3/web_antrian_dinsos/assets/img_print/";
$img_url  = $base_url.$nomor.".png";


	echo json_encode([
		'is_error'       => false,
		'pesan'          => "Berhasil mengambil antrian",
		'currect_number' => (int)$nomor,
		'number'         => $nomor+1,
		'is_kuota'		   => $is_quota,
		'kuota'          => (int)$quota,
		'tanggal'        => $tanggal,
		'next_number'    => $nomor+2,
		'image_url'		   => $img_url,
	]);
}else{
		echo json_encode([
		'is_error'       => true,
		'pesan'          => "Antrian sudah mencapai batas kuota harian, silakan kembali besok",
		'currect_number' => (int)$nomor,
		'number'         => $nomor+1,
		'is_kuota'		  => $is_quota,
		'kuota'          => (int)$quota,
		'tanggal'        => $tanggal,
		'next_number'    => $nomor+2,
		'image_url'		   => null,
	]);
}

