<?php
require_once('../database/header.php');

$message = "";
$messageType = "";

if (isset($_POST['submit_payout'])) {
    $amount = filter_input(INPUT_POST, 'amount', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    $bank_name = filter_input(INPUT_POST, 'bank_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $bank_account = filter_input(INPUT_POST, 'bank_account', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $ifsc = filter_input(INPUT_POST, 'ifsc', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $holder_name = filter_input(INPUT_POST, 'holder_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $user = $userdata['username'];
    $status = 'PENDING';
    $created_at = date('Y-m-d H:i:s');

    if ($amount && $bank_name && $bank_account && $ifsc && $holder_name) {
        try {
            // --- 1. CALCULATE AVAILABLE BALANCE (NET) ---
            // Fetch Global Settings
            $set_stmt = $conn->prepare("SELECT * FROM settings LIMIT 1");
            $set_stmt->execute();
            $settings = $set_stmt->fetch(PDO::FETCH_ASSOC);

            // Fetch successful pay-ins
            $stmt = $conn->prepare("SELECT amount, user FROM create_orders WHERE txn_status = 'SUCCESS' AND user_id = ?");
            $stmt->execute([$userdata['id']]);
            
            $total_payin_net = 0;
            
            // Calculate Pay-In Fees (To get true Net Balance)
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                 // For now, using global settings for historical calculation if user specific not stored with txn
                 // Ideally, we should store 'fee' in create_orders. 
                 // Re-using logic from index.php:
                 
                 $payin_base = floatval($settings['rspay_payin_base'] ?? 0);
                 $payin_margin = floatval($userdata['payin_commission'] ?? $settings['payin_commission'] ?? 0);
                 $payin_percent = $payin_base + $payin_margin;
                 
                 $payin_fixed_base = floatval($settings['rspay_payin_fixed'] ?? 0);
                 $payin_fixed_margin = floatval($settings['payin_fixed'] ?? 0);
                 $payin_fixed = $payin_fixed_base + $payin_fixed_margin;
                 
                 $amt = floatval($row['amount']);
                 $fee = ($amt * ($payin_percent / 100)) + $payin_fixed;
                 $net_amount = $amt - $fee;
                 $total_payin_net += $net_amount;
            }

            // Calculate Total Payouts (Gross: Amount requested is what is deducted from logic)
            $total_payout = 0;
            try {
                $stmt = $conn->prepare("SELECT COALESCE(SUM(amount), 0) FROM payout_requests WHERE user = ? AND status NOT IN ('REJECTED', 'FAILED')");
                $stmt->execute([$userdata['username']]);
                $total_payout = $stmt->fetchColumn();
            } catch (PDOException $e) {
                $total_payout = 0;
            }

            $available_balance = $total_payin_net - $total_payout;

            if ($available_balance < 200) {
                 $message = "提现失败！申请提现需要最低钱包余额 ₹120。您的余额：₹" . number_format($available_balance, 2);
                 $messageType = "danger";
            } else {
                // --- 2. CALCULATE PAYOUT FEE ---
                // Detect UPI
                $is_payout_upi = (stripos($bank_name, 'UPI') !== false) || (strpos($bank_account, '@') !== false);

                if ($is_payout_upi) {
                    $payout_percent = floatval($settings['bank_upi_payout_commission'] ?? 0);
                    $payout_fixed = floatval($settings['bank_upi_payout_fixed'] ?? 0);
                } else {
                    $payout_base = floatval($settings['rspay_payout_base'] ?? 0);
                    $payout_margin = floatval($userdata['payout_commission'] ?? $settings['payout_commission'] ?? 0);
                    $payout_percent = $payout_base + $payout_margin;
                    
                    $payout_fixed_base = floatval($settings['rspay_payout_fixed'] ?? 0);
                    $payout_fixed_margin = floatval($settings['payout_fixed'] ?? 0);
                    $payout_fixed = $payout_fixed_base + $payout_fixed_margin;
                }

                $handling_fee = ($amount * ($payout_percent / 100)) + $payout_fixed;
                $total_deduction = $amount + $handling_fee;
                
                if ($total_deduction > $available_balance) {
                    $message = "余额不足（含手续费）！您需要 ₹" . number_format($total_deduction, 2) . " (金额: ₹$amount + 手续费: ₹" . number_format($handling_fee, 2) . ") 但您只有 ₹" . number_format($available_balance, 2);
                    $messageType = "danger";
                } else {
                    // Logic continues to generate IDs and Insert...
                
                // Generate a random Platform ID (approx 19 digits)
                // Using microtime to ensure uniqueness + random
                $platform_id = date('YmdHis') . rand(10000, 99999); 
                
                // Generate a random Merchant Order ID (Numeric, approx 18-19 digits)
                // distinct from platform_id
                $merchant_order_id = time() . rand(10000000, 99999999);
                
                // Ensure table columns exist
                $conn->exec("CREATE TABLE IF NOT EXISTS payout_requests (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user VARCHAR(255),
                    bank_name VARCHAR(255),
                    amount DECIMAL(10,2),
                    bank_account VARCHAR(255),
                    ifsc VARCHAR(50),
                    holder_name VARCHAR(255),
                    status VARCHAR(50),
                    created_at DATETIME
                )");

                try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN bank_name VARCHAR(255) AFTER user"); } catch (PDOException $e) {}
                try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN handling_fee DECIMAL(10,2) DEFAULT 0.00"); } catch(PDOException $e){}
                try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN platform_id VARCHAR(255)"); } catch(PDOException $e){}
                try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN merchant_order_id VARCHAR(255)"); } catch(PDOException $e){}

                $stmt = $conn->prepare("INSERT INTO payout_requests (user, bank_name, amount, handling_fee, bank_account, ifsc, holder_name, status, created_at, platform_id, merchant_order_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                if ($stmt->execute([$user, $bank_name, $amount, $handling_fee, $bank_account, $ifsc, $holder_name, $status, $created_at, $platform_id, $merchant_order_id])) {
                    $message = "提现申请提交成功！（已扣除手续费：₹" . number_format($handling_fee, 2) . ")";
                    $messageType = "success";
                } else {
                    $message = "申请提交失败。";
                    $messageType = "danger";
                }
            }
        }
        } catch (PDOException $e) {
            $message = "数据库错误：" . $e->getMessage();
            $messageType = "danger";
        }
    } else {
        $message = "请填写所有字段。";
        $messageType = "warning";
    }
}
?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="row">
            <div class="col-md-12 grid-margin stretch-card mx-auto">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">申请提现</h4>
                        <p class="card-description">
                            输入您的银行详细信息以申请提现。
                        </p>
                        
                        <?php if ($message): ?>
                            <div class="alert alert-<?php echo $messageType; ?>">
                                <?php echo $message; ?>
                            </div>
                        <?php endif; ?>

                        <form class="forms-sample" method="POST" action="">
<form class="forms-sample" method="POST" action="">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label for="amount">金额 (₹)</label>
                <input type="number" step="0.01" class="form-control" id="amount" name="amount" placeholder="输入金额" required>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label for="bank_name">银行名称</label>
                <input type="text" class="form-control" id="bank_name" name="bank_name" placeholder="输入银行名称" required>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label for="holder_name">账户持有人姓名</label>
                <input type="text" class="form-control" id="holder_name" name="holder_name" placeholder="账户持有人姓名" required>
            </div>
        </div>
        <div class="col-md-6">
             <div class="form-group">
                <label for="ifsc">IFSC 代码</label>
                <input type="text" class="form-control" id="ifsc" name="ifsc" placeholder="IFSC 代码" required>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <label for="bank_account">银行账号</label>
                <input type="text" class="form-control" id="bank_account" name="bank_account" placeholder="银行账号" required>
            </div>
        </div>
    </div>
                            
                            <button type="submit" name="submit_payout" class="btn btn-primary mr-2">提交申请</button>
                            <button type="button" class="btn btn-light" onclick="window.history.back()">取消</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- content-wrapper ends -->
    <?php require_once('../database/footer.php'); ?>
</div>
