<?php
// 1. UTF-8 Header und Kodierung
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding("UTF-8");

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/lang_init.php'; 

try {
    $pdo->exec("SET NAMES 'utf8mb4'");
} catch (Exception $e) {}

require_login();
$userId = (int)$_SESSION['user_id'];

// --- LOGIK FÜR AKTIONEN (SWAP, RENAME, DELETE) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'swap_goals') {
        $fromId = (int)$_POST['from_goal'];
        $target = $_POST['to_goal']; 
        $amount = (float)str_replace(',', '.', $_POST['amount']);

        if ($amount > 0) {
            $pdo->beginTransaction();
            try {
                $stmtSource = $pdo->prepare("SELECT goal_name, current_amount FROM user_savings_goals WHERE id = ? AND user_id = ?");
                $stmtSource->execute([$fromId, $userId]);
                $sourceGoal = $stmtSource->fetch();

                if ($sourceGoal && (float)$sourceGoal['current_amount'] >= $amount) {
                    $fromName = $sourceGoal['goal_name'];
                    $pdo->prepare("UPDATE user_savings_goals SET current_amount = current_amount - ? WHERE id = ?")->execute([$amount, $fromId]);

                    if ($target === 'wallet') {
                        $pdo->prepare("UPDATE wallets SET balance = balance + ? WHERE user_id = ?")->execute([$amount, $userId]);
                        $desc = "Auszahlung: $fromName ➔ Wallet";
                    } else {
                        $toId = (int)$target;
                        if ($fromId !== $toId) {
                            $stmtTo = $pdo->prepare("SELECT goal_name FROM user_savings_goals WHERE id = ? AND user_id = ?");
                            $stmtTo->execute([$toId, $userId]);
                            $toName = $stmtTo->fetchColumn();
                            $pdo->prepare("UPDATE user_savings_goals SET current_amount = current_amount + ? WHERE id = ?")->execute([$amount, $toId]);
                            $desc = "Swap: $fromName ➔ $toName";
                        } else { throw new Exception("Source and target are the same."); }
                    }
                    $pdo->prepare("INSERT INTO wallet_transactions (user_id, amount, type, description, created_at) VALUES (?, ?, 'swap', ?, NOW())")->execute([$userId, $amount, $desc]);
                    $pdo->commit();
                    header("Location: dashboard.php?success=1"); exit;
                } else { $pdo->rollBack(); }
            } catch (Exception $e) { $pdo->rollBack(); }
        }
    }

    if ($action === 'rename_goal') {
        $goalId = (int)$_POST['goal_id'];
        $newName = htmlspecialchars(trim($_POST['new_name']));
        if (!empty($newName)) {
            $pdo->prepare("UPDATE user_savings_goals SET goal_name = ? WHERE id = ? AND user_id = ?")->execute([newName, $goalId, $userId]);
            header("Location: dashboard.php?success=rename"); exit;
        }
    }

    if ($action === 'delete_goal') {
        $goalId = (int)$_POST['goal_id'];
        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("SELECT current_amount, goal_name FROM user_savings_goals WHERE id = ? AND user_id = ? FOR UPDATE");
            $stmt->execute([$goalId, $userId]);
            $goal = $stmt->fetch();
            if ($goal) {
                $amount = (float)$goal['current_amount'];
                if ($amount > 0) {
                    $pdo->prepare("UPDATE wallets SET balance = balance + ? WHERE user_id = ?")->execute([$amount, $userId]);
                    $pdo->prepare("INSERT INTO wallet_transactions (user_id, amount, type, description, created_at) VALUES (?, ?, 'refund', ?, NOW())")->execute([$userId, $amount, "Goal Deleted: " . $goal['goal_name']]);
                }
                $pdo->prepare("DELETE FROM user_savings_goals WHERE id = ?")->execute([$goalId]);
                $pdo->commit();
                header("Location: dashboard.php?success=deleted"); exit;
            }
        } catch (Exception $e) { $pdo->rollBack(); }
    }
}

// --- DATENABFRAGEN ---
$stmtUser = $pdo->prepare("SELECT first_name, last_name, email FROM users WHERE id = ?");
$stmtUser->execute([$userId]);
$userData = $stmtUser->fetch(PDO::FETCH_ASSOC);
$cardHolderName = !empty($userData['first_name']) ? strtoupper($userData['first_name'] . " " . ($userData['last_name'] ?? '')) : strtoupper(explode('@', $userData['email'])[0]);

$pdo->prepare("INSERT IGNORE INTO wallets (user_id, balance) VALUES (?, 0)")->execute([$userId]);
$stmtW = $pdo->prepare("SELECT balance FROM wallets WHERE user_id = ?");
$stmtW->execute([$userId]);
$walletBalance = (float)$stmtW->fetchColumn();

$stmtOffers = $pdo->prepare("SELECT uc.id, uc.amount, u.email FROM user_credits uc JOIN users u ON u.id = uc.from_user WHERE uc.to_user = ? AND uc.status = 'pending' ORDER BY uc.created_at DESC");
$stmtOffers->execute([$userId]);
$incomingOffers = $stmtOffers->fetchAll(PDO::FETCH_ASSOC);

$stmtReceived = $pdo->prepare("SELECT uc.*, u.email, 'credit' as entry_type FROM user_credits uc JOIN users u ON u.id = uc.from_user WHERE uc.to_user = ? AND uc.status IN ('accepted', 'active', 'paid', 'repaid', 'completed', 'open', 'aktiv') ORDER BY uc.created_at DESC");
$stmtReceived->execute([$userId]);
$receivedCredits = $stmtReceived->fetchAll(PDO::FETCH_ASSOC);

$stmtGiven = $pdo->prepare("SELECT uc.*, u.email AS to_email, 'credit' as entry_type FROM user_credits uc JOIN users u ON u.id = uc.to_user WHERE uc.from_user = ? AND uc.status IN ('accepted', 'active', 'paid', 'repaid', 'completed', 'open', 'aktiv') ORDER BY uc.created_at DESC");
$stmtGiven->execute([$userId]);
$givenCredits = $stmtGiven->fetchAll(PDO::FETCH_ASSOC);

$stmtSwaps = $pdo->prepare("SELECT id, amount, description as email, created_at, 'swap' as entry_type, 'completed' as status FROM wallet_transactions WHERE user_id = ? AND type = 'swap' ORDER BY created_at DESC");
$stmtSwaps->execute([$userId]);
$swapHistory = $stmtSwaps->fetchAll(PDO::FETCH_ASSOC);

$stmtGoals = $pdo->prepare("SELECT * FROM user_savings_goals WHERE user_id = ? AND status = 'active' ORDER BY created_at DESC");
$stmtGoals->execute([$userId]);
$savingsGoals = $stmtGoals->fetchAll(PDO::FETCH_ASSOC);

function getStatusUI($status) {
    $s = strtolower(trim($status));
    switch($s) {
        case 'paid': case 'repaid': case 'completed': case 'bezahlt': case 'swap':
            return ['#10b981', __('status_paid'), 'check-circle'];
        case 'accepted': case 'active': case 'aktiv': case 'open':
            return ['#3b82f6', __('status_active'), 'activity'];
        default: return ['#64748b', ucfirst($s), 'info'];
    }
}
?>
<!DOCTYPE html>
<html lang="<?= $currentLang ?>" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <title><?= __('nav_dashboard') ?> – Pendlify</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, viewport-fit=cover">
    
    <style>
        :root {
          --blue: #3b82f6; --blue-glow: rgba(59, 130, 246, 0.5); --neon: #10b981; --text-muted: #64748b; --topnav-h: 65px;
          --bg-main: #020617; --text-main: #ffffff; --nav-bg: rgba(10, 15, 30, 0.9); --card-bg: rgba(255, 255, 255, 0.03); --border-color: rgba(255, 255, 255, 0.08);
        }
        [data-theme="light"] {
          --bg-main: #ffffff; --text-main: #020617; --nav-bg: rgba(255, 255, 255, 0.9); --card-bg: #f1f5f9; --border-color: #e2e8f0;
        }
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body { 
            background: var(--bg-main); color: var(--text-main); font-family: 'Inter', sans-serif;
            padding-top: calc(var(--topnav-h) + env(safe-area-inset-top, 20px));
            padding-bottom: calc(95px + env(safe-area-inset-bottom, 20px));
            min-height: 100vh; overflow-x: hidden; transition: all 0.3s ease;
        }
        .container { max-width: 480px; margin: 0 auto; padding: 0 20px; }
        
        /* Dashboard Cards & Layout */
        .glass-card { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 24px; padding: 20px; margin-bottom: 20px; backdrop-filter: blur(10px); }
        
        .credit-card { 
            width: 100%; aspect-ratio: 1.58 / 1; 
            background: linear-gradient(135deg, #1e293b, #0f172a); 
            border-radius: 20px; position: relative; padding: 25px; 
            box-shadow: 0 20px 40px rgba(0,0,0,0.4); border: 1px solid var(--border-color);
            margin-bottom: 30px; display: flex; flex-direction: column; justify-content: center;
        }
        [data-theme="light"] .credit-card { background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: white; }

        .action-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
        .action-btn { 
            background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 18px; 
            padding: 15px; text-align: center; text-decoration: none; color: var(--text-main);
            display: flex; flex-direction: column; align-items: center; gap: 8px; font-weight: 600; font-size: 13px;
        }
        
        /* Sparziele Style */
        .progress-bar-bg { background: rgba(148, 163, 184, 0.2); height: 10px; border-radius: 10px; overflow: hidden; margin-top: 10px; }
        .progress-bar-fill { background: linear-gradient(90deg, var(--neon), #34d399); height: 100%; border-radius: 10px; transition: width 1s ease; }
        
        /* History & Lists */
        .item-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--border-color); }
        .item-row:last-child { border-bottom: none; }
        
        /* Modal Overlay */
        .modal-overlay { 
            position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 20000; 
            display: none; align-items: center; justify-content: center; padding: 20px; backdrop-filter: blur(10px); 
        }
        .modal-body { background: var(--bg-main); border: 1px solid var(--border-color); border-radius: 28px; padding: 25px; width: 100%; max-width: 350px; text-align: center; }
        
        /* Buttons & Inputs */
        .btn-primary { background: var(--blue); color: white; border: none; padding: 12px 20px; border-radius: 14px; font-weight: 700; width: 100%; }
        .input-unified { background: var(--card-bg); border: 1px solid var(--border-color); color: var(--text-main); padding: 12px; border-radius: 12px; width: 100%; margin-bottom: 15px; }
    </style>
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body>

<?php if(file_exists(__DIR__ . '/includes/topnav.php')) include __DIR__ . '/includes/topnav.php'; ?>

<div class="container">
    <div class="credit-card">
        <div style="font-size: 10px; letter-spacing: 2px; opacity: 0.7; margin-bottom: 5px;">WALLET BALANCE</div>
        <div style="font-size: 32px; font-weight: 800; font-family: monospace;"><?= number_format($walletBalance, 2, ',', '.') ?> €</div>
        <div style="margin-top: auto; display: flex; justify-content: space-between; align-items: flex-end;">
            <div style="font-size: 12px; font-weight: 600;"><?= htmlspecialchars($cardHolderName) ?></div>
            <div style="font-weight: 900; font-style: italic; opacity: 0.2; font-size: 20px;">PENDLIFY</div>
        </div>
    </div>

    <div class="glass-card">
        <h3 style="font-size: 14px; margin-bottom: 15px; opacity: 0.8;"><i data-lucide="zap" style="color: #fbbf24; fill: #fbbf24;"></i> Quick Actions</h3>
        <div class="action-grid">
            <a href="transfer_send.php" class="action-btn"><i data-lucide="send" style="color: var(--blue);"></i><span>Senden</span></a>
            <a href="transfer_scan.php" class="action-btn"><i data-lucide="scan-line" style="color: var(--blue);"></i><span>Scannen</span></a>
            <div class="action-btn" onclick="document.getElementById('qr-modal').style.display='flex'"><i data-lucide="qr-code" style="color: var(--blue);"></i><span>Mein Code</span></div>
            <a href="wallet.php" class="action-btn"><i data-lucide="plus-circle" style="color: var(--blue);"></i><span>Aufladen</span></a>
        </div>
    </div>

    <div class="glass-card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <h3 style="font-size: 14px;"><i data-lucide="target" style="color: var(--neon);"></i> Sparziele</h3>
            <div style="display: flex; gap: 10px;">
                <button onclick="document.getElementById('swap-ui').style.display='block'" style="background:none; border:none; color:var(--blue);"><i data-lucide="refresh-cw" size="18"></i></button>
                <a href="goal_add.php" style="color:var(--blue);"><i data-lucide="plus-circle" size="18"></i></a>
            </div>
        </div>

        <div id="swap-ui" style="display:none; margin-bottom: 20px; padding: 15px; background: rgba(59,130,246,0.1); border-radius: 18px;">
            <form method="POST">
                <input type="hidden" name="action" value="swap_goals">
                <select name="from_goal" class="input-unified">
                    <?php foreach($savingsGoals as $g): ?>
                        <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['goal_name']) ?> (<?= number_format($g['current_amount'],2) ?>€)</option>
                    <?php endforeach; ?>
                </select>
                <select name="to_goal" class="input-unified">
                    <option value="wallet">Wallet</option>
                    <?php foreach($savingsGoals as $g): ?>
                        <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['goal_name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="number" name="amount" step="0.01" placeholder="Betrag" class="input-unified" required>
                <button type="submit" class="btn-primary">Transferieren</button>
            </form>
        </div>

        <?php foreach ($savingsGoals as $goal): 
            $percent = ($goal['target_amount'] > 0) ? min(100, round(($goal['current_amount'] / $goal['target_amount']) * 100)) : 0;
        ?>
            <div style="margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; font-size: 13px; font-weight: 700; margin-bottom: 5px;">
                    <span><?= htmlspecialchars($goal['goal_name']) ?></span>
                    <span style="color: var(--neon);"><?= number_format($goal['current_amount'], 2, ',', '.') ?> €</span>
                </div>
                <div class="progress-bar-bg"><div class="progress-bar-fill" style="width: <?= $percent ?>%;"></div></div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="glass-card">
        <h3 style="font-size: 14px; margin-bottom: 15px;"><i data-lucide="activity"></i> Aktivität</h3>
        <?php 
        $all = array_merge($receivedCredits, $givenCredits, $swapHistory);
        usort($all, function($a, $b) { return strtotime($b['created_at']) - strtotime($a['created_at']); });
        foreach (array_slice($all, 0, 10) as $c): 
            $isBorrower = ($c['entry_type'] !== 'swap' && (int)$c['to_user'] === $userId);
        ?>
            <div class="item-row">
                <div style="display: flex; gap: 12px; align-items: center;">
                    <div style="padding: 8px; border-radius: 10px; background: var(--card-bg);"><i data-lucide="arrow-<?= $isBorrower ? 'down-left' : 'up-right' ?>" size="16"></i></div>
                    <div>
                        <div style="font-size: 13px; font-weight: 600;"><?= htmlspecialchars($c['email'] ?? 'Transfer') ?></div>
                        <div style="font-size: 10px; color: var(--text-muted);"><?= date('d. M, H:i', strtotime($c['created_at'])) ?></div>
                    </div>
                </div>
                <div style="font-weight: 700; font-size: 14px; color: <?= $isBorrower ? 'var(--neon)' : 'var(--text-main)' ?>;">
                    <?= ($isBorrower ? '+' : '-') ?> <?= number_format($c['amount'], 2, ',', '.') ?> €
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div id="qr-modal" class="modal-overlay" onclick="this.style.display='none'">
    <div class="modal-body" onclick="event.stopPropagation()">
        <h3 style="margin-bottom: 20px;">Empfangen</h3>
        <div style="background: white; padding: 15px; border-radius: 20px; display: inline-block;">
            <img src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=<?= urlencode($userData['email']) ?>" style="display: block;">
        </div>
        <p style="margin-top: 15px; font-weight: 600; opacity: 0.7;"><?= htmlspecialchars($userData['email']) ?></p>
        <button onclick="document.getElementById('qr-modal').style.display='none'" class="btn-primary" style="margin-top: 20px; background: var(--card-bg); color: var(--text-main);">Schließen</button>
    </div>
</div>

<?php if(file_exists(__DIR__ . '/includes/bottomnav.php')) include __DIR__ . '/includes/bottomnav.php'; ?>

<script>
    lucide.createIcons();
    // Beispiel für Theme-Switch (kannst du an deine Logik anpassen)
    // document.documentElement.setAttribute('data-theme', 'light');
</script>
</body>
</html>
