<?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ą
	$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());
	}
	
	// Pobranie danych użytkownika
	$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
	$stmt->execute([$_SESSION['user_id']]);
	$userData = $stmt->fetch(PDO::FETCH_ASSOC);
	
	if (!$userData) {
		session_destroy();
		header('Location: /login/');
		exit();
	}

	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'] ?? '');
	$settingsDisabled = $isSuspended ? 'disabled' : '';
?>
<!--
Author: Wspólnie
Author URL: https://togethere.cloud
-->
<!DOCTYPE html>
<html>
<head>
	<title>Ustawienia Konta | 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="//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 {
			display: flex;
			width: 100%;
			text-align: center;
			justify-content: center;
			align-items: center;
			margin-bottom: 30px;
		}

		.nav-container .box {
			display: flex;
			gap: 15px;
		}

		nav.navigation {
			margin-top: 0px !important;
		}

		.settings-container {
			max-width: 100%;
			width: 100%;
			margin: 0 auto;
			padding: 20px;
		}

		.settings-section {
			background: white;
			border-radius: 15px;
			padding: 35px;
			margin-bottom: 30px;
			box-shadow: 0 10px 30px rgba(100, 181, 246, 0.2);
			width: 100%;
			max-width: 100%;
		}

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

		.form-group {
			margin-bottom: 25px;
			width: 100% !important;
		}

		form div label {
			padding-left: 5px !important;
		}

		.form-group label {
			display: block;
			color: #2c3e50;
			font-weight: 600;
			margin-bottom: 10px;
			font-size: 1.05em;
		}

		.form-group input[type="text"],
		.form-group input[type="email"],
		.form-group input[type="password"],
		.form-group select {
			width: 100% !important;
			max-width: 100% !important;
			padding: 15px;
			border: 2px solid #64b5f6;
			border-radius: 8px;
			font-size: 1em;
			transition: all 0.3s ease;
			box-sizing: border-box;
		}

		.form-group input:focus,
		.form-group select:focus {
			outline: none;
			border-color: #1976d2;
			box-shadow: 0 0 10px rgba(25, 118, 210, 0.2);
		}

		.form-row {
			display: grid;
			grid-template-columns: 1fr;
			gap: 20px;
		}

		.switch-container {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15px;
			background: #f8f9fa;
			border-radius: 10px;
			margin-bottom: 15px;
			gap: 15px;
			flex-wrap: nowrap;
		}

		.switch-label {
			color: #2c3e50;
			font-weight: 600;
			flex: 1;
			font-size: 0.95em;
		}

		.switch {
			position: relative;
			display: inline-block;
			width: 60px;
			height: 30px;
		}

		.switch input {
			opacity: 0;
			width: 0;
			height: 0;
		}

		.slider {
			position: absolute;
			cursor: pointer;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: #ccc;
			transition: 0.4s;
			border-radius: 30px;
		}

		.slider:before {
			position: absolute;
			content: "";
			height: 22px;
			width: 22px;
			left: 4px;
			bottom: 4px;
			background-color: white;
			transition: 0.4s;
			border-radius: 50%;
		}

		input:checked + .slider {
			background-color: #42a5f5;
		}

		input:checked + .slider:before {
			transform: translateX(30px);
		}

		.btn {
			padding: 15px 40px;
			border: none;
			border-radius: 8px;
			font-size: 1.1em;
			font-weight: 600;
			cursor: pointer;
			transition: all 0.3s ease;
			width: 100% !important;
			max-width: 100% !important;
		}

		.btn-primary {
			background: linear-gradient(135deg, #42a5f5, #1976d2);
			color: white;
		}

		.btn-primary:hover {
			background: linear-gradient(135deg, #1976d2, #0d47a1);
			transform: translateY(-2px);
			box-shadow: 0 5px 15px rgba(25, 118, 210, 0.4);
		}

		.btn-danger {
			background: linear-gradient(135deg, #e74c3c, #c0392b);
			color: white;
		}

		.btn-danger:hover {
			background: linear-gradient(135deg, #c0392b, #922b21);
			transform: translateY(-2px);
			box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
		}

		.btn-warning {
			background: linear-gradient(135deg, #ff9800, #f57c00);
			color: white;
		}

		.btn-warning:hover {
			background: linear-gradient(135deg, #f57c00, #e65100);
			transform: translateY(-2px);
			box-shadow: 0 5px 15px rgba(255, 152, 0, 0.4);
		}

		.btn-secondary {
			background: #95a5a6;
			color: white;
		}

		.btn-secondary:hover {
			background: #7f8c8d;
		}

		.button-group {
			display: flex;
			flex-direction: column;
			gap: 15px;
			margin-top: 25px;
		}

		.info-box {
			background: #e3f2fd;
			border-left: 4px solid #42a5f5;
			padding: 15px;
			margin-bottom: 20px;
			border-radius: 5px;
			color: #2c3e50;
		}

		.danger-zone {
			border: 2px solid #e74c3c;
			border-radius: 10px;
			padding: 25px;
			margin-top: 30px;
		}

		.danger-zone h3 {
			color: #e74c3c;
			margin-bottom: 15px;
		}

		.danger-zone p {
			color: #7f8c8d;
			margin-bottom: 20px;
		}

		/* Modal wylogowania */
		.modal-overlay {
			display: none;
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
			z-index: 9999;
			justify-content: center;
			align-items: center;
		}

		.modal-overlay.active {
			display: flex;
		}

		.modal-content {
			background: white;
			border-radius: 15px;
			padding: 40px;
			max-width: 500px;
			width: 90%;
			box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
			animation: modalSlideIn 0.3s ease;
		}

		@keyframes modalSlideIn {
			from {
				opacity: 0;
				transform: translateY(-50px);
			}
			to {
				opacity: 1;
				transform: translateY(0);
			}
		}

		.modal-content h3 {
			color: #ff9800;
			font-size: 1.8em;
			margin-bottom: 20px;
			text-align: center;
		}

		.modal-content p {
			color: #555;
			font-size: 1.1em;
			margin-bottom: 30px;
			text-align: center;
			line-height: 1.6;
		}

		.modal-buttons {
			display: grid;
			grid-template-columns: 1fr 1fr;
			gap: 15px;
		}

		.modal-btn {
			padding: 15px;
			border: none;
			border-radius: 8px;
			font-size: 1.1em;
			font-weight: 600;
			cursor: pointer;
			transition: all 0.3s ease;
		}

		.modal-btn-yes {
			background: linear-gradient(135deg, #ff9800, #f57c00);
			color: white;
		}

		.modal-btn-yes:hover {
			background: linear-gradient(135deg, #f57c00, #e65100);
			transform: translateY(-2px);
			box-shadow: 0 5px 15px rgba(255, 152, 0, 0.4);
		}

		.modal-btn-no {
			background: #95a5a6;
			color: white;
		}

		.modal-btn-no:hover {
			background: #7f8c8d;
			transform: translateY(-2px);
		}

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

			.settings-section {
				padding: 25px 20px;
			}

			.switch-container {
				padding: 12px;
				gap: 10px;
			}

			.switch-label {
				font-size: 0.9em;
				line-height: 1.4;
			}

			.switch {
				flex-shrink: 0;
			}

			.form-row {
				grid-template-columns: 1fr;
			}

			.button-group {
				flex-direction: column;
			}

			.btn {
				width: 100%;
			}
		}

		.footer-copyright {
			display: flex;
			flex-direction: column;
			gap: 40px;
		}

		div.polices p {
			color: black !important;
			font-weight: bold !important;
		}

		div.polices p a {
			text-decoration: none !important;
			font-size: 1rem;
		}

		.disabled {
			background: #c5c5c5ff !important;
			cursor: not-allowed !important;
		}
	</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="settings-container">
			<h1>⚙️ Ustawienia Konta</h1>
			<div class="nav-container">
				<div class="box">
					<a href="/account/profile/" class="nav-link">👤 Informacje profilowe</a>
					<a href="/account/settings/" class="nav-link">⚙️ Pozostałe ustawienia</a>
				</div>
			</div>

			<?php if (isset($_GET['success'])): ?>
				<?php if ($_GET['success'] === 'password_changed'): ?>
					<div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; border-left: 4px solid #28a745;">
						✅ Hasło zostało pomyślnie zmienione!
					</div>
				<?php elseif ($_GET['success'] === 'email_changed'): ?>
					<div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; border-left: 4px solid #28a745;">
						✅ Adres email został pomyślnie zmieniony!
					</div>
				<?php elseif ($_GET['success'] === 'notifications'): ?>
					<div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; border-left: 4px solid #28a745;">
						✅ Preferencje powiadomień zostały zapisane!
					</div>
				<?php elseif ($_GET['success'] === 'preferences'): ?>
					<div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; border-left: 4px solid #28a745;">
						✅ Preferencje zostały zaktualizowane!
					</div>
				<?php endif; ?>
			<?php endif; ?>

			<?php if (isset($_GET['error'])): ?>
				<div style="background: #f8d7da; color: #721c24; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; border-left: 4px solid #dc3545;">
					❌ <?= htmlspecialchars($_GET['error']) ?>
				</div>
			<?php endif; ?>

			<!-- Zmiana hasła -->
			<div class="settings-section">
				<h2>🔒 Zmiana hasła</h2>
				<div class="info-box">
					ℹ️ Hasło musi zawierać co najmniej 8 znaków, w tym wielką literę, małą literę i cyfrę.
				</div>
				<form method="POST" action="<?= $isSuspended ? '#' : 'change_password_request.php' ?>">
					<p style="color: #7f8c8d; margin-bottom: 20px;">
						Aby zmienić hasło, wyślemy kod weryfikacyjny na Twój email. Kod będzie ważny przez 15 minut.
					</p>
					<button type="submit" class="btn btn-primary" <?= $settingsDisabled ?>>Wyślij kod weryfikacyjny</button>
				</form>
			</div>

			<!-- Powiadomienia -->
			<div class="settings-section">
				<h2>🔔 Powiadomienia</h2>
				<form method="POST" action="update_settings.php" id="notificationsForm">
					<fieldset style="border:0;padding:0;margin:0;" <?= $settingsDisabled ?>>
					<input type="hidden" name="action" value="notifications">
					<div class="switch-container">
						<span class="switch-label">Powiadomienia e-mail (wyłącza wszystkie poniżej)</span>
						<label class="switch">
							<input type="checkbox" name="email_notifications" id="masterSwitch" <?= $userData['email_notifications'] ? 'checked' : '' ?>>
							<span class="slider"></span>
						</label>
					</div>
					<div class="switch-container">
						<span class="switch-label">Powiadomienia o nowych turniejach</span>
						<label class="switch">
							<input type="checkbox" name="tournament_notifications" class="subSwitch" <?= $userData['tournament_notifications'] ? 'checked' : '' ?>>
							<span class="slider"></span>
						</label>
					</div>
					<div class="switch-container">
						<span class="switch-label">Powiadomienia o wynikach meczów</span>
						<label class="switch">
							<input type="checkbox" name="match_notifications" class="subSwitch" <?= $userData['match_notifications'] ? 'checked' : '' ?>>
							<span class="slider"></span>
						</label>
					</div>
					<div class="switch-container">
						<span class="switch-label">Newsletter</span>
						<label class="switch">
							<input type="checkbox" name="newsletter_enabled" class="subSwitch" <?= $userData['newsletter_enabled'] ? 'checked' : '' ?>>
							<span class="slider"></span>
						</label>
					</div>
					<div class="button-group">
						<button type="submit" class="btn btn-primary">Zapisz preferencje</button>
					</div>
					</fieldset>
				</form>
			</div>

			<script>
			document.addEventListener('DOMContentLoaded', function() {
				const masterSwitch = document.getElementById('masterSwitch');
				const subSwitches = document.querySelectorAll('.subSwitch');
				
				function updateSubSwitches() {
					const isEnabled = masterSwitch.checked;
					subSwitches.forEach(sw => {
						sw.disabled = !isEnabled;
						if (!isEnabled) {
							sw.checked = false;
						}
						sw.closest('.switch-container').style.opacity = isEnabled ? '1' : '0.5';
					});
				}
				
				masterSwitch.addEventListener('change', updateSubSwitches);
				updateSubSwitches();
			});
			</script>

			<!-- Preferencje -->
			<div class="settings-section">
				<h2>🎨 Preferencje</h2>
				<form method="POST" action="update_settings.php">
					<fieldset style="border:0;padding:0;margin:0;" <?= $settingsDisabled ?>>
					<input type="hidden" name="action" value="preferences">
					<div class="form-group">
						<label for="language">Język</label>
						<select id="language" name="language">
							<option value="pl" <?= $userData['language'] === 'pl' ? 'selected' : '' ?>>Polski</option>
							<option value="en" <?= $userData['language'] === 'en' ? 'selected' : '' ?>>English</option>
							<option value="de" <?= $userData['language'] === 'de' ? 'selected' : '' ?>>Deutsch</option>
						</select>
					</div>
					<div class="form-group">
						<label for="timezone">Strefa czasowa</label>
						<select id="timezone" name="timezone">
							<option value="Europe/Warsaw" <?= $userData['timezone'] === 'Europe/Warsaw' ? 'selected' : '' ?>>Europa/Warszawa (GMT+1)</option>
							<option value="Europe/London" <?= $userData['timezone'] === 'Europe/London' ? 'selected' : '' ?>>Europa/Londyn (GMT+0)</option>
							<option value="America/New_York" <?= $userData['timezone'] === 'America/New_York' ? 'selected' : '' ?>>Ameryka/Nowy Jork (GMT-5)</option>
						</select>
					</div>
					<button type="submit" class="btn btn-primary">Zapisz preferencje</button>
					</fieldset>
				</form>
			</div>

			<!-- Informacje o koncie -->
			<div class="settings-section">
				<h2>ℹ️ Informacje o koncie</h2>
				<div style="padding: 20px; background: #f8f9fa; border-radius: 10px;">
					<div style="margin-bottom: 15px;">
						<strong>Status konta:</strong>
						<?php if ($userData['account_suspended']): ?>
							<span style="color: #c62828; font-weight: bold;">⛔ Zawieszone</span>
						<?php else: ?>
							<span style="color: #28a745; font-weight: bold;">✅ Aktywne</span>
						<?php endif; ?>
					</div>
					<div style="margin-bottom: 15px;">
						<strong>Status portfela:</strong>
						<?php
						$walletColors = [
							'active' => '#28a745',
							'suspended' => '#ff9800',
							'blocked' => '#c62828'
						];
						$walletLabels = [
							'active' => '✅ Aktywny',
							'suspended' => '⚠️ Zawieszony',
							'blocked' => '⛔ Zablokowany'
						];
						$walletStatus = $isSuspended ? 'suspended' : (string)($userData['wallet_status'] ?? 'active');
						$color = $walletColors[$walletStatus] ?? '#7f8c8d';
						$label = $walletLabels[$walletStatus] ?? 'Nieznany';
						?>
						<span style="color: <?= $color ?>; font-weight: bold;"><?= $label ?></span>
					</div>
					<div>
						<strong>Email zweryfikowany:</strong>
						<?php if ($userData['email_verified']): ?>
							<span style="color: #28a745;">✅ Tak</span>
						<?php else: ?>
							<span style="color: #c62828;">❌ Nie</span>
						<?php endif; ?>
					</div>
				</div>
			</div>

			<!-- Strefa niebezpieczna -->
			<div class="settings-section">
				<div class="danger-zone">
					<h3>⚠️ Strefa niebezpieczna</h3>
					<p>Usunięcie konta jest nieodwracalne. Wszystkie Twoje dane, statystyki i osiągnięcia zostaną trwale utracone.</p>
					<button onclick="confirmDeleteAccount()" class="btn btn-danger" <?= $settingsDisabled ?>>Usuń konto</button>
				</div>
			</div>
		</div>
	</main>

	<!-- Modal usuwania konta -->
	<div class="modal-overlay" id="deleteAccountModal">
		<div class="modal-content">
			<h3 style="color: #c62828;">⚠️ Usunięcie konta</h3>
			<p style="font-weight: bold; color: #c62828;">To działanie jest nieodwracalne!</p>
			<p>Wszystkie Twoje dane, statystyki, osiągnięcia i historia zostanie trwale usunięta.</p>
			<p style="margin-top: 20px; font-weight: 600;">Wpisz "USUŃ" aby potwierdzić:</p>
			<input type="text" id="deleteConfirmInput" placeholder="Wpisz USUŃ" 
			       style="width: 100%; padding: 12px; border: 2px solid #e74c3c; border-radius: 8px; font-size: 1em; margin-bottom: 20px; box-sizing: border-box;">
			<div class="modal-buttons">
				<button class="modal-btn modal-btn-no" onclick="closeDeleteAccountModal()">Anuluj</button>
				<button class="modal-btn modal-btn-yes" onclick="deleteAccount()" style="background: #c62828;">Usuń konto na zawsze</button>
			</div>
		</div>
	</div>  
	
	<script>
		function confirmDeleteAccount() {
			document.getElementById('deleteAccountModal').classList.add('active');
			document.getElementById('deleteConfirmInput').value = '';
		}

		function closeDeleteAccountModal() {
			document.getElementById('deleteAccountModal').classList.remove('active');
			document.getElementById('deleteConfirmInput').value = '';
		}

		function deleteAccount() {
			const input = document.getElementById('deleteConfirmInput').value;
			if (input === 'USUŃ') {
				window.location.href = '/account/settings/delete_account.php';
			} else {
				alert('Musisz wpisać "USUŃ" aby potwierdzić usunięcie konta.');
			}
		}

		// Zamknięcie modala po kliknięciu poza nim
		document.getElementById('deleteAccountModal').addEventListener('click', function(e) {
			if (e.target === this) {
				closeDeleteAccountModal();
			}
		});

		// Enter w input potwierdza usunięcie
		document.getElementById('deleteConfirmInput').addEventListener('keypress', function(e) {
			if (e.key === 'Enter') {
				deleteAccount();
			}
		});
	</script>

	<?php
        if (!empty($_SESSION['logged_in'])) {
            include $_SERVER['DOCUMENT_ROOT'].'/global/footerLogined.php';
        } else {
            include $_SERVER['DOCUMENT_ROOT'].'/global/footerNoLogined.php';
        }
    ?>
</body>
</html>
