<?php session_start(); ?>
<style>
    /* Modern Ledger Styling */
    body { margin: 0; padding: 0; background-color: #0f0f0f; font-family: 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
    .client-ledger-container { width: 100%; max-width: 600px; padding: 20px; }
    .card { background: #1a1a1a; padding: 30px; border-radius: 16px; color: #ffffff; border: 1px solid #333; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
    h2 { margin-top: 0; color: #fff; font-size: 1.5rem; margin-bottom: 25px; }
    .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 25px; }
    .stat-box { background: #252525; padding: 20px; border-radius: 12px; border: 1px solid #333; }
    .stat-label { display: block; font-size: 0.7rem; color: #888; text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 8px; }
    .stat-value { font-size: 1.6rem; font-weight: 700; }
    .badge { padding: 6px 14px; border-radius: 50px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; display: inline-block; }
    .badge-bronze { background: #cd7f32; color: #fff; }
    h3 { font-size: 1.1rem; color: #eee; margin-bottom: 15px; }
    input { width: 100%; padding: 14px; margin-bottom: 15px; border-radius: 8px; border: 1px solid #444; background: #222; color: white; box-sizing: border-box; }
    .btn-action { width: 100%; padding: 14px; border-radius: 8px; border: none; cursor: pointer; font-weight: 600; font-size: 1rem; transition: 0.3s; }
    .btn-enabled { background: #28a745; color: white; }
    .btn-disabled { background: #333; color: #777; cursor: not-allowed; }
</style>

<?php
$view = $view ?? 'client';
$user_data = $user_data ?? ['name' => 'Client', 'balance' => 0.00, 'tier' => 'Bronze Tier'];
$can_withdraw = $can_withdraw ?? false;

// FIX: Ensure current_user_id is dynamic based on session
$current_user_id = $_SESSION['user_id'] ?? 'user_001';

if (!isset($db)) {
    $db = new PDO('sqlite:app_feed.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // STABILIZATION: Increased timeout significantly for WAMP file system lag
    $db->setAttribute(PDO::ATTR_TIMEOUT, 30);
}

// FIX: Fetch the actual user data from the database
$stmt_user = $db->prepare("SELECT name, balance, tier, phone FROM users WHERE id = ?");
$stmt_user->execute([$current_user_id]);
$user_data = $stmt_user->fetch(PDO::FETCH_ASSOC) ?: $user_data;
$stmt_user = null; // Explicitly free handle

// SECONDARY LOOKUP: If name is empty, pull from registrations using the phone number
if (empty($user_data['name']) || $user_data['name'] === 'Client') {
    $stmt_reg = $db->prepare("SELECT username FROM user_registrations WHERE phone = ? LIMIT 1");
    $stmt_reg->execute([$user_data['phone'] ?? '']);
    $reg_data = $stmt_reg->fetch(PDO::FETCH_ASSOC);
    if ($reg_data) {
        $user_data['name'] = $reg_data['username'];
    }
    $stmt_reg = null; // Explicitly free handle
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $current_user_id;
    if (isset($_POST['save_details'])) {
        $stmt = $db->prepare("INSERT OR REPLACE INTO payout_methods (user_id, bank_name, account_number) VALUES (?, ?, ?)");
        $stmt->execute([$user_id, $_POST['bank'], $_POST['account']]);
        $stmt = null; // Explicitly free handle
    }
    if (isset($_POST['submit_withdrawal'])) {
        $amount = floatval($_POST['amount']);
        $stmt_check = $db->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt_check->execute([$user_id]);
        $curr_balance = $stmt_check->fetchColumn();
        $stmt_check = null; // Explicitly free handle
        
        if ($amount > 0 && $amount <= $curr_balance && $can_withdraw) {
            $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?")->execute([$amount, $user_id]);
            $stmt = $db->prepare("INSERT INTO transactions (user_id, amount_usd, status) VALUES (?, ?, 'Pending')");
            $stmt->execute([$user_id, $amount]);
            $stmt = null; // Explicitly free handle
        }
    }
}
$stmt_payout = $db->prepare("SELECT * FROM payout_methods WHERE user_id = ?");
$stmt_payout->execute([$current_user_id]);
$payout_info = $stmt_payout->fetch(PDO::FETCH_ASSOC);
$stmt_payout = null; // Explicitly free handle
?>

<?php if ($view === 'client'): ?>
<div class="client-ledger-container">
    <div class="card">
        <h2><?php echo htmlspecialchars($user_data['name'] ?? 'Client'); ?>'s Account Ledger</h2>
        <div class="grid-2">
            <div class="stat-box">
                <span class="stat-label">Balance</span>
                <div class="stat-value">$<?php echo number_format($user_data['balance'] ?? 0, 2); ?></div>
            </div>
            <div class="stat-box">
                <span class="stat-label">Current Rank</span>
                <div style="margin-top:8px;">
                    <?php 
                    $raw = $user_data['tier'] ?? 'Bronze Tier';
                    $rank_string = is_array($raw) ? (string)$raw : (string)$raw;
                    $css_slug = strtolower($rank_string);
                    ?>
                    <span class="badge badge-<?php echo htmlspecialchars($css_slug); ?>"><?php echo htmlspecialchars($rank_string); ?></span>
                </div>
            </div>
        </div>

        <hr style="border:0; border-top:1px solid #333; margin: 25px 0;">

        <h3>Setup Payout Account</h3>
        <form method="POST">
            <input type="text" name="bank" placeholder="Bank or MoMo Provider" value="<?php echo htmlspecialchars($payout_info['bank_name'] ?? ''); ?>" required>
            <input type="tel" name="account" placeholder="Account/Phone Number" value="<?php echo htmlspecialchars($payout_info['account_number'] ?? ''); ?>" required>
            <button type="submit" name="save_details" class="btn-action" style="background:#444; color:#fff;">Update Payout Method</button>
        </form>

        <div style="margin-top: 20px;">
            <?php if ($can_withdraw && $payout_info): ?>
                <form method="POST">
                    <input type="tel" name="amount" step="any" placeholder="Enter Amount to Withdraw" required>
                    <button type="submit" name="submit_withdrawal" class="btn-action btn-enabled">🔓 Request Withdrawal</button>
                </form>
            <?php else: ?>
                <button class="btn-action btn-disabled" disabled>
                    <?php echo !$payout_info ? '🔒 Payout Account Required' : '🔒 Withdrawal Locked'; ?>
                </button>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>