<?php
include 'config.php';
header('Content-Type: application/json');

$id = $_POST['id'] ?? 0;
$type = $_POST['type'] ?? '';

if (!$id || !$type) {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid request"
    ]);
    exit;
}

$req = $conn->query("
SELECT *
FROM gift_requests
WHERE id='$id' AND status='pending'
");

if ($req->num_rows == 0) {
    echo json_encode([
        "status" => "error",
        "message" => "Request not found"
    ]);
    exit;
}

$r = $req->fetch_assoc();

$sender_uid   = $r['sender_uid'];
$receiver_uid = $r['receiver_uid'];
$amount       = $r['amount'];
$total        = $r['total'];
$balance_type = $r['type']; // balance / winning

// APPROVE
if ($type == "success") {

    // receiver balance add
    $conn->query("
    UPDATE users
    SET balance = balance + $amount
    WHERE uid='$receiver_uid'
    ");

    // update status
    $conn->query("
    UPDATE gift_requests
    SET status='approved'
    WHERE id='$id'
    ");

    echo json_encode([
        "status" => "success",
        "message" => "Gift approved"
    ]);
    exit;
}

// FAILED
if ($type == "failed") {

    // refund sender
    $conn->query("
    UPDATE users
    SET $balance_type = $balance_type + $total
    WHERE uid='$sender_uid'
    ");

    // update status
    $conn->query("
    UPDATE gift_requests
    SET status='failed'
    WHERE id='$id'
    ");

    echo json_encode([
        "status" => "success",
        "message" => "Gift rejected and refunded"
    ]);
    exit;
}

echo json_encode([
    "status" => "error",
    "message" => "Invalid type"
]);
?>