<?php
include '../config/koneksi.php';

header('Content-Type: application/json');

try {

  // 🔥 SAFE PARSE JSON
  $raw = file_get_contents("php://input");
  $input = json_decode($raw, true);

  $company_id = null;
  if (is_array($input)) {
    $company_id = $input['company_id'] ?? null;
  }

  // =========================
  // 🔥 QUERY
  // =========================
  if (!empty($company_id)) {

    $stmt = mysqli_prepare($conn, "
      SELECT * FROM units 
      WHERE is_deleted = 0
      AND (is_global = 1 OR company_id = ?)
      ORDER BY is_global DESC, name ASC
    ");

    if (!$stmt) {
      throw new Exception(mysqli_error($conn));
    }

    mysqli_stmt_bind_param($stmt, "s", $company_id);
    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

  } else {

    $result = mysqli_query($conn, "
      SELECT * FROM units 
      WHERE is_deleted = 0
      AND is_global = 1
      ORDER BY name ASC
    ");

    if (!$result) {
      throw new Exception(mysqli_error($conn));
    }
  }

  // =========================
  // 🔥 FETCH DATA
  // =========================
  $data = [];

  if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
      $data[] = $row;
    }
  }

  echo json_encode([
    "success" => true,
    "data" => $data
  ]);

} catch (Exception $e) {

  echo json_encode([
    "success" => false,
    "message" => $e->getMessage()
  ]);
}