<?php
include_once('init.php');

class UserControllerProxy
{
  public function Select($data)
  {
    return call_api("launcher_aio", "select", $data);
  }
}

// Bersihkan input
function clean_text($text)
{
  return htmlspecialchars(trim($text), ENT_QUOTES, 'UTF-8');
}

// Default khusus per field (tipe non-string)
function get_special_defaults()
{
  return [
    'ID' => 0
  ];
}

// Ambil dan bersihkan semua data dari POST + tambahan sistem
function main_data($action)
{
  global $globalTitle, $glovalVersion, $IsWeb;

  $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
  $yourbrowser = $_SERVER['HTTP_USER_AGENT'] ?? '';

  $specialDefaults = get_special_defaults();
  $data = [];

  foreach ($_POST as $key => $val) {
    $val = is_string($val) ? $val : ''; // jika bukan string, kosongkan
    if (isset($specialDefaults[$key])) {
      $val = trim($val) === '' ? $specialDefaults[$key] : clean_text($val);
    } else {
      $val = clean_text($val);
    }
    $data[$key] = $val;
  }

  // Tambahan data sistem
  $data['NamaApp'] = $globalTitle;
  $data['Version'] = $glovalVersion;
  $data['IP'] = $ip_address;
  $data['DeviceData'] = $yourbrowser;
  $data['IsWeb'] = $IsWeb;

  return $data;
}

// Validasi field wajib
function validate_required_fields($action, $data)
{
  $requiredFields = [
    'Update' => ['ID'],
    'Delete' => ['ID'],
    'Select' => [],
  ];

  $missing = [];
  if (isset($requiredFields[$action])) {
    foreach ($requiredFields[$action] as $field) {
      if (!isset($data[$field]) || trim((string)$data[$field]) === '') {
        $missing[] = $field;
      }
    }
  }

  if (!empty($missing)) {
    return [
      'Status' => 0,
      'Keterangan' => 'Field tidak boleh kosong: ' . implode(', ', $missing)
    ];
  }

  return null;
}

// Eksekusi
$action = $_POST['action'] ?? '';
$data = main_data($action);

// Validasi field
$validationResult = validate_required_fields($action, $data);
if ($validationResult !== null) {
  header('Content-Type: application/json');
  echo json_encode($validationResult);
  exit;
}

// Routing action
$UserController = new UserControllerProxy();
switch ($action) {
  case 'select':
    $result = $UserController->Select($data);
    break;
  default:
    $result = ["Status" => 0, "Keterangan" => "Action tidak dikenal."];
    break;
}

header('Content-Type: application/json');
echo json_encode($result);
