<?php
// user_profile.php - Seite zur Verwaltung von Benutzerprofil und Einstellungen
// MODERNISIERTE VERSION: Grid-Layout, Glassmorphism Cards

$page_title = "Mein Profil & Einstellungen";

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'db_connect.php';
$current_user_id = $_SESSION['user_id'];
$message_settings = '';
$message_type_settings = 'info';

// Lade die aktuellen Einstellungen des Benutzers
$user_settings = [];
$stmt_load_settings = $conn->prepare("SELECT setting_key, setting_value FROM user_settings WHERE user_id = ?");
$stmt_load_settings->bind_param("i", $current_user_id);
$stmt_load_settings->execute();
$result_settings = $stmt_load_settings->get_result();
while ($row = $result_settings->fetch_assoc()) {
    $user_settings[$row['setting_key']] = $row['setting_value'];
}
$stmt_load_settings->close();
$items_per_page = $user_settings['items_per_page'] ?? 10;

// FORMULARVERARBEITUNG
if ($_SERVER["REQUEST_METHOD"] == "POST" && !isset($_POST['action'])) {
    if (isset($_POST['save_settings'])) {
        $new_items_per_page = intval($_POST['items_per_page']);
        $new_collapse_default = isset($_POST['articles_collapse_default']) ? '1' : '0';
        
        if (in_array($new_items_per_page, [10, 25, 50, 100])) {
            $sql_save = "INSERT INTO user_settings (user_id, setting_key, setting_value) VALUES (?, 'items_per_page', ?), (?, 'articles_collapse_default', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)";
            $stmt_save = $conn->prepare($sql_save);
            if($stmt_save) {
                $stmt_save->bind_param("isis", $current_user_id, $new_items_per_page, $current_user_id, $new_collapse_default);
                if ($stmt_save->execute()) {
                    $_SESSION['items_per_page'] = $new_items_per_page;
                    $_SESSION['articles_collapse_default'] = $new_collapse_default;
                    $items_per_page = $new_items_per_page;
                    $user_settings['articles_collapse_default'] = $new_collapse_default;
                    $message_settings = 'Einstellungen erfolgreich gespeichert!';
                    $message_type_settings = 'success';
                } else { $message_settings = 'Fehler beim Speichern der Einstellungen.'; $message_type_settings = 'danger'; }
                $stmt_save->close();
            }
        } else { $message_settings = 'Ungültiger Wert ausgewählt.'; $message_type_settings = 'danger'; }
    }
    elseif (isset($_POST['change_username'])) {
        $new_username = trim($_POST['new_username']);
        if (empty($new_username)) {
            $message_settings = 'Der Benutzername darf nicht leer sein.'; $message_type_settings = 'danger';
        } elseif ($new_username === $_SESSION['username']) {
            $message_settings = 'Keine Änderung vorgenommen.'; $message_type_settings = 'info';
        } else {
            $stmt_check = $conn->prepare("SELECT id FROM users WHERE username = ?");
            $stmt_check->bind_param("s", $new_username);
            $stmt_check->execute();
            if ($stmt_check->get_result()->num_rows > 0) {
                $message_settings = 'Dieser Benutzername ist bereits vergeben.'; $message_type_settings = 'danger';
            } else {
                $stmt_update = $conn->prepare("UPDATE users SET username = ? WHERE id = ?");
                $stmt_update->bind_param("si", $new_username, $current_user_id);
                if ($stmt_update->execute()) {
                    $_SESSION['username'] = $new_username;
                    $message_settings = 'Benutzername erfolgreich geändert!'; $message_type_settings = 'success';
                } else {
                    $message_settings = 'Fehler beim Ändern des Benutzernamens.'; $message_type_settings = 'danger';
                }
                $stmt_update->close();
            }
            $stmt_check->close();
        }
    }
    elseif (isset($_POST['change_password'])) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_new_password = $_POST['confirm_new_password'];

        if (empty($current_password) || empty($new_password) || empty($confirm_new_password)) {
            $message_settings = 'Bitte füllen Sie alle Passwortfelder aus.'; $message_type_settings = 'danger';
        } elseif ($new_password !== $confirm_new_password) {
            $message_settings = 'Die Passwörter stimmen nicht überein.'; $message_type_settings = 'danger';
        } else {
            $stmt_pass = $conn->prepare("SELECT password FROM users WHERE id = ?");
            $stmt_pass->bind_param("i", $current_user_id);
            $stmt_pass->execute();
            $result_pass = $stmt_pass->get_result()->fetch_assoc();
            $stmt_pass->close();

            if (password_verify($current_password, $result_pass['password'])) {
                $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt_update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt_update->bind_param("si", $new_password_hash, $current_user_id);
                if ($stmt_update->execute()) {
                    $message_settings = 'Passwort erfolgreich geändert!'; $message_type_settings = 'success';
                } else {
                    $message_settings = 'Fehler beim Ändern des Passworts.'; $message_type_settings = 'danger';
                }
                $stmt_update->close();
            } else {
                $message_settings = 'Das aktuelle Passwort ist nicht korrekt.'; $message_type_settings = 'danger';
            }
        }
    }
}

require_once 'header.php';
?>

<div class="container-fluid p-0">
    <h1 class="h3 mb-4 text-gray-800">Mein Profil</h1>

    <?php if ($message_settings) echo "<div class='alert alert-{$message_type_settings} mb-4 shadow-sm'>" . htmlspecialchars($message_settings) . "</div>"; ?>

    <div class="row g-4">
        <!-- Linke Spalte: Identität & Sicherheit -->
        <div class="col-lg-4">
            <!-- Profil-Karte -->
            <div class="card mb-4 text-center">
                <div class="card-body p-5">
                    <div class="mb-3">
                        <span class="fa-stack fa-4x">
                          <i class="fas fa-circle fa-stack-2x text-primary opacity-25"></i>
                          <i class="fas fa-user fa-stack-1x text-primary"></i>
                        </span>
                    </div>
                    <h3 class="card-title fw-bold"><?php echo htmlspecialchars($_SESSION['username']); ?></h3>
                    <p class="text-muted">Benutzerkonto</p>
                </div>
            </div>

            <!-- Sicherheit & Login -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-shield-alt me-2"></i>Sicherheit</h5>
                </div>
                <div class="card-body">
                    <form action="user_profile.php" method="post">
                        <h6 class="text-muted text-uppercase small fw-bold mb-3">Passwort ändern</h6>
                        <div class="mb-3">
                            <input type="password" class="form-control" id="current_password" name="current_password" placeholder="Aktuelles Passwort" required>
                        </div>
                        <div class="mb-3">
                            <input type="password" class="form-control" id="new_password" name="new_password" placeholder="Neues Passwort" required>
                        </div>
                        <div class="mb-3">
                            <input type="password" class="form-control" id="confirm_new_password" name="confirm_new_password" placeholder="Passwort bestätigen" required>
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="change_password" class="btn btn-outline-primary">Passwort aktualisieren</button>
                        </div>
                    </form>
                    
                    <hr class="my-4">
                    
                    <form action="user_profile.php" method="post">
                        <h6 class="text-muted text-uppercase small fw-bold mb-3">Benutzernamen ändern</h6>
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" id="new_username" name="new_username" value="<?php echo htmlspecialchars($_SESSION['username']); ?>" required>
                            <button type="submit" name="change_username" class="btn btn-outline-secondary">Ändern</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Rechte Spalte: App-Einstellungen -->
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-sliders-h me-2"></i>App-Einstellungen</h5>
                </div>
                <div class="card-body p-4">
                    <form action="user_profile.php" method="post">
                        <div class="row mb-4">
                            <div class="col-md-8">
                                <h6 class="fw-bold">Tabellenansicht</h6>
                                <p class="text-muted small mb-0">Wie viele Artikel sollen pro Seite in Listen angezeigt werden?</p>
                            </div>
                            <div class="col-md-4">
                                <select class="form-select" id="items_per_page" name="items_per_page">
                                    <option value="10" <?php if ($items_per_page == 10) echo 'selected'; ?>>10 Einträge</option>
                                    <option value="25" <?php if ($items_per_page == 25) echo 'selected'; ?>>25 Einträge</option>
                                    <option value="50" <?php if ($items_per_page == 50) echo 'selected'; ?>>50 Einträge</option>
                                    <option value="100" <?php if ($items_per_page == 100) echo 'selected'; ?>>100 Einträge</option>
                                </select>
                            </div>
                        </div>

                        <hr class="my-4">

                        <div class="row mb-4 align-items-center">
                            <div class="col-md-8">
                                <h6 class="fw-bold">Kategorien-Ansicht</h6>
                                <p class="text-muted small mb-0">Sollen Artikelkategorien beim Öffnen der Liste standardmäßig eingeklappt sein?</p>
                            </div>
                            <div class="col-md-4">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" role="switch" id="articles_collapse_default" name="articles_collapse_default" value="1" style="width: 3em; height: 1.5em;" <?php if (isset($user_settings['articles_collapse_default']) && $user_settings['articles_collapse_default'] == '1') echo 'checked'; ?>>
                                </div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <div class="d-flex justify-content-end">
                            <button type="submit" name="save_settings" class="btn btn-primary"><i class="fas fa-save me-2"></i>Einstellungen speichern</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
require_once 'footer.php'; 
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>