<?php
	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';
	if (empty($_SESSION['logged_in'])) {
		header('Location: https://togethere.cloud/login/');
		exit();
	}

	// Połączenie z bazą danych
	$host = "localhost";
	$db = "togethere_cloud";
	$user = "root";
	$pass = "HasloDoSQL";

	try {
		$pdo = og_session_get_pdo();
		if (!$pdo instanceof PDO) {
			throw new PDOException('Nie udało się zainicjalizować połączenia z bazą danych.');
		}
	} catch (PDOException $e) {
		die("Błąd połączenia z bazą danych: " . $e->getMessage());
	}

	// Pobieranie statystyk użytkownika
	$user_id = $_SESSION['user_id'];
	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/account_suspension.php';
	$suspensionState = og_is_current_user_suspended($pdo);
	$isSuspended = (bool)($suspensionState['is_suspended'] ?? false);
	$suspendedReason = (string)($suspensionState['reason'] ?? '');
	$suspendedUntil = (string)($suspensionState['suspended_until'] ?? '');
	$stmt = $pdo->prepare("SELECT * FROM user_stats WHERE user_id = ?");
	$stmt->execute([$user_id]);
	$stats = $stmt->fetch(PDO::FETCH_ASSOC);

	// Jeśli nie ma statystyk (stary użytkownik), utwórz rekord
	if (!$stats) {
		$stmt_create = $pdo->prepare("INSERT INTO user_stats (user_id, balance, matches_played, matches_won, matches_lost, matches_draw, tournaments_played, tournaments_won, leagues_participated, total_income, total_expenses, total_transactions, account_status)
		VALUES (?, 0.00, 0, 0, 0, 0, 0, 0, 0, 0.00, 0.00, 0, 'active')");
		$stmt_create->execute([$user_id]);
		
		// Pobierz ponownie
		$stmt->execute([$user_id]);
		$stats = $stmt->fetch(PDO::FETCH_ASSOC);
	}

	// Formatowanie wartości
	$balance = number_format($stats['balance'], 2, '.', '');
	$total_income = number_format($stats['total_income'], 2, '.', '');
	$total_expenses = number_format($stats['total_expenses'], 2, '.', '');
	$decisive_matches = ((int)$stats['matches_won']) + ((int)$stats['matches_lost']);
	$win_rate = $decisive_matches > 0 ? round((((int)$stats['matches_won']) / $decisive_matches) * 100, 1) : 0;
	$walletStatusLabel = $isSuspended ? '✗ Zawieszone' : (($stats['account_status'] ?? 'active') === 'active' ? '✓ Aktywne' : '✗ Nieaktywne');
	$walletStatusColor = $isSuspended ? '#c62828' : ((($stats['account_status'] ?? 'active') === 'active') ? '#27ae60' : '#e74c3c');

	// Pobieranie ostatnich 10 transakcji
	$stmt_transactions = $pdo->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
	$stmt_transactions->execute([$user_id]);
	$transactions = $stmt_transactions->fetchAll(PDO::FETCH_ASSOC);

	// Funkcja do formatowania daty w języku polskim
	function formatPolishDate($datetime) {
		$months = [
			1 => 'stycznia', 2 => 'lutego', 3 => 'marca', 4 => 'kwietnia',
			5 => 'maja', 6 => 'czerwca', 7 => 'lipca', 8 => 'sierpnia',
			9 => 'września', 10 => 'października', 11 => 'listopada', 12 => 'grudnia'
		];
		$timestamp = strtotime($datetime);
		$day = date('j', $timestamp);
		$month = $months[(int)date('n', $timestamp)];
		$year = date('Y', $timestamp);
		$time = date('H:i', $timestamp);
		return "$day $month $year, $time";
	}
?>
<!--
Author: Wspólnie
Author URL: https://togethere.cloud
-->
<!DOCTYPE html>
<html>
<head>
	<title>Twój Portfel | kontakt: wspolpraca@togethere.cloud</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="utf-8">
	<meta name="keywords" content="projekty przyszłości"/>
	<link rel="stylesheet" href="/css/header.css" type="text/css" media="all"/>
	<link rel="stylesheet" href="/css/footer.css" type="text/css" media="all"/>
	<link href="/css/font-awesome.min.css" rel="stylesheet" type="text/css" media="all">
	<link href="/css/style.css" rel="stylesheet" type="text/css" media="all"/>
	<link href="//fonts.googleapis.com/css?family=Lato:400,500,600,700,800,900" rel="stylesheet">
	<style>
		body {
			background: linear-gradient(135deg, #e3f2fd 0%, #ffffff 100%);
			min-height: 100vh;
		}

		h1 {
			color: #1976d2;
			padding: 30px;
			margin-bottom: 20px;
			text-align: center;
			font-size: 2.5em;
			text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
		}

		.nav-link {
			display: inline-block;
			margin: 0 auto 30px;
			padding: 12px 30px;
			background: linear-gradient(135deg, #42a5f5, #1976d2);
			color: white;
			text-decoration: none;
			border-radius: 25px;
			font-weight: 600;
			transition: all 0.3s ease;
			box-shadow: 0 4px 15px rgba(25, 118, 210, 0.3);
		}

		.nav-link:hover {
			background: linear-gradient(135deg, #1976d2, #0d47a1);
			transform: translateY(-2px);
			box-shadow: 0 6px 20px rgba(25, 118, 210, 0.4);
		}

		.nav-container {
			text-align: center;
			margin-bottom: 30px;
		}

		.wallet-container {
			max-width: 1200px;
			margin: 0 auto;
			padding: 20px;
		}

		.balance-card {
			background: linear-gradient(135deg, #1976d2, #42a5f5);
			color: white;
			padding: 40px;
			border-radius: 20px;
			text-align: center;
			box-shadow: 0 15px 40px rgba(25, 118, 210, 0.4);
			margin-bottom: 40px;
		}

		.balance-card h2 {
            color: white !important;
			font-size: 1.3em;
			margin-bottom: 15px;
			opacity: 0.9;
		}

		.balance-amount {
			font-size: 4em;
			font-weight: 700;
			margin: 20px 0;
		}

		.balance-currency {
			font-size: 2em;
			opacity: 0.8;
		}

		.action-buttons {
			display: flex;
			gap: 20px;
			justify-content: center;
			margin-top: 30px;
			flex-wrap: wrap;
		}

		.action-btn {
			padding: 15px 40px;
			background: white;
			color: #1976d2;
			border: none;
			border-radius: 10px;
			font-size: 1.1em;
			font-weight: 600;
			cursor: pointer;
			transition: all 0.3s ease;
			box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
		}

		.action-btn:hover {
			transform: translateY(-3px);
			box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
		}

		.wallet-sections {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
			gap: 30px;
			margin-bottom: 40px;
		}

		.wallet-section {
			background: white;
			border-radius: 15px;
			padding: 30px;
			box-shadow: 0 10px 30px rgba(100, 181, 246, 0.2);
		}

		.wallet-section h3 {
			color: #1976d2;
			font-size: 1.6em;
			margin-bottom: 25px;
			padding-bottom: 15px;
			border-bottom: 3px solid #64b5f6;
		}

		.transaction-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15px;
			margin-bottom: 12px;
			background: #f8f9fa;
			border-radius: 10px;
			border-left: 4px solid #42a5f5;
			transition: all 0.3s ease;
		}

		.transaction-item:hover {
			background: #e3f2fd;
			transform: translateX(5px);
		}

		.transaction-info {
			flex: 1;
		}

		.transaction-title {
			font-weight: 600;
			color: #2c3e50;
			margin-bottom: 5px;
		}

		.transaction-date {
			font-size: 0.9em;
			color: #7f8c8d;
		}

		.transaction-amount {
			font-size: 1.3em;
			font-weight: 700;
		}

		.amount-positive {
			color: #27ae60;
		}

		.amount-negative {
			color: #e74c3c;
		}

		.stat-item {
			display: flex;
			justify-content: space-between;
			padding: 15px 0;
			border-bottom: 1px solid #ecf0f1;
		}

		.stat-item:last-child {
			border-bottom: none;
		}

		.stat-label {
			color: #7f8c8d;
			font-weight: 600;
		}

		.stat-value {
			color: #2c3e50;
			font-weight: 700;
			font-size: 1.1em;
		}

		@media (max-width: 768px) {
			h1 {
				font-size: 2em;
				padding: 20px;
			}

			.balance-amount {
				font-size: 3em;
			}

			.wallet-sections {
				grid-template-columns: 1fr;
			}

			.action-buttons {
				flex-direction: column;
			}

			.action-btn {
				width: 100%;
			}

			.balance-card {
				padding: 30px 20px;
			}
		}
	</style>
</head>
<body>
	<!-- Tutaj PHP sprawdza sesje czy zalogowany i wczytuje z /global/navLogged.html lun /global/navNoLogged.html -->
    <?php
        if (!empty($_SESSION['logged_in'])) {
            include $_SERVER['DOCUMENT_ROOT'].'/global/navLogined.php';
        } else {
            include $_SERVER['DOCUMENT_ROOT'].'/global/navNoLogined.php';
        }
    ?>

	<main>
		<div class="wallet-container">
			<h1>💰 Twój Portfel</h1>
			<?php if ($isSuspended): ?>
				<div style="background:#f8d7da;color:#721c24;padding:14px;border-radius:10px;margin:0 auto 20px;max-width:900px;line-height:1.7;border-left:4px solid #dc3545;">
					<strong>⛔ Portfel zawieszony.</strong>
					<?php if ($suspendedReason !== ''): ?>
						Powód: <?= htmlspecialchars($suspendedReason, ENT_QUOTES, 'UTF-8') ?>.
					<?php endif; ?>
					<?php if ($suspendedUntil !== ''): ?>
						Zawieszenie do: <?= htmlspecialchars($suspendedUntil, ENT_QUOTES, 'UTF-8') ?>.
					<?php else: ?>
						Zawieszenie bezterminowe.
					<?php endif; ?>
					Operacje portfela są niedostępne do czasu odwieszenia konta.
				</div>
			<?php endif; ?>
			<div class="nav-container">
				<a href="https://togethere.cloud/account/settings/" class="nav-link">⚙️ Przejdź do Ustawień</a>
			</div>

			<div class="balance-card">
				<h2>Dostępne środki</h2>
				<div class="balance-amount">
					<?php echo $balance; ?> <span class="balance-currency">Playons</span>
				</div>
				<div class="action-buttons">
					<button class="action-btn" <?= $isSuspended ? 'disabled style="opacity:0.6;cursor:not-allowed;"' : '' ?>>➕ Doładuj konto</button>
					<button class="action-btn" <?= $isSuspended ? 'disabled style="opacity:0.6;cursor:not-allowed;"' : '' ?>>💸 Wypłać środki</button>
				</div>
			</div>

			<div class="wallet-sections">
				<div class="wallet-section">
					<h3>📊 Ostatnie transakcje</h3>
					<?php if (empty($transactions)): ?>
						<div style="text-align: center; padding: 40px; color: #7f8c8d;">
							<p style="font-size: 1.2em;">🔍 Brak transakcji</p>
							<p>Tutaj pojawią się Twoje przyszłe transakcje</p>
						</div>
					<?php else: ?>
						<?php foreach ($transactions as $transaction): ?>
							<div class="transaction-item">
								<div class="transaction-info">
									<div class="transaction-title"><?php echo htmlspecialchars($transaction['title']); ?></div>
									<div class="transaction-date"><?php echo formatPolishDate($transaction['created_at']); ?></div>
								</div>
								<div class="transaction-amount <?php echo $transaction['type'] === 'income' ? 'amount-positive' : 'amount-negative'; ?>">
									<?php echo $transaction['type'] === 'income' ? '+' : '-'; ?><?php echo number_format($transaction['amount'], 2, '.', ''); ?> Playons
								</div>
							</div>
						<?php endforeach; ?>
					<?php endif; ?>
				</div>

				<div class="wallet-section">
					<h3>📈 Statystyki</h3>
					<div class="stat-item">
						<span class="stat-label">Całkowity przychód:</span>
						<span class="stat-value amount-positive">+<?php echo $total_income; ?> Playons</span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Całkowite wydatki:</span>
						<span class="stat-value amount-negative">-<?php echo $total_expenses; ?> Playons</span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Liczba transakcji:</span>
						<span class="stat-value"><?php echo $stats['total_transactions']; ?></span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Rozegrane mecze:</span>
						<span class="stat-value"><?php echo $stats['matches_played']; ?></span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Wygrane mecze:</span>
						<span class="stat-value amount-positive"><?php echo $stats['matches_won']; ?></span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Przegrane mecze:</span>
						<span class="stat-value amount-negative"><?php echo $stats['matches_lost']; ?></span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Remisy:</span>
						<span class="stat-value"><?php echo $stats['matches_draw']; ?></span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Wygranych turniejów:</span>
						<span class="stat-value"><?php echo $stats['tournaments_won']; ?></span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Wskaźnik wygranych:</span>
						<span class="stat-value"><?php echo $win_rate; ?>%</span>
					</div>
					<div class="stat-item">
						<span class="stat-label">Status konta:</span>
						<span class="stat-value" style="color: <?php echo $walletStatusColor; ?>;">
							<?php echo $walletStatusLabel; ?>
						</span>
					</div>
				</div>
			</div>
		</div>
	</main> 
	
	<?php
        if (!empty($_SESSION['logged_in'])) {
            include $_SERVER['DOCUMENT_ROOT'].'/global/footerLogined.php';
        } else {
            include $_SERVER['DOCUMENT_ROOT'].'/global/footerNoLogined.php';
        }
    ?>
</body>
</html>
