<?php include __DIR__ . '/../header.php'; ?>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-4">
            <div class="card shadow border-0 rounded-4 mb-4">
                <div class="card-body text-center p-5">
                    <div class="bg-success text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-4" style="width: 80px; height: 80px;">
                        <i class="fas fa-user fs-1"></i>
                    </div>
                    <h3 class="fw-bold mb-0"><?php echo $user['username']; ?></h3>
                    <p class="text-muted"><?php echo __('member_since'); ?> <?php echo date('M Y', strtotime($user['created_at'])); ?></p>
                    <hr>
                    <div class="row g-0">
                        <div class="col-6 border-end">
                            <h4 class="fw-bold text-success mb-0"><?php echo number_format($user['points']); ?></h4>
                            <small class="text-muted text-uppercase"><?php echo __('points'); ?></small>
                        </div>
                        <div class="col-6">
                            <h4 class="fw-bold text-primary mb-0"><?php echo $user['total_referrals']; ?></h4>
                            <small class="text-muted text-uppercase"><?php echo __('referrals'); ?></small>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow border-0 rounded-4 mb-4">
                <div class="card-body p-4 text-center bg-light">
                    <h6 class="text-uppercase text-muted fw-bold mb-2"><?php echo __('balance'); ?></h6>
                    <h2 class="fw-bold text-success mb-3" id="user-balance">Rp <?php echo number_format($user['balance'], 0, ',', '.'); ?></h2>
                    <button class="btn btn-success btn-lg px-5 rounded-pill" data-bs-toggle="modal" data-bs-target="#withdrawModal">
                        <i class="fas fa-wallet me-2"></i> <?php echo __('withdraw'); ?>
                    </button>
                    <p class="small text-muted mt-3 mb-0"><?php echo __('min_withdraw'); ?>: Rp 10.000</p>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div id="alert-container">
                <?php if (isset($success)): ?>
                    <div class="alert alert-success border-0 rounded-4 mb-4"><?php echo $success; ?></div>
                <?php endif; ?>
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger border-0 rounded-4 mb-4"><?php echo $error; ?></div>
                <?php endif; ?>
            </div>

            <div class="card shadow border-0 rounded-4 mb-4">
                <div class="card-header bg-white py-3">
                    <h5 class="m-0 fw-bold"><?php echo __('referral_link'); ?></h5>
                </div>
                <div class="card-body p-4">
                    <p><?php echo __('referral_share_text'); ?></p>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control bg-light" id="refLink" value="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/?ref=' . $user['referral_code']; ?>" readonly>
                        <button class="btn btn-outline-success" type="button" onclick="copyText('refLink')"><?php echo __('copy_link'); ?></button>
                    </div>
                    <div class="small text-muted"><?php echo __('example_ref_link'); ?></div>
                    <div class="input-group">
                        <input type="text" class="form-control bg-light" value="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/apk/example-slug?ref=' . $user['referral_code']; ?>" readonly>
                    </div>
                </div>
            </div>

            <div class="card shadow border-0 rounded-4">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                    <h5 class="m-0 fw-bold"><?php echo __('withdrawal_history'); ?></h5>
                    <span class="badge bg-light text-dark"><?php echo __('recent_activities'); ?></span>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" id="withdrawal-table">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4"><?php echo __('date'); ?></th>
                                    <th><?php echo __('amount'); ?></th>
                                    <th><?php echo __('method'); ?></th>
                                    <th><?php echo __('status'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($withdrawals)): ?>
                                    <tr id="no-history-row">
                                        <td colspan="4" class="text-center py-5 text-muted"><?php echo __('no_history'); ?></td>
                                    </tr>
                                <?php endif; ?>
                                <?php foreach ($withdrawals as $wd): ?>
                                    <tr>
                                        <td class="ps-4"><?php echo date('d M Y, H:i', strtotime($wd['created_at'])); ?></td>
                                        <td class="fw-bold text-success">Rp <?php echo number_format($wd['amount'], 0, ',', '.'); ?></td>
                                        <td><?php echo $wd['method']; ?></td>
                                        <td>
                                            <?php 
                                                $statusClass = 'secondary';
                                                if ($wd['status'] === 'pending') $statusClass = 'warning';
                                                if ($wd['status'] === 'approved') $statusClass = 'success';
                                                if ($wd['status'] === 'rejected') $statusClass = 'danger';
                                            ?>
                                            <span class="badge bg-<?php echo $statusClass; ?>">
                                                <?php echo ucfirst($wd['status']); ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Withdraw Modal -->
<div class="modal fade" id="withdrawModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 rounded-4 overflow-hidden">
            <div class="modal-header bg-success text-white py-4 border-0">
                <h5 class="modal-title fw-bold"><?php echo __('request_withdrawal'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="withdraw-form" action="/withdraw" method="POST">
                <div class="modal-body p-4">
                    <div id="modal-alert"></div>
                    <div class="mb-3">
                        <label class="form-label fw-bold"><?php echo __('amount_to_withdraw'); ?></label>
                        <div class="input-group">
                            <span class="input-group-text">Rp</span>
                            <input type="number" class="form-control" name="amount" min="10000" max="<?php echo (int)$user['balance']; ?>" step="1000" placeholder="Min 10.000" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold"><?php echo __('payment_method'); ?></label>
                        <select class="form-select" name="method" required>
                            <option value=""><?php echo __('select_method'); ?></option>
                            <option value="DANA">DANA</option>
                            <option value="OVO">OVO</option>
                            <option value="GOPAY">GoPay</option>
                            <option value="ShopeePay">ShopeePay</option>
                            <option value="BANK">Bank Transfer</option>
                        </select>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold"><?php echo __('account_details'); ?></label>
                        <textarea class="form-control" name="details" rows="3" placeholder="<?php echo __('account_details_placeholder'); ?>" required></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light px-4 rounded-pill" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-success px-4 rounded-pill" id="withdraw-submit-btn"><?php echo __('submit_request'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function copyText(id) {
    var copyText = document.getElementById(id);
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(copyText.value);
    alert("<?php echo __('ref_copy_success_js'); ?>");
}

document.getElementById('withdraw-form').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = this;
    const btn = document.getElementById('withdraw-submit-btn');
    const modalAlert = document.getElementById('modal-alert');
    const alertContainer = document.getElementById('alert-container');
    const balanceEl = document.getElementById('user-balance');
    const tableBody = document.querySelector('#withdrawal-table tbody');
    const noHistoryRow = document.getElementById('no-history-row');

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...';

    const formData = new FormData(form);
    
    fetch('/withdraw', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<?php echo __('submit_request'); ?>';

        if (data.success) {
            // Update balance
            if (data.new_balance !== undefined) {
                balanceEl.textContent = 'Rp ' + data.new_balance.toLocaleString('id-ID');
            }

            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('withdrawModal'));
            modal.hide();

            // Show success message on main page
            alertContainer.innerHTML = '<div class="alert alert-success border-0 rounded-4 mb-4">' + data.success + '</div>';

            // Add to table (simplified, just reload or prepend)
            // For now, let's just prepend a row if we can
            if (noHistoryRow) noHistoryRow.remove();
            
            const now = new Date();
            const dateStr = now.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' }) + ', ' + 
                          now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' });
            
            const newRow = `<tr>
                <td class="ps-4">${dateStr}</td>
                <td class="fw-bold text-success">Rp ${parseInt(formData.get('amount')).toLocaleString('id-ID')}</td>
                <td>${formData.get('method')}</td>
                <td><span class="badge bg-warning">Pending</span></td>
            </tr>`;
            
            tableBody.insertAdjacentHTML('afterbegin', newRow);
            form.reset();
        } else {
            modalAlert.innerHTML = '<div class="alert alert-danger border-0 small">' + data.error + '</div>';
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerHTML = '<?php echo __('submit_request'); ?>';
        modalAlert.innerHTML = '<div class="alert alert-danger border-0 small">An error occurred. Please try again.</div>';
    });
});
</script>

<?php include __DIR__ . '/../footer.php'; ?>