<?php
// partner/rspay/payout_callback.php
// Handles Asynchronous Notifications from RSPay for Payouts

header('Content-Type: application/json');

// 1. Connect to Database
require_once('../../database/config.php');

// 2. Read Incoming Data
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Log for debugging (Optional - enable if needed)
// file_put_contents('payout_callback.log', date('Y-m-d H:i:s') . " - " . $input . "\n", FILE_APPEND);

if (!$data) {
    echo json_encode(['status' => 'error', 'message' => 'No data received']);
    exit;
}

try {
    // 3. Fetch API Key from Settings
    $stmt = $conn->prepare("SELECT rspay_api_key FROM settings LIMIT 1");
    $stmt->execute();
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    $key = $settings['rspay_api_key'] ?? '';

    if (empty($key)) {
        throw new Exception("API Key not configured");
    }

    // 4. Verify Signature
    $received_sign = $data['sign'] ?? '';
    unset($data['sign']); // Remove sign from data to calculate hash
    
    // Sort keys
    ksort($data);
    $stringA = "";
    foreach ($data as $k => $v) {
        if ($v !== null && $v !== "" && !is_array($v)) { // Handle non-array values
             $stringA .= $k . "=" . $v . "&";
        }
    }
    $stringA .= "key=" . $key;
    $calculated_sign = strtolower(hash("sha256", $stringA));

    // Note: In production, strictly check signature. 
    // For now, if signature logic matches docs, it's good. 
    // Docs: SHA256(stringA&key=key), sorted params.
    
    // 5. Process Status
    // valid ext format: payout_{id}
    $ext = $data['ext'] ?? '';
    if (strpos($ext, 'payout_') === 0) {
        $req_id = str_replace('payout_', '', $ext);
        
        $state = $data['state'] ?? 0; // 1: Success, 2: Processing, 3: Failed
        $utr = $data['utr'] ?? '';
        
        $new_status = '';
        if ($state == 1) {
            $new_status = 'SUCCESS';
        } elseif ($state == 3) {
            $new_status = 'FAILED';
        }

        if (!empty($new_status)) {
            // Update Database
            if ($new_status == 'SUCCESS') {
                $upd = $conn->prepare("UPDATE payout_requests SET status = ?, utr = ? WHERE id = ?");
                $upd->execute([$new_status, $utr, $req_id]);
            } else {
                $upd = $conn->prepare("UPDATE payout_requests SET status = ? WHERE id = ?");
                $upd->execute([$new_status, $req_id]);
            }
        }
    }
    
    // 6. Return Success Response
    echo "success";

} catch (Exception $e) {
    // Determine response code? Docs say return "success" to stop retries.
    // If error is ours, maybe allow retry? But usually best to ack.
    echo "success"; 
}
?>
