<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user'])) { http_response_code(401); exit; }
$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','warehouse'])) { http_response_code(403); exit; }

require_once __DIR__ . '/../config/db_remote.php'; // $mysqli

$data = json_decode(file_get_contents('php://input'), true);
$bolId = $data['bol_id'] ?? '';
$fieldId = isset($data['field_id']) ? (int)$data['field_id'] : 0;
$value = $data['value'] ?? '';

if ($bolId === '' || $fieldId <= 0) {
  http_response_code(400);
  echo 'Bad Request';
  exit;
}

$bolEsc = $mysqli->real_escape_string($bolId);

// block saves if not draft
$res = $mysqli->query("SELECT status FROM bol_documents WHERE id = '$bolEsc' LIMIT 1");
if (!$res) { http_response_code(500); exit; }
$status = ($res->fetch_assoc()['status'] ?? null);
if ($status !== 'draft') {
  http_response_code(403);
  echo 'Locked';
  exit;
}

$stmt = $mysqli->prepare("
  INSERT INTO bol_values (bol_id, field_id, value)
  VALUES (?, ?, ?)
  ON DUPLICATE KEY UPDATE value = VALUES(value)
");
$stmt->bind_param('sis', $bolId, $fieldId, $value);
if (!$stmt->execute()) {
  http_response_code(500);
  echo 'DB Error';
  exit;
}

echo 'OK';
