<?php
/** Keep the token in private server config, never in email HTML or client JavaScript. */
declare(strict_types=1);
function inboxmarketConnectorRequest(string $token,array $payload): array {
 if(!preg_match('/^[a-f0-9]{64}$/D',$token)||!function_exists('curl_init'))return [];
 $curl=curl_init('https://inboxmarket.ae/connector-api.php');
 curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$token,'X-InboxMarket-Connector: '.$token],CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT_MS=>800,CURLOPT_TIMEOUT_MS=>2000,CURLOPT_FOLLOWLOCATION=>false,CURLOPT_PROTOCOLS=>CURLPROTO_HTTPS]);
 $body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl);
 if($status!==200||!is_string($body)||strlen($body)>20000)return [];
 $result=json_decode($body,true);return is_array($result)&&($result['ok']??false)===true?$result:[];
}
function inboxmarketPrepareEmail(string $token): array {
 $result=inboxmarketConnectorRequest($token,['action'=>'render']);
 return ['html'=>is_string($result['embed_html']??null)?$result['embed_html']:'','receipt'=>is_string($result['receipt']??null)?$result['receipt']:null];
}
/** Backward-compatible footer-only method. It deliberately does not report a send. */
function inboxmarketEmailFooter(string $token): string {return inboxmarketPrepareEmail($token)['html'];}
function inboxmarketReportAccepted(string $token,?string $receipt): bool {
 if(!$receipt)return false;
 return (inboxmarketConnectorRequest($token,['action'=>'report_accepted','receipt'=>$receipt])['ok']??false)===true;
}
// Optional integration in your mail-sending service:
// $prepared = inboxmarketPrepareEmail($privateToken);
// Append $prepared['html'] to ONE outgoing email and retain this pair in that message.
// Only AFTER your actual transport returns accepted for that message:
// inboxmarketReportAccepted($privateToken, $prepared['receipt']);
// On transport failure: do not report. Retry reporting with the SAME receipt within 24h.
// Never send recipient addresses or message contents to this API.
// A receipt is one render/message, not a recipient count. Render separately per outgoing message.
// Empty HTML or a failed callback must not block the underlying email. The helper does not send mail.
