<?php if(empty($connection) AND !isset($_COOKIE['siswa'])){
    header('location:../404');
}else{
header("Content-Type: application/json");
require_once'../../../sw-library/sw-config.php';
require_once'../../../sw-library/sw-function.php';
require_once'../../oauth/user.php';


function faceDistance($d1, $d2){
  $sum = 0;
  for($i=0;$i<count($d1);$i++){
    $sum += pow($d1[$i] - $d2[$i], 2);
  }
  return sqrt($sum);
}

switch (@$_GET['action']){
case'add':
$data = json_decode(file_get_contents("php://input"), true);

  if(!$data || !isset($data['descriptor'])){
    echo json_encode([
      "status"=>false,
      "msg"=>"Data tidak valid"
    ]);
    exit;
  }
  $descriptor = json_encode($data['descriptor']);
  $newDesc = $data['descriptor'];

  $data = $connection->query("SELECT * FROM user WHERE active='Y' AND user_id='$user_id'");
  while($row = $data->fetch_assoc()){
    if(empty($row['descriptor'])) continue;
    $old = json_decode($row['descriptor'], true);
    if(!is_array($old)) continue;
    $dist = faceDistance($old, $newDesc);
    if($dist < 0.45){
      echo json_encode([
        "status"=>false,
        "msg"=>"Wajah sudah terdaftar"
      ]);
      exit;
    }
  }

  $update = "UPDATE user 
           SET descriptor = '$descriptor'
           WHERE user_id = '$user_id'";
  if($connection->query($update) === false){
    echo json_encode([
      "status"=>false,
      "msg"=>"Registrasi gagal"
    ]);
  } else {
    echo json_encode([
      "status"=>true,
      "msg"=>"Registrasi Wajah berhasil"
    ]);
  }


/** Delete*/
break;
case 'reset':
  $descriptor = NULL;
  $update = "UPDATE user 
           SET descriptor = '$descriptor'
           WHERE user_id = '$user_id'";
  if($connection->query($update) === true){
     echo json_encode([
      "status"=>true,
      "msg"=>"Penyetelan Wajah berhasil"
    ]);
  } else {
   echo json_encode([
      "status"=>false,
      "msg"=>"Wajah gagal dihapus"
    ]);
  }
  
  break;
  }
}