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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Login required']);
    exit;
}

$userId = (int)$_SESSION['user_id'];
global $pdo;

$input = json_decode(file_get_contents('php://input'), true) ?: [];
$amount = isset($input['amount']) ? (float)$input['amount'] : 0;
$method = isset($input['method']) ? trim($input['method']) : ''; // bank, upi, usdt
$detailId = isset($input['detail_id']) ? (int)$input['detail_id'] : 0;

if ($amount <= 0 || !in_array($method, ['bank', 'upi', 'usdt'], true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid amount or method']);
    exit;
}

$minWithdraw = 110;
$feePct = 0;
try {
    $s = $pdo->query("SELECT setting_key, setting_value FROM site_settings WHERE setting_key IN ('min_withdrawal','withdraw_fee')");
    while ($row = $s->fetch(PDO::FETCH_ASSOC)) {
        if ($row['setting_key'] === 'min_withdrawal') $minWithdraw = (float)$row['setting_value'];
        if ($row['setting_key'] === 'withdraw_fee') $feePct = (float)$row['setting_value'];
    }
} catch (Exception $e) {}

if ($amount < $minWithdraw) {
    echo json_encode(['success' => false, 'message' => 'Minimum withdrawal is ₹' . number_format($minWithdraw, 2)]);
    exit;
}

$fee = round($amount * ($feePct / 100), 2);
$netAmount = $amount - $fee;

// Transaction Shuru Karo
$pdo->beginTransaction();

try {
    // 1. Balance Check karo
    $wallet = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE"); // FOR UPDATE is safety lock
    $wallet->execute([$userId]);
    $bal = $wallet->fetchColumn();
    
    if ((float)$bal < $amount) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Insufficient balance']);
        exit;
    }

    // 2. Balance Minus Karo
    $upd = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $upd->execute([$amount, $userId]);

    $bankDetailId = null;
    $upiDetailId = null;
    if ($method === 'bank') $bankDetailId = $detailId > 0 ? $detailId : null;
    if ($method === 'upi') $upiDetailId = $detailId > 0 ? $detailId : null;

    // 3. Request Insert Karo
    $pdo->prepare("
        INSERT INTO withdraw_requests (user_id, amount, net_amount, fee, payment_method, bank_detail_id, upi_detail_id, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
    ")->execute([$userId, $amount, $netAmount, $fee, $method, $bankDetailId, $upiDetailId]);
    
    // Sab theek hai toh Commit (Save) karo
    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'Withdrawal request submitted. Balance deducted.']);

} catch (Exception $e) {
    // Agar koi error aaya toh Undo (Rollback) karo
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>