<?php if (!defined('C1O2N3S4T5A6N7T8')) { http_response_code(403); exit; }
if (!defined('PRIVATE_DIR')) define('PRIVATE_DIR', '/var/www/private');
require_once PRIVATE_DIR . '/../shared/request_signer.php';

function p1a2y3m4_query(string $action, array $params = []): array {
    $engine_ip = '10.69.69.1';
    $port = 7272;
    $timeout = 3;
    try {
        $socket = @fsockopen($engine_ip, $port, $errno, $errstr, $timeout);
        if (!$socket) {
            return ['ok' => false, 'e' => "Payment Node Offline: $errstr ($errno)"];
        }
        $payload = array_merge(['action' => $action], $params);
        $json = json_encode($payload);
        $signed = RequestSigner::sign($json);
        $envelope = json_encode([
            'sig' => $signed['signature'],
            'ts' => $signed['timestamp'],
            'nonce' => $signed['nonce'],
            'node' => 'origin-01',
            'body' => $json
        ]);
        fwrite($socket, $envelope);
        stream_set_timeout($socket, 3);
        $response = "";
        while (!feof($socket)) {
            $chunk = fgets($socket, 1024);
            if ($chunk === false) break;
            $response .= $chunk;
            $info = stream_get_meta_data($socket);
            if ($info['timed_out']) break;
        }
        fclose($socket);
        $result = json_decode($response, true);
        if (!$result) {
            return ['ok' => false, 'e' => 'Protocol error: Invalid engine response'];
        }
        return $result;
    } catch (\Throwable $e) {
        return ['ok' => false, 'e' => 'Bridge Exception: ' . $e->getMessage()];
    }
}

function p1a2y3m4_status(string $purchase_id): array {
    return p1a2y3m4_query('get_status', ['purchase_id' => $purchase_id]);
}

function p1a2y3m4_verify(string $purchase_id, string $proof, string $method = 'manual'): array {
    return p1a2y3m4_query('verify_payment', [
        'purchase_id' => $purchase_id,
        'proof' => $proof,
        'method' => $method
    ]);
}

function p1a2y3m4_sync_tracking(string $purchase_id, string $tracking_no): array {
    return p1a2y3m4_query('sync_tracking', [
        'purchase_id' => $purchase_id,
        'tracking_no' => $tracking_no
    ]);
}
