<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

function done($code=200,$msg=['ok'=>true]){
 http_response_code($code);
 echo json_encode($msg,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
 exit;
}
function media_log($level,$stage,$message,$context=[]){
 $row=['time'=>gmdate('c'),'level'=>$level,'stage'=>$stage,'message'=>$message,'context'=>$context];
 @error_log(json_encode($row,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES).PHP_EOL,3,__DIR__.'/relay-media.log');
}
function telegram_file_descriptor($m){
 if(!empty($m['photo'])&&is_array($m['photo'])){
  $p=end($m['photo']);return is_array($p)?['file_id'=>(string)($p['file_id']??''),'name'=>'telegram-photo.jpg','bucket'=>'images']:null;
 }
 foreach([['voice','telegram-voice.ogg','voice'],['audio','telegram-audio','audio'],['video','telegram-video.mp4','video'],['document','telegram-document','files'],['animation','telegram-animation.mp4','video']] as $row){
  $key=$row[0];
  if(!empty($m[$key])&&is_array($m[$key])){
   $x=$m[$key];
   return ['file_id'=>(string)($x['file_id']??''),'name'=>(string)($x['file_name']??$row[1]),'bucket'=>$row[2]];
  }
 }
 return null;
}
function telegram_download($c,$file_id,$fallback_name){
 $ch=curl_init('https://api.telegram.org/bot'.$c['bot_token'].'/getFile');
 curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT=>8,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>['Content-Type: application/json'],CURLOPT_POSTFIELDS=>json_encode(['file_id'=>$file_id])]);
 $body=curl_exec($ch);$err=curl_error($ch);$code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);
 $j=is_string($body)?json_decode($body,true):null;
 if($body===false||$err!==''||!is_array($j)||empty($j['ok']))return [null,null,'getFile failed: '.($err?:($j['description']??('HTTP '.$code)))];
 $fp=(string)($j['result']['file_path']??'');$declared=(int)($j['result']['file_size']??0);
 if($fp===''||$declared>8*1024*1024)return [null,null,'Telegram file path/size invalid'];
 $ch=curl_init('https://api.telegram.org/file/bot'.$c['bot_token'].'/'.$fp);
 curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT=>8,CURLOPT_TIMEOUT=>25,CURLOPT_NOPROGRESS=>false,CURLOPT_PROGRESSFUNCTION=>function($ch,$total,$downloaded,$ut,$uploaded){return $downloaded>8*1024*1024?1:0;}]);
 $bytes=curl_exec($ch);$err=curl_error($ch);$code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);
 if($bytes===false||$err!==''||$code!==200||strlen((string)$bytes)>8*1024*1024)return [null,null,'file download failed: '.($err?:('HTTP '.$code))];
 $name=basename($fp)?:$fallback_name;
 return [(string)$bytes,$name,null];
}
function multipart_forward_body($update,$bytes,$name,&$ctype){
 $boundary='----MesoraWP'.bin2hex(random_bytes(12));$e="
";
 $body='--'.$boundary.$e;
 $body.='Content-Disposition: form-data; name="update_json"; filename="update.json"'.$e;
 $body.='Content-Type: application/json'.$e.$e.$update.$e;
 $safe=preg_replace('/[^A-Za-z0-9._-]/','_',basename($name));if($safe==='')$safe='telegram-media';
 $body.='--'.$boundary.$e.'Content-Disposition: form-data; name="media"; filename="'.$safe.'"'.$e;
 $body.='Content-Type: application/octet-stream'.$e.$e.$bytes.$e.'--'.$boundary.'--'.$e;
 $ctype='multipart/form-data; boundary='.$boundary;
 return $body;
}
function forward_wordpress($c,$raw,$media=null){
 $ts=(string)time();$headers=['X-Mesora-Site: '.(string)$c['site_id'],'X-Mesora-Timestamp: '.$ts];
 if(is_array($media)){
  [$bytes,$name]=$media;
  $sig=hash_hmac('sha256',$ts.'.MEDIA.'.hash('sha256',$raw).'.'.hash('sha256',$bytes),(string)$c['shared_secret']);
  $ctype='';$post=multipart_forward_body($raw,$bytes,$name,$ctype);
  $headers[]='Content-Type: '.$ctype;$headers[]='Content-Length: '.strlen($post);$headers[]='Expect:';$headers[]='X-Mesora-Media: 1';$headers[]='X-Mesora-Signature: '.$sig;
 }else{
  $sig=hash_hmac('sha256',$ts.'.'.$raw,(string)$c['shared_secret']);$post=$raw;
  $headers[]='Content-Type: application/json';$headers[]='X-Mesora-Signature: '.$sig;
 }
 $ch=curl_init((string)$c['wordpress_url']);
 curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT=>8,CURLOPT_TIMEOUT=>20,CURLOPT_HTTPHEADER=>$headers,CURLOPT_POSTFIELDS=>$post]);
 $body=curl_exec($ch);$err=curl_error($ch);$code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);
 return [$code,$err,is_string($body)?$body:''];
}

$cf=__DIR__.'/config.php';if(!is_file($cf))done(503,['ok'=>false]);$c=require $cf;require_once __DIR__.'/queue-lib.php';
$got=(string)($_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN']??'');
if($got===''||!hash_equals((string)$c['webhook_secret'],$got))done(403,['ok'=>false]);
$raw=file_get_contents('php://input');if(!is_string($raw)||$raw==='')done();
$u=json_decode($raw,true);$msg=is_array($u)?($u['message']??null):null;$media=null;

if(is_array($msg)){
 $d=telegram_file_descriptor($msg);
 if(is_array($d)&&$d['file_id']!==''){
  media_log('info','webhook_media','Telegram media webhook received',['update_id'=>(int)($u['update_id']??0),'message_id'=>(int)($msg['message_id']??0)]);
  [$bytes,$name,$e]=telegram_download($c,$d['file_id'],$d['name']);
  if($e!==null){
   media_log('error','telegram_media_download','Telegram media download failed',['update_id'=>(int)($u['update_id']??0),'error'=>$e]);
   done(502,['ok'=>false,'error'=>'Telegram media download failed']);
  }
  $media=[$bytes,$name];
  ms_store_bytes($bytes,$name,(string)($d['bucket']??'files'));
  media_log('info','telegram_media_download','Telegram media downloaded for inline WordPress forwarding',['name'=>$name,'bytes'=>strlen($bytes)]);
 }
}

[$code,$err,$body]=forward_wordpress($c,$raw,$media);
if($err!==''||$code<200||$code>=300){
 media_log('error','wordpress_forward','WordPress webhook forwarding failed',[
  'http'=>$code,'curl_error'=>$err,'response_body'=>substr($body,0,1000),
  'update_id'=>(int)($u['update_id']??0),'media_inline'=>is_array($media),'update_sha256'=>hash('sha256',$raw),'media_sha256'=>is_array($media)?hash('sha256',$media[0]):''
 ]);
 done(502,['ok'=>false,'error'=>'WordPress forwarding failed','http'=>$code]);
}
if(is_array($media)){
 media_log('info','wordpress_forward','Telegram media webhook forwarded inline to WordPress',['http'=>$code,'update_id'=>(int)($u['update_id']??0),'update_sha256'=>hash('sha256',$raw),'media_sha256'=>hash('sha256',$media[0])]);
}
done();
