<?php
declare(strict_types=1);
// Installed path is generated by install-bridge.php. No SMTP credentials in public files.
$private = '/home/aiprasfz/openmodule-mail';
header('Content-Type: application/json; charset=utf-8');header('Cache-Control: no-store, private');header('X-Content-Type-Options: nosniff');
function reply(array $data,int $code=200): never {http_response_code($code);echo json_encode($data,JSON_INVALID_UTF8_SUBSTITUTE);exit;}
if(($_SERVER['REQUEST_METHOD']??'')!=='POST')reply(['error'=>'Not found.'],404);
if(!is_file($private.'/cloudflare-bridge.php'))reply(['error'=>'Bridge not configured.'],503);
$secret=require $private.'/cloudflare-bridge.php';$time=$_SERVER['HTTP_X_OM_TIME']??'';$signature=$_SERVER['HTTP_X_OM_SIGNATURE']??'';
if(!is_string($secret)||strlen($secret)<32||!preg_match('/^[0-9]+$/D',$time)||abs(time()-(int)$time)>300||!preg_match('/^[a-f0-9]{64}$/D',$signature))reply(['error'=>'Unauthorized.'],401);
if((int)($_SERVER['CONTENT_LENGTH']??0)>7500000)reply(['error'=>'Request too large.'],413);
$raw=file_get_contents('php://input',false,null,0,7500001);if($raw===false||strlen($raw)>7500000)reply(['error'=>'Request too large.'],413);
if(!hash_equals(hash_hmac('sha256',$time."\n".hash('sha256',$raw),$secret),$signature))reply(['error'=>'Unauthorized.'],401);
require $private.'/src/core.php';require $private.'/src/sending.php';
try{
 $input=json_decode($raw,true,32,JSON_THROW_ON_ERROR);$action=$input['action']??'';
 if($action==='check'){if(!smtp_settings())reply(['error'=>'SMTP is not configured.']);smtp_connection_check(smtp_settings());reply(['ok'=>true]);}
 if(!in_array($action,['send','forward'],true))reply(['error'=>'Unknown action.'],400);
 $v=$input['message']??[];$settings=smtp_settings();if(!$settings)reply(['error'=>'SMTP is not configured.']);
 if($action==='forward'&&empty($v['from_email'])){$v['from_email']=$settings['username'];$v['from_name']='OpenModule Mail';}
 $sender=sending_sender(['email'=>$v['from_email']??'','name'=>$v['from_name']??'']);$valid=sending_validate($v);
 $hash=hash('sha256',json_encode([$action,$v],JSON_THROW_ON_ERROR));$key=$valid['request_key'];
 $existing=query('SELECT * FROM om_cf_relay WHERE request_key=?',[$key])->fetch(PDO::FETCH_ASSOC);
 if($existing){if(!hash_equals($existing['payload_hash'],$hash))reply(['error'=>'Request key mismatch.'],409);reply(['status'=>$existing['status']==='sending'&&time()-(int)$existing['created_at']>180?'uncertain':$existing['status'],'error'=>$existing['last_error']]);}
 // The unique reservation persists before SMTP; replaying this signed request cannot resend it.
 try{query("INSERT INTO om_cf_relay(request_key,payload_hash,status,created_at) VALUES(?,?,'sending',?)",[$key,$hash,time()]);}
 catch(PDOException $e){if($e->getCode()!=='23000')throw $e;$existing=query('SELECT * FROM om_cf_relay WHERE request_key=?',[$key])->fetch(PDO::FETCH_ASSOC);if(!$existing||!hash_equals($existing['payload_hash'],$hash))reply(['error'=>'Request key mismatch.'],409);reply(['status'=>$existing['status'],'error'=>$existing['last_error']]);}
 $m=null;$status='failed';$error=null;$started=false;
 try{
  $m=smtp_mailer($settings);$m->setFrom($sender['email'],$sender['name']);$m->Sender=$settings['username'];$m->addAddress($valid['to']);$m->addReplyTo($sender['email'],$sender['name']);$m->Subject=$valid['subject'];$m->Body=$valid['body'];$m->isHTML(false);
  if($action==='forward'){$m->addCustomHeader('Auto-Submitted','auto-generated');$m->addCustomHeader('X-OpenModule-Forwarded','1');$m->clearReplyTos();if(filter_var($v['reply_to']??'',FILTER_VALIDATE_EMAIL))$m->addReplyTo($v['reply_to']);}
  foreach($valid['attachments'] as $a)$m->addStringAttachment($a['content'],$a['name']);
  if(!$m->preSend())throw new RuntimeException('Could not prepare email.');
  // Retain the existing private Namecheap sent log for diagnostics and rollback.
  query("INSERT INTO om_sent(request_key,from_email,from_name,recipient,subject,body,raw_message,status,created_at) VALUES(?,?,?,?,?,?,?,'sending',?)",[$key,$sender['email'],$sender['name'],$valid['to'],$valid['subject'],$valid['body'],$m->getSentMIMEMessage(),time()]);
  $started=true;$status='uncertain';$m->postSend();$status='accepted';
 }catch(Throwable $e){$smtp=$m?$m->getSMTPInstance():null;$status=!$started||($smtp instanceof OpenModuleSMTP&&$smtp->failureCode>=400)?'failed':'uncertain';$error=smtp_safe_error($m?($m->ErrorInfo?:$e->getMessage()):$e->getMessage(),$settings);}
 finally{if($m)$m->smtpClose();}
 query('UPDATE om_cf_relay SET status=?,last_error=?,finished_at=? WHERE request_key=?',[$status,$error,time(),$key]);
 query('UPDATE om_sent SET status=?,last_error=?,finished_at=? WHERE request_key=?',[$status,$error,time(),$key]);
 reply(['status'=>$status,'error'=>$error]);
}catch(InvalidArgumentException $e){reply(['error'=>$e->getMessage()],422);}
catch(Throwable $e){error_log('OpenModule SMTP bridge failed: '.$e::class);reply(['error'=>'SMTP bridge request failed.'],500);}
