<?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>Manage Account</title>
    
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    
    <style>
        /* ==========================================
           1. ORIGINAL VANT UI SETTINGS
           ========================================== */
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif; -webkit-tap-highlight-color: transparent;}
        body { background-color: #f7f8fa; color: #333; max-width: 480px; margin: 0 auto; padding-top: 46px; }
        
        .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: center; z-index: 90; box-shadow: 0 1px 3px rgba(0,0,0,0.05);}
        .back-icon { position: absolute; left: 15px; font-size: 20px; color: #666; cursor: pointer; }
        .title { font-size: 16px; font-weight: 500; }

        .form-wrap { padding: 15px; }
        .info-alert { background: #fffbe8; color: #ed6a0c; font-size: 12px; padding: 10px 15px; border-radius: 8px; margin-bottom: 15px; display: flex; gap: 8px; align-items: center;}
        
        .input-group { background: #fff; border-radius: 8px; overflow: hidden; margin-bottom: 20px; }
        .input-box { display: flex; align-items: center; justify-content: space-between; padding: 15px; border-bottom: 1px solid #f5f5f5; position: relative;}
        .input-box:last-child { border-bottom: none; }
        .input-box label { width: 100px; font-size: 14px; color: #333; flex-shrink: 0;}
        .input-box input { border: none; outline: none; font-size: 14px; width: 100%; color: #333; background: transparent; }
        .input-box input::placeholder { color: #ccc; }
        
        /* Bank Selector Specific */
        .select-bank { flex: 1; font-size: 14px; color: #333; cursor: pointer; display: flex; justify-content: space-between; align-items: center;}
        .select-bank.empty { color: #ccc; }

        .submit-btn { width: 100%; background: linear-gradient(90deg, #ff7b7b, #f3595b); color: #fff; border: none; padding: 14px; border-radius: 25px; font-size: 15px; font-weight: 500; cursor: pointer; transition: 0.2s;}
        .submit-btn:disabled { background: #ebedf0; color: #c8c9cc; cursor: not-allowed; }
        .submit-btn:active { transform: scale(0.98); }

        .toast { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0,0,0,0.8); color: white; padding: 10px 20px; border-radius: 8px; font-size: 14px; z-index: 1000; }
        
        /* ==========================================
           2. BOTTOM SHEET (BANK SELECTOR)
           ========================================== */
        .overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 100; transition: opacity 0.3s; }
        .bottom-sheet { 
            position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; 
            height: 75vh; background: #fff; border-radius: 16px 16px 0 0; z-index: 101; 
            display: flex; flex-direction: column; transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .slide-enter-from, .slide-leave-to { transform: translate(-50%, 100%); }
        .fade-enter-from, .fade-leave-to { opacity: 0; }

        .bs-header { display: flex; justify-content: space-between; align-items: center; padding: 15px; border-bottom: 1px solid #f5f5f5; }
        .bs-title { font-size: 16px; font-weight: 500; }
        .bs-close { font-size: 20px; color: #999; cursor: pointer; }
        
        .bs-search { padding: 10px 15px; background: #f7f8fa; }
        .search-input { width: 100%; padding: 10px 15px; border-radius: 20px; border: none; outline: none; background: #fff; font-size: 13px; box-shadow: 0 1px 5px rgba(0,0,0,0.02);}
        
        .bs-list { flex: 1; overflow-y: auto; padding-bottom: 20px;}
        .bank-item { padding: 15px; border-bottom: 1px solid #f5f5f5; font-size: 14px; color: #333; cursor: pointer; transition: 0.2s;}
        .bank-item:active { background: #f9f9f9; }
        .bank-item.active { color: #f3595b; font-weight: bold; background: #fff5f5; }

        /* Loader */
        .page-loader { text-align: center; padding: 50px 0; color: #999; font-size: 14px;}
    </style>
</head>
<body>
    <div id="app">
        <div class="header">
            <div class="back-icon" @click="goBack()">&#10094;</div>
            <div class="title">{{ isEditing ? 'Edit' : 'Add' }} {{ typeName }}</div>
        </div>

        <div v-if="pageLoading" class="page-loader">
            Checking existing details...
        </div>

        <div v-else class="form-wrap">
            <div class="info-alert">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="#ed6a0c"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>
                Please bind your real account information carefully.
            </div>

            <div v-if="type === 'bank'" class="input-group">
                <div class="input-box" @click="showBankList = true">
                    <label>Bank Name</label>
                    <div class="select-bank" :class="{'empty': !form.bank_name}">
                        {{ form.bank_name || 'Please select a bank' }}
                        <span style="color:#ccc;">&#10095;</span>
                    </div>
                </div>
                <div class="input-box">
                    <label>Holder Name</label>
                    <input type="text" v-model="form.account_holder" placeholder="Enter account holder name">
                </div>
                <div class="input-box">
                    <label>Account No.</label>
                    <input type="number" v-model="form.account_no" placeholder="Enter account number">
                </div>
                <div class="input-box">
                    <label>IFSC Code</label>
                    <input type="text" v-model="form.ifsc_code" placeholder="Enter IFSC code" style="text-transform: uppercase;">
                </div>
            </div>

            <div v-if="type === 'upi'" class="input-group">
                <div class="input-box">
                    <label>UPI ID</label>
                    <input type="text" v-model="form.upi_id" placeholder="e.g. yourname@ybl">
                </div>
            </div>

            <div v-if="type === 'usdt'" class="input-group">
                <div class="input-box">
                    <label>USDT Addr.</label>
                    <input type="text" v-model="form.usdt_address" placeholder="Enter TRC20 Address">
                </div>
            </div>

            <button class="submit-btn" :disabled="!isFormValid || saving" @click="submitForm">
                {{ saving ? 'Saving...' : (isEditing ? 'Update Details' : 'Save Details') }}
            </button>
        </div>

        <transition name="fade">
            <div v-if="showBankList" class="overlay" @click="showBankList = false"></div>
        </transition>
        <transition name="slide">
            <div v-if="showBankList" class="bottom-sheet">
                <div class="bs-header">
                    <div class="bs-title">Select Bank</div>
                    <div class="bs-close" @click="showBankList = false">&#10005;</div>
                </div>
                <div class="bs-search">
                    <input type="text" v-model="searchQuery" class="search-input" placeholder="Search your bank name...">
                </div>
                <div class="bs-list">
                    <div v-if="filteredBanks.length === 0" style="text-align:center; padding: 20px; color:#999; font-size:13px;">
                        No bank found
                    </div>
                    <div v-for="b in filteredBanks" :key="b" 
                         class="bank-item" :class="{'active': form.bank_name === b}"
                         @click="selectBank(b)">
                        {{ b }}
                    </div>
                </div>
            </div>
        </transition>

        <div v-if="toastMsg" class="toast">{{ toastMsg }}</div>
    </div>

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

        createApp({
            setup() {
                const type = ref('bank');
                const pageLoading = ref(true);
                const saving = ref(false);
                const isEditing = ref(false);
                const toastMsg = ref('');
                
                // Bank List UI States
                const showBankList = ref(false);
                const searchQuery = ref('');

                // Comprehensive Indian Banks List
                const allBanks = [
                    "State Bank of India (SBI)", "HDFC Bank", "ICICI Bank", "Punjab National Bank (PNB)", 
                    "Axis Bank", "Bank of Baroda", "Canara Bank", "Union Bank of India", "Bank of India", 
                    "Indian Bank", "Central Bank of India", "Indian Overseas Bank", "UCO Bank", 
                    "Bank of Maharashtra", "Punjab & Sind Bank", "Kotak Mahindra Bank", "IndusInd Bank", 
                    "Yes Bank", "IDFC FIRST Bank", "Federal Bank", "South Indian Bank", 
                    "Paytm Payments Bank", "Airtel Payments Bank", "Jio Payments Bank", 
                    "Equitas Small Finance Bank", "Bandhan Bank", "Standard Chartered Bank"
                ].sort();

                // Form Data State
                const form = ref({
                    bank_name: '', account_holder: '', account_no: '', ifsc_code: '',
                    upi_id: '', usdt_address: ''
                });

                // Fetch Existing Data Logic
                const fetchExistingData = async () => {
                    try {
                        const res = await fetch('getwithrol.php');
                        const data = await res.json();
                        
                        if(data.success) {
                            if(type.value === 'bank' && data.bank) {
                                form.value.bank_name = data.bank.bank_name || '';
                                form.value.account_no = data.bank.account_no || '';
                                form.value.ifsc_code = data.bank.ifsc_code || '';
                                form.value.account_holder = data.bank.account_holder || ''; // Note: Ensure account_holder is selected in getwithrol.php
                                isEditing.value = true;
                            } 
                            else if(type.value === 'upi' && data.upi) {
                                form.value.upi_id = data.upi.upi_id || '';
                                isEditing.value = true;
                            }
                            else if(type.value === 'usdt' && data.usdt) {
                                form.value.usdt_address = data.usdt.usdt_address || '';
                                isEditing.value = true;
                            }
                        }
                    } catch (e) {
                        console.error('Error fetching data');
                    } finally {
                        pageLoading.value = false;
                    }
                };

                onMounted(() => {
                    const urlParams = new URLSearchParams(window.location.search);
                    const t = urlParams.get('type');
                    if(t === 'upi' || t === 'usdt' || t === 'bank') {
                        type.value = t;
                    }
                    // Fetch existing details
                    fetchExistingData();
                });

                // Computed filter for banks
                const filteredBanks = computed(() => {
                    if(!searchQuery.value) return allBanks;
                    return allBanks.filter(b => b.toLowerCase().includes(searchQuery.value.toLowerCase()));
                });

                const selectBank = (bName) => {
                    form.value.bank_name = bName;
                    showBankList.value = false;
                    searchQuery.value = ''; // reset search
                };

                const typeName = computed(() => {
                    if(type.value === 'bank') return 'Bank Card';
                    if(type.value === 'upi') return 'UPI ID';
                    if(type.value === 'usdt') return 'USDT Address';
                });

                const isFormValid = computed(() => {
                    if(type.value === 'bank') return form.value.bank_name && form.value.account_holder && form.value.account_no && form.value.ifsc_code;
                    if(type.value === 'upi') return form.value.upi_id;
                    if(type.value === 'usdt') return form.value.usdt_address;
                    return false;
                });

                const showToast = (msg) => {
                    toastMsg.value = msg;
                    setTimeout(() => toastMsg.value = '', 2000);
                }

                const goBack = () => window.history.back();

                const submitForm = async () => {
                    saving.value = true;
                    // Force uppercase for IFSC
                    if(form.value.ifsc_code) form.value.ifsc_code = form.value.ifsc_code.toUpperCase();
                    
                    const payload = { type: type.value, ...form.value };

                    try {
                        const response = await fetch('save_account.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(payload)
                        });
                        const result = await response.json();
                        
                        showToast(result.message);
                        
                        if(result.success) {
                            setTimeout(() => { window.location.href = 'withdraw.php'; }, 1500);
                        }
                    } catch (error) {
                        showToast('Network Error! Try again.');
                    }
                    saving.value = false;
                };

                return { 
                    type, typeName, form, isFormValid, pageLoading, saving, isEditing,
                    showBankList, searchQuery, filteredBanks, selectBank,
                    submitForm, goBack, toastMsg 
                };
            }
        }).mount('#app');
    </script>
</body>
</html>