<?php
// --- SETTINGS BRIDGE ---
$settings_file = 'theme_settings.json';
$config = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : ['blur' => 12, 'hue' => 120];

// --- DYNAMIC PREVIEW OVERRIDE ---
$dynamic_hue = $_GET['hue'] ?? $config['hue'];
$dynamic_blur = $_GET['blur'] ?? $config['blur'];

// --- PREVIEW MODE START ---
$isPreview = isset($_GET['preview_region']);
if (!$isPreview) {
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header("Location: login.php");
        exit;
    }
}
// --- PREVIEW MODE END ---

$db = new PDO('sqlite:' . __DIR__ . '/app_feed.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// --- SESSION ID IDENTIFIER ---
$current_user_id = $isPreview ? 'preview_user' : $_SESSION['user_id'];

// --- LANGUAGE LOADING ---
$user_lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en';
$lang_file = "lang/{$user_lang}.php";
$lang = [];
if (file_exists($lang_file)) { include($lang_file); }

// --- DATA FETCH: Unified Query ---
$stmt = $db->prepare("
    SELECT u.*, s.withdrawal_locked, r.username
    FROM users u 
    LEFT JOIN user_registrations r ON u.id = r.id 
    LEFT JOIN user_settings s ON u.id = s.user_id
    WHERE u.id = ? LIMIT 1");
$stmt->execute([$current_user_id]);
$user_data = $stmt->fetch(PDO::FETCH_ASSOC);

// --- FORCE REFRESH: Fetch Lock Status directly from user_settings table ---
$stmt_lock = $db->prepare("SELECT withdrawal_locked FROM user_settings WHERE user_id = ?");
$stmt_lock->execute([$current_user_id]);
$lock_row = $stmt_lock->fetch(PDO::FETCH_ASSOC);
$is_withdrawal_locked = (int)($lock_row['withdrawal_locked'] ?? 0);

// Fallback values
$balance = (float)($user_data['balance'] ?? 0.00);

// --- DYNAMIC BACKGROUND LOGIC ---
$user_region = $isPreview ? $_GET['preview_region'] : (!empty($user_data['country_code']) ? strtolower($user_data['country_code']) : 'ng');
$stmt_bg = $db->prepare("SELECT setting_value FROM app_feed_settings WHERE setting_key = ?");
$stmt_bg->execute(['bg_dash_' . $user_region]);
$custom_bg = $stmt_bg->fetchColumn() ?: ($db->query("SELECT setting_value FROM app_feed_settings WHERE setting_key = 'bg_dash_default'")->fetchColumn() ?: 'http://localhost/1/5/image/dash.png');

// --- BANK DETAILS HANDLING ---
$bank_info = ['bank_name' => '', 'account_number' => '', 'swift_code' => ''];
$stmt_bank = $db->prepare("SELECT bank_name, account_number, swift_code FROM bank_details WHERE user_id = ?");
$stmt_bank->execute([$current_user_id]);
$result = $stmt_bank->fetch(PDO::FETCH_ASSOC);
if ($result) { $bank_info = $result; }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_bank'])) {
        $db->prepare("INSERT OR REPLACE INTO bank_details (user_id, bank_name, account_number, swift_code) VALUES (?, ?, ?, ?)")->execute([$current_user_id, $_POST['bank_name'], $_POST['account_number'], $_POST['swift_code']]);
        header("Location: cdashboard.php"); exit;
    }
    if (isset($_POST['clear_bank'])) {
        $db->prepare("DELETE FROM bank_details WHERE user_id = ?")->execute([$current_user_id]);
        header("Location: cdashboard.php"); exit;
    }
    if (isset($_POST['submit_withdrawal'])) {
        $amount = floatval($_POST['amount']);
        if ($amount > 0 && $amount <= $balance && !$is_withdrawal_locked) {
            $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?")->execute([$amount, $current_user_id]);
            $db->prepare("INSERT INTO transactions (user_id, amount_usd, status) VALUES (?, ?, 'Pending')")->execute([$current_user_id, $amount]);
            header("Location: cdashboard.php"); exit;
        }
    }
}

// --- UI CONFIGURATION ---
$display_name = !empty($user_data['username']) ? $user_data['username'] : ($user_data['name'] ?? 'Client');
$tier = $user_data['tier'] ?? 'Bronze Tier';
$colors = [
    'Bronze Tier' => ['main' => '#cd7f32', 'dark' => '#8b5a2b', 'light' => '#d98e3b'],
    'Silver Tier' => ['main' => '#c0c0c0', 'dark' => '#808080', 'light' => '#e0e0e0'],
    'Gold Tier'   => ['main' => '#ffd700', 'dark' => '#b8860b', 'light' => '#fff700']
];
$c = $colors[$tier] ?? $colors['Bronze Tier'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        :root { --blur: <?php echo $dynamic_blur; ?>px; --hue: <?php echo $dynamic_hue; ?>; }
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&display=swap');
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: #080b11; background-image: url('<?php echo $custom_bg; ?>?t=<?php echo time(); ?>'); background-size: cover; background-position: center; color: #fff; display: flex; justify-content: center; padding: 40px 20px; margin: 0; filter: hue-rotate(calc(var(--hue) * 1deg)); }
        .container { width: 100%; max-width: 440px; background: rgba(15, 22, 36, 0.6); backdrop-filter: blur(var(--blur)); padding: 32px; border-radius: 24px; border: 1px solid rgba(16, 185, 129, 0.4); box-shadow: 0 10px 25px rgba(0,0,0,0.5); }
        .monitor-circle { width: 120px; height: 120px; border: 5px solid #10b981; background: linear-gradient(145deg, <?php echo $c['light']; ?>, <?php echo $c['main']; ?>); border-radius: 50%; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 800; text-align: center; color: #fff; text-transform: uppercase; box-shadow: inset 0 -4px 0 <?php echo $c['dark']; ?>, 0 6px 10px rgba(0,0,0,0.4); }
        .tier-card { background: rgba(10, 15, 26, 0.9); padding: 20px; border-radius: 16px; border: 1px solid rgba(255,255,255,0.05); margin-top: 20px; }
        input { width: 100%; padding: 12px; margin: 10px 0; background: #0a0f1a; border: 1px solid #333; color: white; border-radius: 8px; box-sizing: border-box; }
        .btn { width: 100%; padding: 14px; background: <?php echo $c['main']; ?>; border: none; color: white; font-weight: 800; border-radius: 8px; cursor: pointer; box-shadow: 0 4px 0 <?php echo $c['dark']; ?>; text-decoration: none; text-align: center; display: block; }
        .btn:disabled { background: #333; cursor: not-allowed; }
    </style>
</head>
<body>
<div class="container">
    <div class="monitor-circle"><?php echo htmlspecialchars($tier); ?></div>
    <h2 style="text-align: center;"><?php echo $lang['welcome_msg'] ?? 'Welcome'; ?>, <?php echo htmlspecialchars($display_name); ?></h2>
    <div style="text-align: center; font-size: 24px; margin-bottom: 20px;"><?php echo $lang['balance_label'] ?? 'Balance'; ?>: $<?php echo number_format($balance, 2); ?></div>

    <div class="tier-card">
        <h4 style="margin-top:0;"><?php echo $lang['bank_details_title'] ?? 'International Bank Details'; ?></h4>
        <form method="POST">
            <input type="text" name="bank_name" placeholder="Bank Name" value="<?php echo htmlspecialchars($bank_info['bank_name'] ?? ''); ?>">
            <input type="text" name="account_number" placeholder="IBAN / Account Number" value="<?php echo htmlspecialchars($bank_info['account_number'] ?? ''); ?>">
            <input type="text" name="swift_code" placeholder="SWIFT / BIC Code" value="<?php echo htmlspecialchars($bank_info['swift_code'] ?? ''); ?>">
            <button type="submit" name="save_bank" class="btn" style="background: #333;"><?php echo $lang['save_bank_btn'] ?? 'Save Bank Details'; ?></button>
            <button type="submit" name="clear_bank" class="btn" style="background: #555; margin-top:10px;"><?php echo $lang['clear_bank_btn'] ?? 'Clear Bank Details'; ?></button>
        </form>
    </div>

    <div class="tier-card">
        <form method="POST">
            <input type="number" name="amount" step="0.01" placeholder="Enter amount to withdraw" required>
            <button type="submit" name="submit_withdrawal" class="btn" <?php echo ($is_withdrawal_locked) ? 'disabled' : ''; ?>>
                <?php 
                if ($is_withdrawal_locked) echo 'Withdrawals Locked';
                else echo $lang['request_withdrawal_btn'] ?? 'Request Withdrawal'; 
                ?>
            </button>
        </form>
    </div>
    
    <div style="margin-top:20px;">
        <a href="index.php" class="btn" style="background: #10b981;">Back to Index</a>
    </div>
</div>
</body>
</html>