<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require '../../../db.php';

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->user_id) || !isset($data->amount_diamonds) || !isset($data->payment_method_id)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing data']);
    exit();
}

// Get Settings
$stmt = $pdo->query("SELECT setting_key, setting_value FROM site_config WHERE setting_key IN ('diamond_exchange_rate', 'min_withdrawal_diamonds')");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$rate = isset($settings['diamond_exchange_rate']) ? (float)$settings['diamond_exchange_rate'] : 0.01;
$minWithdraw = isset($settings['min_withdrawal_diamonds']) ? (int)$settings['min_withdrawal_diamonds'] : 100;

$user_id = $data->user_id;
$diamonds = (int)$data->amount_diamonds;

if ($diamonds < $minWithdraw) {
    echo json_encode(['success' => false, 'message' => "Minimum withdrawal is $minWithdraw diamonds"]);
    exit();
}

$money = $diamonds * $rate;

try {
    $pdo->beginTransaction();

    // Check Balance
    $stmt = $pdo->prepare("SELECT diamonds FROM i_users WHERE iuid = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if (!$user || $user['diamonds'] < $diamonds) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Insufficient funds']);
        exit();
    }

    // Deduct Diamonds immediately (or hold)? Usually deduct to prevent double spend.
    $pdo->prepare("UPDATE i_users SET diamonds = diamonds - ? WHERE iuid = ?")->execute([$diamonds, $user_id]);

    // Create Withdrawal Request
    $sql = "INSERT INTO withdrawals (user_id, amount_diamonds, amount_money, payment_method_id, status) VALUES (?, ?, ?, ?, 'pending')";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $diamonds, $money, $data->payment_method_id]);

    // Log Transaction
    $pdo->prepare("INSERT INTO wallet_transactions (user_id, type, amount, related_user_id, status) VALUES (?, 'withdraw', ?, NULL, 'pending')")
        ->execute([$user_id, -$diamonds]);

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'Withdrawal requested']);

} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
