<?php
require_once dirname(__DIR__, 2) . '/config.php';

$user_id = $_SESSION['user_id'];
$user = currentUser();

if ($user['is_agent'] != 1) {
    redirect('?page=dashboard');
}

$available_commission = $user['agent_total_commission'] - $user['agent_withdrawn'];

// 处理提现申请
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'withdraw') {
    $amount = floatval($_POST['amount'] ?? 0);
    $withdrawal_method = $_POST['withdrawal_method'] ?? '';
    $account = trim($_POST['account'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');
    
    if ($amount <= 0) {
        $error = '提现金额必须大于0';
    } elseif ($amount > $available_commission) {
        $error = '提现金额超过可提现佣金';
    } elseif (empty($withdrawal_method)) {
        $error = '请选择提现方式';
    } elseif (empty($account)) {
        $error = '请填写收款账号';
    } else {
        $amount = $db->escape($amount);
        $withdrawal_method = $db->escape($withdrawal_method);
        $account = $db->escape($account);
        $account_name = $db->escape($account_name);
        
        $db->query("INSERT INTO agent_withdrawals (agent_id, amount, withdrawal_method, account, account_name) 
                    VALUES ($user_id, $amount, '$withdrawal_method', '$account', '$account_name')");
        $success = '提现申请已提交，请等待管理员处理';
    }
}

// 获取提现记录
$withdrawals = $db->fetchAll("
    SELECT * FROM agent_withdrawals 
    WHERE agent_id = $user_id 
    ORDER BY id DESC LIMIT 20
");

// 状态映射
$status_map = [
    'pending' => '待处理',
    'processing' => '处理中',
    'completed' => '已完成',
    'rejected' => '已拒绝'
];
$status_class = [
    'pending' => 'status-pending',
    'processing' => 'status-processing',
    'completed' => 'status-completed',
    'rejected' => 'status-rejected'
];
?>

<div class="agent-withdraw-container">
    <div class="page-header">
        <h2>佣金提现</h2>
        <a href="?page=agent_dashboard" class="btn btn-secondary">返回控制台</a>
    </div>
    
    <div class="balance-card">
        <div class="balance-info">
            <span class="label">可提现佣金</span>
            <span class="amount">¥<?php echo number_format($available_commission, 2); ?></span>
        </div>
        <div class="balance-info">
            <span class="label">累计佣金</span>
            <span class="value">¥<?php echo number_format($user['agent_total_commission'], 2); ?></span>
        </div>
        <div class="balance-info">
            <span class="label">已提现</span>
            <span class="value">¥<?php echo number_format($user['agent_withdrawn'], 2); ?></span>
        </div>
    </div>
    
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    
    <div class="withdraw-card">
        <h3>申请提现</h3>
        <form method="POST">
            <input type="hidden" name="action" value="withdraw">
            <div class="form-group">
                <label>提现金额</label>
                <input type="number" name="amount" step="0.01" min="1" max="<?php echo $available_commission; ?>" required placeholder="请输入提现金额">
                <small>最低提现金额：¥1.00</small>
            </div>
            <div class="form-group">
                <label>提现方式</label>
                <select name="withdrawal_method" required>
                    <option value="">请选择</option>
                    <option value="alipay">支付宝</option>
                    <option value="wechat">微信支付</option>
                    <option value="bank">银行卡</option>
                </select>
            </div>
            <div class="form-group">
                <label>收款账号</label>
                <input type="text" name="account" required placeholder="支付宝账号/微信账号/银行卡号">
            </div>
            <div class="form-group">
                <label>收款人姓名</label>
                <input type="text" name="account_name" placeholder="真实姓名（银行卡提现必填）">
            </div>
            <button type="submit" class="btn btn-primary" <?php echo $available_commission < 1 ? 'disabled' : ''; ?>>提交提现申请</button>
        </form>
    </div>
    
    <div class="withdraw-history">
        <h3>提现记录</h3>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>申请时间</th>
                        <th>金额</th>
                        <th>提现方式</th>
                        <th>收款账号</th>
                        <th>状态</th>
                        <th>处理时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($withdrawals)): ?>
                        <tr><td colspan="6" style="text-align: center;">暂无提现记录</td></tr>
                    <?php else: ?>
                        <?php foreach ($withdrawals as $item): ?>
                            <tr>
                                <td><?php echo $item['created_at']; ?></td>
                                <td>¥<?php echo number_format($item['amount'], 2); ?></td>
                                <td><?php echo $item['withdrawal_method'] == 'alipay' ? '支付宝' : ($item['withdrawal_method'] == 'wechat' ? '微信支付' : '银行卡'); ?></td>
                                <td><?php echo htmlspecialchars($item['account']); ?></td>
                                <td><span class="status-badge <?php echo $status_class[$item['status']]; ?>"><?php echo $status_map[$item['status']]; ?></span></td>
                                <td><?php echo $item['processed_at'] ?: '-'; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.agent-withdraw-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
}
.balance-card {
    background: linear-gradient(135deg, var(--primary-light) 0%, var(--bg-primary) 100%);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    gap: 20px;
    border: 1px solid var(--border-color);
}
.balance-info {
    text-align: center;
}
.balance-info .label {
    display: block;
    font-size: 14px;
    color: var(--text-secondary);
    margin-bottom: 8px;
}
.balance-info .amount {
    font-size: 28px;
    font-weight: bold;
    color: var(--primary-color);
}
.balance-info .value {
    font-size: 20px;
    font-weight: 600;
}
.withdraw-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 30px;
    border: 1px solid var(--border-color);
}
.withdraw-card h3 {
    margin-bottom: 20px;
}
.withdraw-history h3 {
    margin-bottom: 15px;
}
.status-pending {
    background: #fef3c7;
    color: #92400e;
}
.status-processing {
    background: #d1fae5;
    color: #065f46;
}
.status-completed {
    background: #10b981;
    color: white;
}
.status-rejected {
    background: #fee2e2;
    color: #991b1b;
}
</style>