<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';
ob_start();

if (empty($_SESSION['logged_in'])) {
    header('Location: /login/');
    exit();
}

$host = "localhost";
$db = "togethere_cloud";
$user = "root";
$pass = "HasloDoSQL";

try {
    
$pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch (PDOException $e) {
    die("Błąd połączenia z bazą danych: " . $e->getMessage());
}

function usersHasColumn(PDO $pdo, string $columnName): bool
{
    try {
        $database = (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
        if ($database === '') {
            return false;
        }

        $stmt = $pdo->prepare(
            'SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = :schema AND table_name = :table AND column_name = :column'
        );
        $stmt->execute([
            ':schema' => $database,
            ':table' => 'users',
            ':column' => $columnName,
        ]);

        return (int)$stmt->fetchColumn() > 0;
    } catch (Throwable $e) {
        return false;
    }
}

function ensureUsersPhoneNumberColumn(PDO $pdo): bool
{
    if (usersHasColumn($pdo, 'phone_number')) {
        return true;
    }

    try {
        $pdo->exec('ALTER TABLE users ADD COLUMN phone_number VARCHAR(50) NULL');
    } catch (Throwable $e) {
        return usersHasColumn($pdo, 'phone_number');
    }

    return usersHasColumn($pdo, 'phone_number');
}

$user_id = $_SESSION['user_id'];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST['action'] ?? '';
    
    // DANE OSOBOWE
    if ($action === 'personal_data') {
        try {
            $first_name = trim($_POST['first_name'] ?? '');
            $last_name = trim($_POST['last_name'] ?? '');
            $username = trim($_POST['username'] ?? '');
            $phone_country_code = trim($_POST['phone_country_code'] ?? '');
            $phone_number_raw = trim($_POST['phone_number'] ?? '');
            $phone_number = preg_replace('/\D+/', '', $phone_number_raw);
            $full_phone_number = null;
            
            if (empty($username)) {
                header('Location: /account/profile/?error=' . urlencode('Nazwa użytkownika nie może być pusta'));
                exit();
            }

            if (!preg_match('/^[A-Za-z0-9_&!]{1,20}$/', $username)) {
                header('Location: /account/profile/?error=' . urlencode('Nazwa użytkownika może zawierać tylko litery angielskie, cyfry oraz znaki _ & ! i maksymalnie 20 znaków'));
                exit();
            }

            if ($phone_country_code !== '' && !preg_match('/^\+\d{1,4}$/', $phone_country_code)) {
                header('Location: /account/profile/?error=' . urlencode('Niepoprawny kierunkowy numeru telefonu'));
                exit();
            }

            if ($phone_number_raw !== '' && ($phone_number === '' || strlen($phone_number) < 4 || strlen($phone_number) > 14)) {
                header('Location: /account/profile/?error=' . urlencode('Niepoprawny numer telefonu'));
                exit();
            }

            if (($phone_country_code === '' && $phone_number_raw !== '') || ($phone_country_code !== '' && $phone_number_raw === '')) {
                header('Location: /account/profile/?error=' . urlencode('Uzupełnij zarówno kierunkowy, jak i numer telefonu'));
                exit();
            }

            if ($phone_country_code !== '' && $phone_number !== '') {
                $full_phone_number = $phone_country_code . ' ' . $phone_number;
            }
            
            $check_username = $pdo->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $check_username->execute([$username, $user_id]);
            
            if ($check_username->fetch()) {
                header('Location: /account/profile/?error=' . urlencode('Nazwa użytkownika jest już zajęta'));
                exit();
            }
            
            $hasPhoneNumberColumn = ensureUsersPhoneNumberColumn($pdo);

            if ($hasPhoneNumberColumn) {
                $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, username = ?, phone_number = ? WHERE id = ?");
                $stmt->execute([
                    $first_name,
                    $last_name,
                    $username,
                    $full_phone_number,
                    $user_id
                ]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, username = ? WHERE id = ?");
                $stmt->execute([
                    $first_name,
                    $last_name,
                    $username,
                    $user_id
                ]);
            }
            
            $_SESSION['username'] = $username;
            header('Location: /account/profile/?success=personal_data');
            exit();
        } catch (Throwable $e) {
            error_log('Profile update error: ' . $e->getMessage());
            header('Location: /account/profile/?error=' . urlencode('Nie udało się zapisać danych profilowych'));
            exit();
        }
    }
    
    // POWIADOMIENIA
    if ($action === 'notifications') {
        $email_notifications = isset($_POST['email_notifications']) ? 1 : 0;
        $tournament_notifications = isset($_POST['tournament_notifications']) ? 1 : 0;
        $match_notifications = isset($_POST['match_notifications']) ? 1 : 0;
        $newsletter_enabled = isset($_POST['newsletter_enabled']) ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE users SET email_notifications = ?, tournament_notifications = ?, match_notifications = ?, newsletter_enabled = ? WHERE id = ?");
        $stmt->execute([$email_notifications, $tournament_notifications, $match_notifications, $newsletter_enabled, $user_id]);
        
        header('Location: /account/settings/?success=notifications');
        exit();
    }
    
    // PREFERENCJE
    if ($action === 'preferences') {
        $language = $_POST['language'] ?? 'pl';
        $timezone = $_POST['timezone'] ?? 'Europe/Warsaw';
        
        $stmt = $pdo->prepare("UPDATE users SET language = ?, timezone = ? WHERE id = ?");
        $stmt->execute([$language, $timezone, $user_id]);
        
        header('Location: /account/settings/?success=preferences');
        exit();
    }
}

header('Location: /account/settings/');
exit();

