<?php
session_start();
include '../database/db.php';

// Pārbauda, vai lietotājs ir autentificēts
if (!isset($_SESSION['user_id'])) {
    header("Location: ../users/login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$success_message = "";
$error_message = "";

// Iegūst pašreizējā lietotāja informāciju
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Iegūst lietotāja paziņojumu iestatījumus
$prefs_stmt = $pdo->prepare("SELECT * FROM user_notification_preferences WHERE user_id = ?");
$prefs_stmt->execute([$user_id]);
$prefs = $prefs_stmt->fetch();

// Ja paziņojumu iestatījumi neeksistē, izveido noklusējuma vērtības
if (!$prefs) {
    $pdo->prepare(
        "INSERT INTO user_notification_preferences 
         (user_id, reminder_1h, reminder_6h, reminder_12h, reminder_24h) 
         VALUES (?, 1, 0, 0, 1)"
    )->execute([$user_id]);

    $prefs_stmt->execute([$user_id]);
    $prefs = $prefs_stmt->fetch();
}

// Apstrādā profila atjaunināšanas formu
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_name = trim($_POST['name']);
    $old_password = trim($_POST['old_password'] ?? '');
    $new_password = trim($_POST['new_password'] ?? '');
    $allow_email = isset($_POST['allow_email_notifications']) ? 1 : 0;

    // Paziņojumu laiku iestatījumi
    $reminder_1h = isset($_POST['reminder_1h']) ? 1 : 0;
    $reminder_6h = isset($_POST['reminder_6h']) ? 1 : 0;
    $reminder_12h = isset($_POST['reminder_12h']) ? 1 : 0;
    $reminder_24h = isset($_POST['reminder_24h']) ? 1 : 0;

    // Atjaunina vārdu, ja tas ir mainīts
    if (!empty($new_name) && $new_name !== $user['name']) {
        $stmt = $pdo->prepare("UPDATE users SET name = ? WHERE id = ?");
        $stmt->execute([$new_name, $user_id]);
        $_SESSION['name'] = $new_name;
        $success_message = "Name updated successfully!";
    }

    // Paroles maiņas loģika
    if (!empty($new_password)) {
        if (empty($old_password)) {
            $error_message = "Please enter your current password to change it.";
        } elseif (!password_verify($old_password, $user['password_hash'])) {
            $error_message = "Current password is incorrect!";
        } elseif (strlen($new_password) < 6) {
            $error_message = "New password must be at least 6 characters long!";
        } else {
            $new_password_hashed = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
            $stmt->execute([$new_password_hashed, $user_id]);
            $success_message = "Password updated successfully!";
        }
    }

    // Atjaunina e-pasta paziņojumu atļauju
    $stmt = $pdo->prepare("UPDATE users SET allow_email_notifications = ? WHERE id = ?");
    $stmt->execute([$allow_email, $user_id]);

    // Atjaunina paziņojumu laikus
    $stmt = $pdo->prepare(
        "UPDATE user_notification_preferences 
         SET reminder_1h = ?, reminder_6h = ?, reminder_12h = ?, reminder_24h = ? 
         WHERE user_id = ?"
    );
    $stmt->execute([$reminder_1h, $reminder_6h, $reminder_12h, $reminder_24h, $user_id]);

    // Ja nebija kļūdu un citu paziņojumu, uzrāda veiksmīgu atjaunināšanu
    if (empty($error_message) && empty($success_message)) {
        $success_message = "Settings updated successfully!";
    }

    // Novērš formas atkārtotu iesniegšanu
    header("Location: profile.php?success=1");
    exit();
}

// Ziņojums pēc veiksmīgas pāradresācijas
if (isset($_GET['success'])) {
    $success_message = "Settings updated successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile - Work Planner</title>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/profile.css">
</head>
<body>
<nav>
    <ul>
        <li><a href="../dashboard.php">Dashboard</a></li>
        <li><a href="../calendar/calendar.php">Calendar</a></li>
        <li><a href="../tasks/tasks.php">All Tasks</a></li>
        <li><a href="../teams/teams.php">Teams</a></li>
        <li><a href="../friends/add_friend.php">Friends</a></li>
        <li><a href="../profile/profile.php">Profile</a></li>
        <li><a href="../users/logout.php">Logout</a></li>
    </ul>
</nav>

<main>
    <h2>Profile Settings</h2>

    <?php if (!empty($error_message)) : ?>
        <div class="message error"><?= htmlspecialchars($error_message) ?></div>
    <?php endif; ?>

    <?php if (!empty($success_message)) : ?>
        <div class="message success"><?= htmlspecialchars($success_message) ?></div>
    <?php endif; ?>

    <div class="profile-container">
        <div class="profile-section">
            <h3>Account Information</h3>
            <form method="post">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" name="name" id="name" value="<?= htmlspecialchars($user['name']) ?>" required>
                </div>

                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" id="email" value="<?= htmlspecialchars($user['email']) ?>" disabled>
                    <small>Email cannot be changed</small>
                </div>

                <div class="section-divider"></div>

                <h3>Change Password</h3>
                <div class="form-group">
                    <label for="old_password">Current Password</label>
                    <input type="password" name="old_password" id="old_password" placeholder="Enter current password">
                    <small>Required to change password</small>
                </div>

                <div class="form-group">
                    <label for="new_password">New Password</label>
                    <input type="password" name="new_password" id="new_password" placeholder="Enter new password (min 8 characters)">
                </div>

                <div class="section-divider"></div>

                <h3>Notification Preferences</h3>

                <div class="checkbox-group">
                    <h4>Email Notifications</h4>
                    <label class="checkbox-label">
                        <input type="checkbox" name="allow_email_notifications" <?= $user['allow_email_notifications'] ? 'checked' : '' ?>>
                        <span>Allow email notifications for reminders</span>
                    </label>
                </div>

                <div class="checkbox-group">
                    <h4>Reminder Times</h4>
                    <p class="hint">Select when you want to receive reminders before events:</p>

                    <label class="checkbox-label">
                        <input type="checkbox" name="reminder_1h" <?= $prefs['reminder_1h'] ? 'checked' : '' ?>>
                        <span>1 hour before</span>
                    </label>

                    <label class="checkbox-label">
                        <input type="checkbox" name="reminder_6h" <?= $prefs['reminder_6h'] ? 'checked' : '' ?>>
                        <span>6 hours before</span>
                    </label>

                    <label class="checkbox-label">
                        <input type="checkbox" name="reminder_12h" <?= $prefs['reminder_12h'] ? 'checked' : '' ?>>
                        <span>12 hours before</span>
                    </label>

                    <label class="checkbox-label">
                        <input type="checkbox" name="reminder_24h" <?= $prefs['reminder_24h'] ? 'checked' : '' ?>>
                        <span>24 hours before (1 day)</span>
                    </label>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-save">Save All Changes</button>
                    <a href="../dashboard.php" class="btn-cancel">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</main>

</body>
</html>