<?php


// UNITV_COMPAT_APP_STATUS_PAGO
$__unitv_id = $_GET['id'] ?? $_GET['idTransaction'] ?? $_GET['transaction_id'] ?? $_GET['transaction'] ?? '';
$__unitv_id = basename((string)$__unitv_id);

if ($__unitv_id !== '') {
    $__unitv_file = __DIR__ . '/syncpay_paid/' . $__unitv_id . '.json';

    if (is_file($__unitv_file)) {
        $__unitv_raw = file_get_contents($__unitv_file);
        $__unitv_j = json_decode($__unitv_raw, true);

        if (is_array($__unitv_j)) {
            $__unitv_status = strtoupper((string)($__unitv_j['status'] ?? $__unitv_j['raw_status'] ?? $__unitv_j['payment_status'] ?? $__unitv_j['status_transaction'] ?? ''));

            $__unitv_user = $__unitv_j['username'] ?? $__unitv_j['user'] ?? $__unitv_j['login'] ?? $__unitv_j['whatsapp'] ?? '';
            $__unitv_pass = $__unitv_j['password'] ?? $__unitv_j['pass'] ?? $__unitv_j['pin'] ?? '';

            $__unitv_ok_status = in_array($__unitv_status, ['APPROVED','PAID','CONFIRMED','PAGO','SUCCESS'], true);
            $__unitv_ok_xui = !empty($__unitv_j['xui_created']) || !empty($__unitv_j['processed']) || !empty($__unitv_j['xui_processed']);

            if ($__unitv_ok_status && $__unitv_ok_xui && $__unitv_user !== '' && $__unitv_pass !== '') {
                header('Content-Type: application/json; charset=utf-8');
                header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

                $server = $__unitv_j['server'] ?? $__unitv_j['dns'] ?? $__unitv_j['xui_server'] ?? 'https://brstream.vip';

                echo json_encode([
                    'ok' => true,
                    'found' => true,
                    'paid' => true,
                    'approved' => true,
                    'confirmed' => true,
                    'created' => true,
                    'processed' => true,

                    'status' => 'PAID',
                    'raw_status' => 'APPROVED',
                    'payment_status' => 'PAID',
                    'status_transaction' => 'APPROVED',
                    'transactionStatus' => 'APPROVED',

                    'id' => $__unitv_id,
                    'idTransaction' => $__unitv_id,
                    'transaction_id' => $__unitv_id,

                    'username' => (string)$__unitv_user,
                    'password' => (string)$__unitv_pass,
                    'login' => (string)$__unitv_user,
                    'senha' => (string)$__unitv_pass,
                    'user' => (string)$__unitv_user,
                    'pass' => (string)$__unitv_pass,
                    'pin' => (string)$__unitv_pass,

                    'server' => $server,
                    'dns' => $server,
                    'xui_server' => $server,
                    'url' => $server,

                    'days' => intval($__unitv_j['days'] ?? 30),
                    'max_connections' => intval($__unitv_j['max_connections'] ?? 1),
                    'xui_created' => true,
                    'xui_processed' => true,
                    'xui_error' => null,
                    'message' => 'Pagamento confirmado. Reiniciando app.'
                ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                exit;
            }
        }
    }
}
// UNITV_COMPAT_APP_STATUS_PAGO_FIM

/** UniTV PIX STATUS V90 - app fica escutando até XUI player_api local autenticar. */
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
const STATUS_VERSION='v96-status-escuta-mesmo-se-webhook-errou';
function out_json(array $b,int $c=200):void{http_response_code($c);echo json_encode($b,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);exit;}
function read_json_file(string $p):array{$j=json_decode((string)@file_get_contents($p),true);return is_array($j)?$j:[];}
function write_json_file(string $p,array $d):void{@file_put_contents($p,json_encode($d,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));}
function env_file_value(string $key,string $default=''):string{static $env=null;$v=getenv($key);if($v!==false&&trim((string)$v)!=='')return trim((string)$v);if($env===null){$env=[];$p=__DIR__.'/pix_xui.env';if(is_file($p))foreach((file($p,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[])as$line){$line=trim($line);if($line===''||$line[0]==='#'||strpos($line,'=')===false)continue;[$k,$val]=explode('=',$line,2);$k=trim($k);$val=trim($val);if(strlen($val)>=2&&(($val[0]==='"'&&substr($val,-1)==='"')||($val[0]==="'"&&substr($val,-1)==="'")))$val=substr($val,1,-1);if($k!=='')$env[$k]=$val;}}return isset($env[$key])&&trim((string)$env[$key])!==''?trim((string)$env[$key]):$default;}
function pick(array $a,array $keys,$def=null){foreach($keys as$k)if(isset($a[$k])&&$a[$k]!=='')return$a[$k];return$def;}
function json_contains_value($node,string $needle):bool{if($needle==='')return false;if(is_array($node)){foreach($node as$v)if(json_contains_value($v,$needle))return true;return false;}return(is_string($node)||is_numeric($node))&&trim((string)$node)===$needle;}
function find_json_by_id(string $dir,string $id):array{$safe=basename($id);$direct=$dir.'/'.$safe.'.json';if(is_file($direct))return[$direct,$safe,'direct'];$files=glob($dir.'/*.json')?:[];usort($files,fn($a,$b)=>(@filemtime($b)?:0)<=> (@filemtime($a)?:0));foreach(array_slice($files,0,500)as$p){$bn=basename($p);if(preg_match('/\.result\.json$/',$bn)||strpos($bn,'webhook_raw_')===0||strpos($bn,'webhook_orphan_')===0)continue;$tx=read_json_file($p);if($tx&&json_contains_value($tx,$id))return[$p,basename($p,'.json'),'scan'];}return[$direct,$safe,'not_found'];}
function normalize_status($raw,bool$created,bool$processed):string{$s=strtoupper(trim((string)$raw));if($s==='PAIDOUT')$s='PAID_OUT';$failed=['APPROVED_CREATE_FAILED','CREATE_LINE_FAILED','FAILED','CANCELED','CANCELLED','EXPIRED','REFUSED','CHARGEBACK'];if(in_array($s,$failed,true))return$s;if($processed)return'APPROVED';if($created)return'PENDING_RELEASE';return in_array($s,['APPROVED','PAID','PAID_OUT','COMPLETED','CONFIRMED','PAGO','SUCCESS','SUCCESSFUL'],true)?'PENDING_RELEASE':'PENDING';}
function call_bridge_check(string$username,string$password,string$txid):array{$url=env_file_value('XUI_BRIDGE_URL','https://brstream.vip/pix/syncpay_bridge_create.php');$token=env_file_value('XUI_BRIDGE_TOKEN','UNITV_PIX_BRIDGE_2026_081150');$timeout=max(5,min(20,(int)env_file_value('STATUS_BRIDGE_CHECK_TIMEOUT','12')));if(!function_exists('curl_init'))return['ok'=>false,'error'=>'curl_missing'];$post=['token'=>$token,'mode'=>'check','username'=>$username,'password'=>$password,'transaction_id'=>$txid];$ch=curl_init($url);curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($post),CURLOPT_CONNECTTIMEOUT=>5,CURLOPT_TIMEOUT=>$timeout,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_SSL_VERIFYHOST=>false,CURLOPT_HTTPHEADER=>['Accept: application/json']]);$body=curl_exec($ch);$errno=curl_errno($ch);$err=curl_error($ch);$http=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);if($errno)return['ok'=>false,'http'=>$http,'error'=>$err];$j=json_decode((string)$body,true);return is_array($j)?array_merge($j,['http'=>$http]):['ok'=>false,'http'=>$http,'error'=>'non_json','body'=>substr((string)$body,0,500)];}
if(isset($_GET['ping']))out_json(['ok'=>true,'file'=>'syncpayment_status.php','version'=>STATUS_VERSION,'time'=>date('c')]);
$id=trim((string)($_GET['idTransaction']??$_GET['idtransaction']??$_GET['id']??$_GET['transactionId']??$_GET['transaction_id']??''));if($id==='')out_json(['ok'=>false,'error'=>'Parâmetro idTransaction obrigatório'],400);
$baseDir=__DIR__.'/syncpay_paid';[$jsonPath,$idSafe,$match]=find_json_by_id($baseDir,$id);$resultPath=$baseDir.'/'.$idSafe.'.result.json';$donePath=$jsonPath.'.done';$tx=read_json_file($jsonPath);$result=read_json_file($resultPath);$dados=$result?:$tx;if(!$dados)out_json(['ok'=>true,'found'=>false,'version'=>STATUS_VERSION,'status'=>'PENDING','idTransaction'=>$idSafe,'match'=>$match]);
$username=(string)pick($dados,['username','login','whatsapp'],'');$password=(string)pick($dados,['password','senha','pin'],'');$created=!empty($dados['xui_created'])||!empty($dados['created']);$processed=!empty($dados['xui_processed'])||!empty($dados['processed'])||is_file($donePath);$rawStatus=(string)pick($dados,['status','webhook_status_received'],'PENDING');$check=null;
$upperStatus=strtoupper(trim($rawStatus));
$approvedLike=in_array($upperStatus,['APPROVED','PAID','PAID_OUT','COMPLETED','CONFIRMED','PAGO','SUCCESS','SUCCESSFUL','PENDING_RELEASE','APPROVED_CREATE_FAILED','CREATE_LINE_FAILED'],true)||!empty($dados['webhook_status_received'])||!empty($dados['pending_release_started_at']);
// V96: mesmo que o webhook tenha marcado erro/timeout, se já existe login/senha continuamos perguntando ao XUI local.
// Isso resolve o caso em que a line é criada, mas a resposta do create volta como erro/timeout e o app parava antes de receber o login.
if(!$processed&&$username!==''&&$password!==''&&$approvedLike){$check=call_bridge_check($username,$password,$idSafe);if(!empty($check['xui_ready'])||!empty($check['ready'])){$processed=true;$created=true;$rawStatus='APPROVED';$tx=read_json_file($jsonPath)?:$tx;$tx['status']='APPROVED';$tx['xui_created']=true;$tx['xui_processed']=true;$tx['processed']=true;$tx['released_at']=date('c');$tx['last_check']=$check;write_json_file($jsonPath,$tx);$dados=array_merge($dados,$tx);$res=read_json_file($resultPath)?:[];$res=array_merge($res,['ok'=>true,'status'=>'APPROVED','xui_created'=>true,'xui_processed'=>true,'processed'=>true,'username'=>$username,'password'=>$password,'login'=>$username,'senha'=>$password,'server'=>env_file_value('PUBLIC_XUI_SERVER','https://brstream.vip'),'dns'=>env_file_value('PUBLIC_XUI_SERVER','https://brstream.vip'),'xui_server'=>env_file_value('PUBLIC_XUI_SERVER','https://brstream.vip'),'released_at'=>date('c'),'last_check'=>$check]);write_json_file($resultPath,$res);@file_put_contents($donePath,date('c')." OK\n");}else{if(in_array($upperStatus,['APPROVED_CREATE_FAILED','CREATE_LINE_FAILED'],true)){$rawStatus='PENDING_RELEASE';}}}
$status=normalize_status($rawStatus,$created,$processed);$server=rtrim((string)pick($dados,['server','dns','xui_server'],env_file_value('PUBLIC_XUI_SERVER','https://brstream.vip')),'/');
out_json(['ok'=>true,'found'=>true,'version'=>STATUS_VERSION,'status'=>$status,'raw_status'=>$rawStatus,'idTransaction'=>$idSafe,'match'=>$match,'username'=>$username?:null,'password'=>$password?:null,'server'=>$server,'dns'=>$server,'xui_server'=>$server,'xui_created'=>$created,'xui_processed'=>$processed,'processed'=>$processed,'xui_error'=>pick($dados,['xui_error','error'],null),'rc'=>pick($dados,['xui_rc','rc'],null),'days'=>pick($dados,['days','dias'],null),'max_connections'=>pick($dados,['max_connections','conexoes'],null),'check'=>$check]);
