<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
  require_once "connection/connect.php";
  if (isset($_POST['id'])) {
    $id = mysqli_real_escape_string($mysqli, $_POST['id']);
    $status = "selesai";
    $updated_date = gmdate("Y-m-d H:i:s", time() + 60 * 60 * 7);

    $update = mysqli_query($mysqli, "UPDATE antrian
                                     SET status='$status'
                                     WHERE id='$id'")
                                     or die('Ada kesalahan pada query update : ' . mysqli_error($mysqli));
    if ($_POST['index_row'] >= 2) {
      $id_antrian = $id-2;
      mysqli_query($mysqli, "UPDATE antrian
                                     SET is_close=true
                                     WHERE id='$id_antrian'")
                                     or die('Ada kesalahan pada query update : ' . mysqli_error($mysqli));
    }

    // Send the HTTP request to the websockets server (it runs both  HTTP and Websockets)
    // (change the URL accordingly)
    $ch = curl_init('http://localhost:8080');
    // It's POST
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

    $data = mysqli_query($mysqli, "SELECT * FROM antrian
                                     WHERE id='$id'");

    $tanggal = date('Y-m-d');
    $data_antrian = 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_antrian as $key => $value) {
      $total_antrian  = $value['total_antrian'];
      $total_menunggu = $value['total_menunggu'];
      $total_selesai  = $value['total_selesai'];
    }

    foreach ($data as $key => $value) {
        $data_id     = $value['id'];
        $data_nomor  = $value['nomor'];
        $data_waktu  = $value['waktu'];
        $data_status = $value['status'];
    }
    // we send JSON encoded data to the client
    $jsonData = json_encode([
      'id'     => $data_id,
      'nomor'  => $data_nomor,
      'waktu'  => $data_waktu,
      'status' => $data_status,
      'is_update' => true,
      'total_antrian' => $total_antrian,
      'total_menunggu' => $total_menunggu,
      'total_selesai' => $total_selesai,
    ]);
    $query = http_build_query(['data' => $jsonData]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
    // Just return the transfer
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // execute
    $response = curl_exec($ch);
     // close
    curl_close($ch);


    // Now real time notification should be sent to all the users



  }
}