<?php
session_start();
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Withdraw</title>
    
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <style>
        /* ==========================================
           1. ORIGINAL VANT UI SETTINGS (Flat Design)
           ========================================== */
        * {
            margin: 0; padding: 0; box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Segoe UI, Arial, sans-serif;
            -webkit-tap-highlight-color: transparent;
        }
        body { background-color: #f7f8fa; color: #333; max-width: 480px; margin: 0 auto; padding-top: 46px; padding-bottom: 30px; }
        a { text-decoration: none; color: inherit; }
        input[type=number]::-webkit-inner-spin-button, 
        input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }

        /* ==========================================
           2. HEADER (Flat White)
           ========================================== */
        .header {
            position: fixed; top: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px;
            height: 46px; background: #fff; display: flex; align-items: center; justify-content: space-between;
            padding: 0 15px; z-index: 99; color: #333;
        }
        .back-icon { font-size: 20px; font-weight: 300; cursor: pointer; color: #666; }
        .title { font-size: 16px; font-weight: 500; position: absolute; left: 50%; transform: translateX(-50%); }
        .history-link { font-size: 12px; color: #666; cursor: pointer; }

        /* ==========================================
           3. RED BALANCE CARD
           ========================================== */
        .card-wrap { padding: 15px 15px 0; }
        .balance-card {
            background: linear-gradient(90deg, #ff7b7b, #f3595b);
            border-radius: 10px; padding: 20px 15px; color: #fff;
            position: relative; overflow: hidden;
        }
        .bc-title { font-size: 12px; display: flex; align-items: center; gap: 5px; opacity: 0.9; margin-bottom: 5px; }
        .bc-title svg { width: 14px; height: 14px; fill: #f1c40f; }
        .bc-amt { font-size: 24px; font-weight: 500; display: flex; align-items: center; gap: 8px; }
        .refresh-icon { width: 16px; height: 16px; fill: #fff; cursor: pointer; }
        .spin { animation: rotation 0.6s linear; }
        @keyframes rotation { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        .card-pattern { position: absolute; right: 15px; bottom: 15px; font-size: 14px; opacity: 0.5; letter-spacing: 2px; }

        /* ==========================================
           4. FLAT PAYMENT TABS
           ========================================== */
        .tabs { display: flex; gap: 10px; padding: 15px; }
        .tab-item {
            flex: 1; background: #fff; border-radius: 8px; padding: 12px 0;
            display: flex; flex-direction: column; align-items: center; gap: 5px;
            cursor: pointer; border: 1px solid transparent; transition: 0.2s;
        }
        .tab-item.active { border-color: #f3595b; }
        .tab-item.active .tab-name { color: #f3595b; }
        .tab-icon { width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; }
        .tab-name { font-size: 11px; color: #999; font-weight: 500; text-transform: uppercase;}

        /* ==========================================
           5. ACCOUNT AREA
           ========================================== */
        .account-area { padding: 0 15px 15px; }
        .saved-box {
            background: #fff; border-radius: 8px; padding: 15px; display: flex; justify-content: space-between;
            align-items: center; cursor: pointer;
        }
        .acc-left { display: flex; align-items: center; gap: 10px; }
        .acc-text { display: flex; flex-direction: column; gap: 2px; }
        .acc-name { font-size: 13px; color: #333; font-weight: 500;}
        .acc-num { font-size: 12px; color: #999; }
        
        .add-box {
            background: #fff; border-radius: 8px; padding: 20px; display: flex; flex-direction: column;
            align-items: center; justify-content: center; gap: 8px; cursor: pointer;
        }
        .add-icon-wrap { width: 40px; height: 30px; border: 1px dashed #ccc; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #ccc; font-size: 20px; font-weight: 300;}
        .add-text { font-size: 12px; color: #999; }
        .warning-text { font-size: 11px; color: #f3595b; margin-top: 10px; }

        /* ==========================================
           6. INPUT SECTION
           ========================================== */
        .input-wrap { background: #fff; border-radius: 8px; margin: 0 15px 15px; padding: 15px; }
        .input-row { display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #f5f5f5; padding-bottom: 10px; margin-bottom: 15px; }
        .input-row span { font-size: 18px; color: #f3595b; font-weight: 500; }
        .input-row input { border: none; outline: none; font-size: 16px; width: 100%; color: #333; font-weight: 500;}
        .input-row input::placeholder { color: #f3595b; opacity: 0.5; font-size: 14px; font-weight: normal;}

        .bal-row { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: #999; margin-bottom: 15px; }
        .bal-val { color: #f3595b; margin-left: 5px; }
        .btn-all { border: 1px solid #f3595b; color: #f3595b; background: #fff; border-radius: 15px; padding: 2px 15px; font-size: 12px; cursor: pointer; }

        .receive-row { display: flex; justify-content: space-between; font-size: 12px; color: #999; margin-bottom: 20px; }
        .receive-val { color: #f3595b; font-weight: 500; }

        .btn-withdraw {
            width: 100%; background: #ebedf0; color: #c8c9cc; border: none; border-radius: 20px;
            padding: 12px; font-size: 14px; font-weight: 500; transition: 0.3s; cursor: not-allowed;
        }
        .btn-withdraw.active { background: linear-gradient(90deg, #ff7b7b, #f3595b); color: #fff; cursor: pointer;}
        .btn-withdraw.active:active { opacity: 0.8; }

        /* ==========================================
           7. RULES SECTION
           ========================================== */
        .rules { padding: 0 15px 20px; }
        .rule-item { font-size: 11px; color: #999; line-height: 1.6; display: flex; align-items: flex-start; gap: 5px; margin-bottom: 2px; }
        .diamond { color: #f3595b; font-size: 12px; line-height: 1.2; }
        .rule-item span { color: #f3595b; }

        /* ==========================================
           8. HISTORY SECTION
           ========================================== */
        .history { background: #fff; padding: 15px; min-height: 200px; }
        .h-title { font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 5px; border-left: 3px solid #f3595b; padding-left: 8px; margin-bottom: 15px; }
        .empty-box { display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 30px 0; color: #999; font-size: 12px; }
        
        .hist-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #f5f5f5; }
        .hist-amt { font-size: 14px; color: #333; font-weight: 500;}
        .hist-date { font-size: 11px; color: #999; margin-top: 3px; }
        .hist-status { font-size: 12px; font-weight: 500; text-transform: capitalize;}
        .text-green { color: #07c160; }
        .text-orange { color: #ff976a; }
        .text-red { color: #ee0a24; }
    </style>
</head>
<body>

    <div id="app">
        <div class="header">
            <div class="back-icon" @click="goBack()">&#10094;</div>
            <div class="title">Withdraw</div>
            <div class="history-link" onclick="window.location.href='withdraw_history.php'">Withdrawal history</div>
        </div>

        <div class="card-wrap">
            <div class="balance-card">
                <div class="bc-title">
                    <svg viewBox="0 0 24 24"><path d="M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.11.89-2 2-2h14c1.1 0 2 .89 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-2.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/></svg>
                    Available balance
                </div>
                <div class="bc-amt">
                    ₹<span>{{ balance }}</span>
                    <svg class="refresh-icon" :class="{'spin': refreshing}" @click="fetchData()" viewBox="0 0 24 24"><path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>
                </div>
                <div class="card-pattern">•••• &nbsp; ••••</div>
            </div>
        </div>

        <div class="tabs">
            <div class="tab-item" :class="{'active': method === 'bank'}" @click="method = 'bank'">
                <div class="tab-icon">
                    <svg width="28" height="28" viewBox="0 0 40 40"><rect x="4" y="8" width="32" height="24" rx="4" fill="#f3595b"/><rect x="4" y="14" width="32" height="6" fill="#f1c40f"/><rect x="8" y="24" width="8" height="3" fill="#fff"/></svg>
                </div>
                <div class="tab-name">BANK CARD</div>
            </div>
            <div class="tab-item" :class="{'active': method === 'upi'}" @click="method = 'upi'">
                <div class="tab-icon">
                    <svg width="28" height="28" viewBox="0 0 40 40"><rect x="4" y="8" width="32" height="24" rx="4" fill="none" stroke="#ccc" stroke-width="2"/><text x="20" y="24" font-size="10" fill="#666" text-anchor="middle" font-family="Arial" font-weight="bold">UPI</text></svg>
                </div>
                <div class="tab-name">UPI</div>
            </div>
            <div class="tab-item" :class="{'active': method === 'usdt'}" @click="method = 'usdt'">
                <div class="tab-icon">
                    <svg width="28" height="28" viewBox="0 0 40 40"><circle cx="20" cy="20" r="14" fill="#26a17b"/><path d="M20 12c-3.3 0-6 1-6 2.2s2.7 2.2 6 2.2 6-1 6-2.2-2.7-2.2-6-2.2zm2.2 5.2v6h-4.4v-6H14v-1.5h12v1.5h-3.8z" fill="#fff"/></svg>
                </div>
                <div class="tab-name">USDT</div>
            </div>
        </div>

        <div class="account-area">
            <template v-if="loading">
                <div style="text-align:center; color:#999; font-size:12px; padding:20px;">Loading data...</div>
            </template>
            <template v-else>
                <template v-if="method === 'bank'">
                    <div v-if="savedData.bank" class="saved-box" @click="goToAdd('bank')">
                        <div class="acc-left">
                            <svg width="30" height="30" fill="#f3595b" viewBox="0 0 24 24"><path d="M12 2l-10 5v2h20V7l-10-5zm-6 9v7h2v-7H6zm5 0v7h2v-7h-2zm5 0v7h2v-7h-2zM2 20v2h20v-2H2z"/></svg>
                            <div class="acc-text">
                                <div class="acc-name">{{ savedData.bank.bank_name }}</div>
                                <div class="acc-num">{{ maskAccount(savedData.bank.account_no) }}</div>
                            </div>
                        </div>
                        <div style="color:#ccc; font-weight:bold;">&#10095;</div>
                    </div>
                    <div v-else class="add-box" @click="goToAdd('bank')">
                        <div class="add-icon-wrap">+</div>
                        <div class="add-text">Add a bank account</div>
                    </div>
                </template>

                <template v-if="method === 'upi'">
                    <div v-if="savedData.upi" class="saved-box" @click="goToAdd('upi')">
                        <div class="acc-left">
                            <svg width="30" height="30" fill="#4A90E2" viewBox="0 0 24 24"><path d="M3 5v14h18V5H3zm16 12H5V7h14v10zm-6-8h-2v4H9v-4H7v6h8V9z"/></svg>
                            <div class="acc-text">
                                <div class="acc-name">UPI</div>
                                <div class="acc-num">{{ savedData.upi.upi_id }}</div>
                            </div>
                        </div>
                        <div style="color:#ccc; font-weight:bold;">&#10095;</div>
                    </div>
                    <div v-else>
                        <div class="add-box" @click="goToAdd('upi')">
                            <div class="add-icon-wrap">+</div>
                            <div class="add-text">Add UPI</div>
                        </div>
                        <div class="warning-text">Need to add beneficiary information to be able to withdraw money</div>
                    </div>
                </template>

                <template v-if="method === 'usdt'">
                    <div v-if="savedData.usdt" class="saved-box" @click="goToAdd('usdt')">
                        <div class="acc-left">
                            <svg width="30" height="30" fill="#26a17b" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.5 9h-1.5v5h-2v-5H9.5V9.5h5V11z"/></svg>
                            <div class="acc-text">
                                <div class="acc-name">USDT Address</div>
                                <div class="acc-num">{{ savedData.usdt.usdt_address }}</div>
                            </div>
                        </div>
                        <div style="color:#ccc; font-weight:bold;">&#10095;</div>
                    </div>
                    <div v-else>
                        <div class="add-box" @click="goToAdd('usdt')">
                            <div class="add-icon-wrap">+</div>
                            <div class="add-text">Add USDT address</div>
                        </div>
                        <div class="warning-text">Need to add beneficiary information to be able to withdraw money</div>
                    </div>
                </template>
            </template>
        </div>

        <div class="input-wrap">
            <div class="input-row">
                <span>{{ currencySymbol }}</span>
                <input type="number" v-model="amount" :placeholder="method === 'usdt' ? 'Please enter USDT amount' : 'Please enter the amount'">
            </div>
            
            <div class="bal-row">
                <div>Withdrawable balance <span class="bal-val">₹{{ balance }}</span></div>
                <button class="btn-all" @click="amount = balance">All</button>
            </div>
            
            <div class="receive-row">
                <div>Withdrawal amount received</div>
                <div class="receive-val">{{ currencySymbol }}{{ receivedAmount }}</div>
            </div>
            
            <button class="btn-withdraw" :class="{'active': isSubmitValid}" :disabled="!isSubmitValid || submitting" @click="submitWithdraw">{{ submitting ? 'Submitting...' : 'Withdraw' }}</button>
        </div>

        <div class="rules">
            <div class="rule-item">
                <div class="diamond">&#9830;</div>
                <div>Need to bet <span>₹0.00</span> to be able to withdraw</div>
            </div>
            <div class="rule-item">
                <div class="diamond">&#9830;</div>
                <div>Withdraw time <span>00:00-23:59</span></div>
            </div>
            <div class="rule-item">
                <div class="diamond">&#9830;</div>
                <div>Inday Remaining Withdrawal Times <span>3</span></div>
            </div>
            <div class="rule-item">
                <div class="diamond">&#9830;</div>
                <div>Withdrawal amount range <span>₹{{ minWithdraw.toFixed(2) }}-₹50,000.00</span></div>
            </div>
            <div class="rule-item">
                <div class="diamond">&#9830;</div>
                <div>Please confirm your beneficial account information before withdrawing. If your information is incorrect, our company will not be liable for the amount of loss</div>
            </div>
            <div class="rule-item">
                <div class="diamond">&#9830;</div>
                <div>If your beneficial information is incorrect, please contact customer service</div>
            </div>
        </div>

        <div class="history">
            <div class="h-title">Withdrawal history</div>
            
            <div v-if="loading" style="text-align:center; padding:20px; color:#999; font-size:12px;">Loading...</div>
            <div v-else-if="history.length === 0" class="empty-box">
                <svg width="100" height="80" viewBox="0 0 100 80" fill="#ebedf0"><path d="M20 20h60v40H20z"/><path d="M10 30h80v10H10z" fill="#dcdee0"/><path d="M30 45h40v4H30zm0 10h20v4H30z" fill="#c8c9cc"/></svg>
                No data
            </div>
            <div v-else>
                <div v-for="(item, index) in history" :key="index" class="hist-item">
                    <div>
                        <div class="hist-amt">₹{{ parseFloat(item.amount).toFixed(2) }}</div>
                        <div class="hist-date">{{ item.created_at }}</div>
                    </div>
                    <div class="hist-status" :class="getStatusColor(item.status)">{{ item.status }}</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, computed, onMounted } = Vue;

        createApp({
            setup() {
                const balance = ref("0.00");
                const minWithdraw = ref(110);
                const method = ref('bank'); // bank, upi, usdt
                const savedData = ref({ bank: null, upi: null, usdt: null });
                const history = ref([]);
                const amount = ref('');
                const loading = ref(true);
                const refreshing = ref(false);
                const submitting = ref(false);

                const fetchData = async () => {
                    refreshing.value = true;
                    try {
                        const res = await fetch('getwithrol.php');
                        const data = await res.json();
                        if(data.success) {
                            balance.value = data.balance;
                            minWithdraw.value = parseFloat(data.min_withdraw);
                            savedData.value.bank = data.bank;
                            savedData.value.upi = data.upi;
                            savedData.value.usdt = data.usdt;
                            history.value = data.history || [];
                        }
                    } catch (e) {
                        console.error("API Error", e);
                    }
                    loading.value = false;
                    setTimeout(() => refreshing.value = false, 500);
                };

                onMounted(() => {
                    fetchData();
                });

                // Computed Properties
                const currencySymbol = computed(() => method.value === 'usdt' ? '₮' : '₹');
                
                const receivedAmount = computed(() => {
                    const val = parseFloat(amount.value);
                    return val > 0 ? val.toFixed(2) : '0.00';
                });

                const isSubmitValid = computed(() => {
                    const val = parseFloat(amount.value) || 0;
                    const bal = parseFloat(balance.value) || 0;
                    let hasAcc = false;
                    if(method.value === 'bank' && savedData.value.bank) hasAcc = true;
                    if(method.value === 'upi' && savedData.value.upi) hasAcc = true;
                    if(method.value === 'usdt' && savedData.value.usdt) hasAcc = true;

                    return val >= minWithdraw.value && val <= bal && hasAcc;
                });

                // Helpers
                const goBack = () => window.history.back();
                const goToAdd = (type) => window.location.href = `add_account.php?type=${type}`;
                
                const maskAccount = (acc) => {
                    if(!acc) return '';
                    return acc.replace(/.(?=.{4})/g, '*');
                };

                const getStatusColor = (status) => {
                    if(status === 'approved' || status == 1) return 'text-green';
                    if(status === 'rejected' || status == 2) return 'text-red';
                    return 'text-orange'; // pending
                };

                const getDetailId = () => {
                    if(method.value === 'bank' && savedData.value.bank) return savedData.value.bank.id || 0;
                    if(method.value === 'upi' && savedData.value.upi) return savedData.value.upi.id || 0;
                    if(method.value === 'usdt' && savedData.value.usdt) return savedData.value.usdt.id || 0;
                    return 0;
                };

                const submitWithdraw = async () => {
                    if(!isSubmitValid.value || submitting.value) return;
                    submitting.value = true;
                    try {
                        const res = await fetch('submit_withdraw.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                amount: parseFloat(amount.value),
                                method: method.value,
                                detail_id: getDetailId()
                            })
                        });
                        const data = await res.json();
                        if(data.success) {
                            amount.value = '';
                            fetchData();
                            alert(data.message || 'Request submitted.');
                        } else {
                            alert(data.message || 'Failed to submit.');
                        }
                    } catch (e) {
                        alert('Network error.');
                    }
                    submitting.value = false;
                };

                return {
                    balance, minWithdraw, method, savedData, history, amount, 
                    loading, refreshing, submitting, currencySymbol, receivedAmount, isSubmitValid,
                    fetchData, goBack, goToAdd, maskAccount, getStatusColor, submitWithdraw
                };
            }
        }).mount('#app');
    </script>
</body>
</html>