<?php
require __DIR__.'/bootstrap.php'; method('POST'); require_auth(true);
$in=input_json((int)$config['max_payload_bytes']); $payload=validate_payload($in['payload']??null); $base=max(0,(int)($in['base_revision']??0)); $force=!empty($in['force']); $device=substr(trim((string)($in['device_id']??'UNKNOWN')),0,160);
[$dir,$file,$lockFile,$hist]=storage_paths($config); $lock=fopen($lockFile,'c+'); if(!$lock||!flock($lock,LOCK_EX)) respond(['error'=>'No se pudo bloquear el almacenamiento.'],503);
try{$current=read_state($file);$rev=(int)$current['revision'];if(!$force&&$base!==$rev)respond(['error'=>'Conflicto de revisión.','server_revision'=>$rev,'base_revision'=>$base],409);if($rev>0&&is_array($current['payload']))@file_put_contents($hist.'/revision-'.str_pad((string)$rev,8,'0',STR_PAD_LEFT).'-'.date('Ymd-His').'.json',json_encode($current,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),LOCK_EX);$next=$rev+1;$state=['revision'=>$next,'checksum'=>checksum_payload($payload),'updated_at'=>gmdate('c'),'device_id'=>$device,'payload'=>$payload];$tmp=$file.'.tmp-'.bin2hex(random_bytes(5));$json=json_encode($state,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);if(file_put_contents($tmp,$json,LOCK_EX)===false||!rename($tmp,$file))respond(['error'=>'No se pudo escribir la copia del servidor.'],500);prune_history($hist,(int)$config['history_limit']);respond(['ok'=>true,'revision'=>$next,'checksum'=>$state['checksum'],'updated_at'=>$state['updated_at']]);}finally{flock($lock,LOCK_UN);fclose($lock);}
