<?php
$title='余额提现';
include __DIR__ . '/head.php';
$t = intval($conf['tixian']);
if($t==0)exit("<script>window.location.href='./index.php';</script>");
$is_tc = 0;
$is_rmb = 0;
if($t == 1 || $t == 3){ $is_rmb = 1; }
if($t == 2 || $t == 3){ $is_tc = 1; }
?>
<div class="grid grid-cols-1 lg:grid-cols-5 gap-4">
    <div class="lg:col-span-2">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
                <h3 class="font-medium text-gray-800 flex items-center">
                    <i class="fas fa-wallet text-indigo-500 mr-1.5"></i>
                    余额提现
                </h3>
            </div>
            <div class="p-4 space-y-4">
                <?php if($conf['tixian_gg']!=''): ?>
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-700"><?php echo $conf['tixian_gg']; ?></div>
                <?php endif; ?>

                <div class="grid grid-cols-2 gap-3">
                    <div class="bg-indigo-600 rounded-xl p-4 text-white">
                        <p class="text-sm text-indigo-200">账户余额</p>
                        <p class="text-2xl font-bold" id="_rmb"><?php echo $userrow['rmb'] ?></p>
                    </div>
                    <div class="bg-green-600 rounded-xl p-4 text-white">
                        <p class="text-sm text-green-200">账户佣金</p>
                        <p class="text-2xl font-bold" id="_tc"><?php echo $userrow['rmb_tc'] ?></p>
                    </div>
                </div>

                <?php if($conf['tc_to_rmb'] == 1): ?>
                <button type="button" onclick="tc_to_rmb()" class="w-full py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">
                    <i class="fas fa-exchange-alt mr-1"></i>佣金转移到余额
                </button>
                <?php endif; ?>

                <div class="bg-amber-50 border border-amber-200 rounded-lg p-3">
                    <p class="text-sm text-gray-700">
                        <i class="fas fa-info-circle text-amber-500 mr-1"></i>
                        每笔提现扣除 <strong class="text-red-600"><?php echo (100-$conf['tixian_rate'])?>%</strong> 手续费，
                        大于等于 <strong class="text-red-600"><?php echo $conf['tixian_min']; ?>元</strong> 可提现
                    </p>
                </div>

                <div>
                    <button type="button" onclick="togglePaymentConfig()" class="w-full flex items-center justify-between px-3 py-2.5 bg-gray-50 hover:bg-gray-100 rounded-lg transition-colors">
                        <span class="text-sm font-medium text-gray-700"><i class="fas fa-cog text-gray-500 mr-1.5"></i>收款信息配置</span>
                        <i class="fas fa-chevron-down text-gray-400 transition-transform" id="paymentConfigIcon"></i>
                    </button>
                    <div class="mt-3 hidden" id="paymentConfigContent">
                        <div class="space-y-3 p-3 bg-gray-50 rounded-lg">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">收款方式</label>
                                <select class="w-full px-3 py-2 bg-white border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" id="type">
                                    <option value="0">支付宝</option>
                                    <option value="1">微信</option>
                                    <option value="2">QQ</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">收款码</label>
                                <input type="file" class="w-full px-3 py-2 bg-white border border-gray-200 rounded-lg text-sm" id="pay_img" onchange="check_pay_img()">
                            </div>
                            <?php if($userrow['pay_img'] != ''): ?>
                            <div class="text-center"><img src="../<?php echo $userrow['pay_img']; ?>?time=<?php echo time(); ?>" class="rounded-lg" style="max-width:150px;"></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">提现金额</label>
                    <input type="number" class="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" id="rmb" placeholder="请输入提现金额">
                </div>

                <div class="grid grid-cols-2 gap-2">
                    <button type="button" onclick="tixian('rmb')" class="py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors" style="<?php echo $is_rmb==1?'':'display: none;'?>">
                        <i class="fas fa-wallet mr-1"></i>余额提现
                    </button>
                    <button type="button" onclick="tixian('tc')" class="py-2.5 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors" style="<?php echo $is_tc==1?'':'display: none;'?>">
                        <i class="fas fa-coins mr-1"></i>佣金提现
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="lg:col-span-3">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 flex items-center justify-between">
                <h3 class="font-medium text-gray-800 flex items-center">
                    <i class="fas fa-list-alt text-indigo-500 mr-1.5"></i>
                    提现记录
                </h3>
                <button type="button" onclick="refreshList()" class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 text-gray-500 transition-colors">
                    <i class="fas fa-redo text-sm"></i>
                </button>
            </div>
            <div class="p-4">
                <div class="hidden md:grid grid-cols-5 gap-2 items-center mb-3 pb-3 border-b border-gray-100 text-sm font-medium text-gray-600">
                    <div>提现金额</div>
                    <div>到账金额</div>
                    <div>状态</div>
                    <div>申请时间</div>
                    <div>到账时间</div>
                </div>
                <div class="space-y-2" id="list">
                    <div class="flex items-center justify-center py-8">
                        <div class="animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-indigo-500"></div>
                    </div>
                </div>
            </div>
            <div class="px-4 pb-4" id="pagination"></div>
        </div>
    </div>
</div>

<?php include 'foot.php'; ?>

<div id="appModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div id="modalBody" class="px-5 py-4 overflow-y-auto"></div>
            <div id="modalFooter" class="px-5 py-3 border-t border-gray-100 hidden"></div>
        </div>
    </div>
</div>

<script>
var pagesize = 30, currentPage = 1;

function openModal(title, content, footerCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    const modalFooter = document.getElementById('modalFooter');
    if (footerCallback) {
        modalFooter.innerHTML = footerCallback();
        modalFooter.classList.remove('hidden');
    } else {
        modalFooter.classList.add('hidden');
    }
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function togglePaymentConfig() {
    document.getElementById('paymentConfigContent').classList.toggle('hidden');
    document.getElementById('paymentConfigIcon').classList.toggle('rotate-180');
}

function tixian(type){
    var rmb=$('#rmb').val();
    if(!rmb){ showToast('请输入提现金额'); return; }
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=tixian',
        data: {type:type,rmb:rmb},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1){
                openModal('提示', data.msg, function(){ return '<button onclick="location.reload()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
            }else{ showToast(data.msg); }
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function fileUpload(){
    var fileObj = $("#pay_img")[0].files[0];
    if (!fileObj || fileObj.size <= 0) return;
    var formData = new FormData();
    formData.append("do","upload");
    formData.append("type","payimg");
    formData.append("file",fileObj);
    showLoading();
    $.ajax({
        url: "ajax.php?act=uploadimg",
        data: formData,
        type: "POST",
        dataType: "json",
        cache: false,
        processData: false,
        contentType: false,
        success: function(data) {
            hideLoading();
            if(data.code == 1){
                openModal('提示', data.msg, function(){ return '<button onclick="location.reload()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
            }else{ showToast(data.msg); }
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function loadList(page){
    currentPage = page;
    showLoading();
    $.ajax({
        type: 'POST',
        data: {pagesize:pagesize,page:page},
        url: 'ajax.php?act=get_tixian',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            renderTable(data.data);
            renderPagination(data.total, data.page, data.pagesize);
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function renderTable(data){
    $("#list").empty();
    if(data.length == 0){
        $("#list").html('<div class="text-center py-8 text-gray-400"><i class="fas fa-file-invoice-dollar text-3xl mb-2"></i><p class="text-sm">暂无提现记录</p></div>');
        return;
    }
    $.each(data, function(i,v){
        var status = getStatus(v.status, v.remark);
        var tmp = '<div class="bg-gray-50 rounded-lg p-3 text-sm">' +
            '<div class="grid grid-cols-2 gap-2 mb-2">' +
            '<div><span class="text-gray-500">提现：</span><span class="font-bold text-indigo-600">' + v.money + '</span></div>' +
            '<div><span class="text-gray-500">到账：</span><span class="font-bold text-green-600">' + v.realmoney + '</span></div></div>' +
            '<div class="space-y-1">' +
            '<div><span class="text-gray-500">状态：</span>' + status + '</div>' +
            '<div><span class="text-gray-500">申请：</span><span class="text-gray-700">' + v.addtime + '</span></div>' +
            '<div><span class="text-gray-500">到账：</span><span class="text-gray-700">' + (v.endtime || '-') + '</span></div></div></div>';
        $("#list").append(tmp);
    });
}

function getStatus(zt, msg){
    if(zt == 1) return '<span class="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">已到账</span>';
    if(zt == 2) return '<span class="px-2 py-0.5 bg-red-100 text-red-700 rounded text-xs">已退回(' + msg + ')</span>';
    return '<span class="px-2 py-0.5 bg-indigo-100 text-indigo-700 rounded text-xs">未结算</span>';
}

function renderPagination(total, page, pagesize){
    var totalPages = Math.ceil(total / pagesize);
    if(totalPages <= 1){ $('#pagination').html(''); return; }
    var html = '<div class="flex items-center justify-center gap-1">';
    html += '<button onclick="loadList(' + (page - 1) + ')" ' + (page == 1 ? 'disabled' : '') + ' class="px-2 py-1 rounded border border-gray-200 text-sm ' + (page == 1 ? 'opacity-50' : 'hover:bg-gray-100') + '"><i class="fas fa-chevron-left"></i></button>';
    for(var i = 1; i <= totalPages; i++){
        if(i == 1 || i == totalPages || (i >= page - 2 && i <= page + 2)){
            html += '<button onclick="loadList(' + i + ')" class="px-2 py-1 rounded border text-sm ' + (i == page ? 'bg-indigo-600 text-white border-indigo-600' : 'border-gray-200 hover:bg-gray-100') + '">' + i + '</button>';
        }else if(i == page - 3 || i == page + 3){
            html += '<span class="px-1 text-gray-400">...</span>';
        }
    }
    html += '<button onclick="loadList(' + (page + 1) + ')" ' + (page == totalPages ? 'disabled' : '') + ' class="px-2 py-1 rounded border border-gray-200 text-sm ' + (page == totalPages ? 'opacity-50' : 'hover:bg-gray-100') + '"><i class="fas fa-chevron-right"></i></button>';
    html += '</div>';
    $('#pagination').html(html);
}

function refreshList(){ loadList(currentPage); }

function check_pay_img(){
    openModal('提示', '文件已选择，请点击上传', function(){ return '<div class="flex gap-2"><button onclick="fileUpload()" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">上传</button><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button></div>'; });
}

function tc_to_rmb(){
    var rmb = $('#_rmb').html(), tc = $('#_tc').html();
    openModal('佣金转余额', '余额:'+rmb+'，佣金:'+tc+'<br><input type="text" id="tcAmount" class="w-full px-3 py-2 mt-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="请输入金额">', function(){ return '<div class="flex gap-2"><button onclick="submitTcToRmb()" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button></div>'; });
}

function submitTcToRmb() {
    var text = document.getElementById('tcAmount').value;
    var tc = $('#_tc').html();
    if(text > tc){ showToast('佣金不足'); return; }
    showLoading();
    $.post('ajax.php?act=tc_to_rmb', {tc:text}, function(d) {
        hideLoading();
        showToast(d.msg, d.code == 1 ? 'success' : 'error');
        if(d.code == 1){ $('#_tc').html(d.tc); $('#_rmb').html(d.rmb); closeModal(); }
    }, 'json');
}

$(document).ready(function(){ loadList(1); });
</script>
