<?php
/**
 * boompay_payout_callback.php — Boompay Withdrawal Payout Callback
 * status 'success' = approved, otherwise = failed (refund user)
 */
require_once __DIR__ . '/config.php';

date_default_timezone_set('Asia/Karachi');

$log = __DIR__ . '/boompay_payout_callback_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['order_id'])) { echo "ok"; exit; }

$order_sn = $post['order_id'];
$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') {
        // 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";
}
