<?php
/**
 * io_payout_webhook.php - IO Pay Withdrawal Payout Callback
 */
require_once __DIR__ . '/config.php';

$log = __DIR__ . '/io_payout_webhook_log.txt';

$post = $_POST;
if (empty($post)) {
    $raw  = file_get_contents('php://input');
    $post = json_decode($raw, true) ?: [];
    if (empty($post)) parse_str($raw, $post);
}
file_put_contents($log, date('Y-m-d H:i:s')." | IN: ".json_encode($post)."\n", FILE_APPEND);

if (empty($post['merchant_order_no'])) { echo "ok"; exit; }

// Fetch API Key from settings
$stmt = $pdo->query("SELECT setting_value FROM admin_settings WHERE setting_key = 'io_key'");
$key = $stmt->fetchColumn() ?: '2D0B68F4496049956B6E259662FE0155';

// Verify signature
function iopay_verify($data, $apiKey) {
    $provided_sign = $data['sign'] ?? '';
    unset($data['sign']);
    $filtered = array_filter($data, function($v) { return $v !== '' && $v !== null; });
    ksort($filtered);
    $stringA = urldecode(http_build_query($filtered));
    $expected_sign = strtoupper(md5($stringA . "&key=" . $apiKey));
    return hash_equals($expected_sign, $provided_sign);
}

if (!iopay_verify($post, $key)) {
    file_put_contents($log, date('Y-m-d H:i:s')." | SIGN MISMATCH\n", FILE_APPEND);
    http_response_code(400); 
    echo "invalid sign"; 
    exit;
}

$order_sn = $post['merchant_order_no'];
$status   = strtolower($post['status'] ?? '');

$st = $pdo->prepare("SELECT * FROM withdrawals WHERE payout_order_id=?");
$st->execute([$order_sn]); $wd = $st->fetch();

if (!$wd || $wd['payout_status'] !== 'processing') {
    file_put_contents($log, date('Y-m-d H:i:s')." | Not found or not processing: $order_sn\n", FILE_APPEND);
    echo "ok"; exit;
}

$pdo->beginTransaction();
try {
    if ($status === 'success') {
        // Payout success
        $pdo->prepare("UPDATE withdrawals SET payout_status='sent', status='approved', updated_at=NOW() WHERE id=?")->execute([$wd['id']]);
        $pdo->prepare("UPDATE users SET total_withdrawn=COALESCE(total_withdrawn,0)+? WHERE id=?")->execute([$wd['amount'], $wd['user_id']]);
        $pdo->commit();
        file_put_contents($log, date('Y-m-d H:i:s')." | SUCCESS WD#{$wd['id']}\n", FILE_APPEND);
    } elseif ($status === 'failed' || $status === 'rejected') {
        // Payout failed - refund balance
        $reason = $post['msg'] ?? 'Payout failed by gateway';
        $pdo->prepare("UPDATE withdrawals SET payout_status='failed', status='rejected', reject_reason=?, updated_at=NOW() WHERE id=?")->execute([$reason, $wd['id']]);
        $pdo->prepare("UPDATE users SET balance=COALESCE(balance,0)+? WHERE id=?")->execute([$wd['amount'], $wd['user_id']]);
        $pdo->commit();
        file_put_contents($log, date('Y-m-d H:i:s')." | FAILED WD#{$wd['id']}, refunded Rs{$wd['amount']}\n", FILE_APPEND);
    } else {
        $pdo->rollBack();
    }
    echo "ok";
} catch (Exception $e) {
    $pdo->rollBack();
    file_put_contents($log, date('Y-m-d H:i:s')." | ERROR: ".$e->getMessage()."\n", FILE_APPEND);
    echo "ok";
}
