<?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;
  }

  // =========================
  // 🔥 GET LAST UNITS
  // =========================
  if (!empty($company_id)) {

    $stmtUnits = mysqli_prepare($conn, "
      SELECT MAX(updated_at) as last 
      FROM units 
      WHERE is_deleted = 0
      AND (is_global = 1 OR company_id = ?)
    ");

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

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

    mysqli_stmt_bind_result($stmtUnits, $lastUnits);
    mysqli_stmt_fetch($stmtUnits);
    mysqli_stmt_close($stmtUnits);

  } else {

    $resultUnits = mysqli_query($conn, "
      SELECT MAX(updated_at) as last 
      FROM units 
      WHERE is_deleted = 0
      AND is_global = 1
    ");

    if (!$resultUnits) {
      throw new Exception("Query units error: " . mysqli_error($conn));
    }

    $rowUnits = mysqli_fetch_assoc($resultUnits);
    $lastUnits = $rowUnits['last'] ?? null;
  }

  if (empty($lastUnits)) {
    $lastUnits = '1970-01-01 00:00:00';
  }

  // =========================
  // 🔥 GET LAST CONVERSIONS
  // =========================
  if (!empty($company_id)) {

    $stmtConv = mysqli_prepare($conn, "
      SELECT MAX(updated_at) as last 
      FROM unit_conversions 
      WHERE is_deleted = 0
      AND (company_id IS NULL OR company_id = ?)
    ");

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

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

    mysqli_stmt_bind_result($stmtConv, $lastConv);
    mysqli_stmt_fetch($stmtConv);
    mysqli_stmt_close($stmtConv);

  } else {

    $resultConv = mysqli_query($conn, "
      SELECT MAX(updated_at) as last 
      FROM unit_conversions 
      WHERE is_deleted = 0
      AND company_id IS NULL
    ");

    if (!$resultConv) {
      throw new Exception("Query conversions error: " . mysqli_error($conn));
    }

    $rowConv = mysqli_fetch_assoc($resultConv);
    $lastConv = $rowConv['last'] ?? null;
  }

  if (empty($lastConv)) {
    $lastConv = '1970-01-01 00:00:00';
  }

  // =========================
  // 🔥 VERSION FINAL
  // =========================
  $version = max($lastUnits, $lastConv);

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

} catch (Exception $e) {

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