<?php 
if(!isset($_COOKIE['ADMIN_KEY']) && !isset($_COOKIE['KEY'])){
  header('location:./login/');
  exit;
}else{
header("Content-Type: application/json");
require_once'../../../sw-library/sw-config.php';
require_once'../../../sw-library/sw-function.php';
require_once'../../login/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 'dropdown':
 $query_user = "SELECT user_id, nama_lengkap 
                FROM user 
                WHERE descriptor IS NULL 
                  AND active = 'Y' 
                ORDER BY nama_lengkap ASC";
  $result_user = $connection->query($query_user);
  $data = [];
  while ($data_user = $result_user->fetch_assoc()) {
    $data[] = [
        'id'   => convert('encrypt', $data_user['user_id'] ?? '-'),
        'text' => $data_user['nama_lengkap']
    ];
  }

echo json_encode($data);
exit;

break;
case 'add':
$error = array();

$data   = json_decode(file_get_contents("php://input"), true);

  if(!$data || !isset($data['descriptor'])){
    echo json_encode([
      "status"=>false,
      "msg"=>"Data tidak valid"
    ]);
    exit;
  }
  
  $user_id  = convert('decrypt', $data['user_id']?? 0);
  $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"
    ]);
  }
exit;

/** Delete*/
break;
case 'delete':
if(isset($_POST['id'])){
    $user_id  = convert('decrypt', $_POST['id']?? 0);

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

break;
}
}?>