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

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

// 🔥 DEBUG (hapus kalau sudah live)
ini_set('display_errors', 1);
error_reporting(E_ALL);

try {

  // =========================
  // 🔥 AMBIL INPUT POST 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 id, from_unit_id, to_unit_id, multiplier, company_id, is_deleted, created_at, updated_at
      FROM unit_conversions
      WHERE is_deleted = 0
      AND (company_id IS NULL OR company_id = ?)
    ");

    if (!$stmt) {
      throw new Exception("Prepare failed: " . mysqli_error($conn));
    }

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

    // ❗ TANPA mysqli_stmt_get_result (ANTI 500)
    mysqli_stmt_bind_result(
      $stmt,
      $id,
      $from_unit_id,
      $to_unit_id,
      $multiplier,
      $company_id_row,
      $is_deleted,
      $created_at,
      $updated_at
    );

    $data = [];

    while (mysqli_stmt_fetch($stmt)) {
      $data[] = [
        "id" => $id,
        "from_unit_id" => $from_unit_id,
        "to_unit_id" => $to_unit_id,
        "multiplier" => $multiplier,
        "company_id" => $company_id_row,
        "is_deleted" => $is_deleted,
        "created_at" => $created_at,
        "updated_at" => $updated_at,
      ];
    }

    mysqli_stmt_close($stmt);

  } else {

    $result = mysqli_query($conn, "
      SELECT id, from_unit_id, to_unit_id, multiplier, company_id, is_deleted, created_at, updated_at
      FROM unit_conversions
      WHERE is_deleted = 0
      AND company_id IS NULL
    ");

    if (!$result) {
      throw new Exception("Query failed: " . mysqli_error($conn));
    }

    $data = [];

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

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

} catch (Exception $e) {

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