<?php
require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';
require_once '../classes/User.php';

$db = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn()) {
    header('Location: ../login.php');
    exit();
}

$userClass = new User($db);
$currentUser = $auth->getCurrentUser();

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');

    if ($userClass->updateProfile($currentUser['id'], $name, $email)) {
        $message = '✅ Profile updated successfully';
        $_SESSION['user_name'] = $name;
        $_SESSION['user_email'] = $email;
        $currentUser = $auth->getCurrentUser();
    } else {
        $message = '❌ Failed to update profile. Please try again.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Profile - <?php echo APP_NAME; ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
    background-color: #f8f9fa;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
.container {
    max-width: 600px;
    margin-top: 50px;
}
.card {
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="container">
    <div class="card p-4">
        <h4 class="mb-3">👤 My Profile</h4>
        <?php if ($message): ?>
            <div class="alert alert-info"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        <form method="post">
            <div class="mb-3">
                <label class="form-label">Full Name</label>
                <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($_SESSION['user_name']); ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Email Address</label>
                <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($_SESSION['user_email']); ?>" required>
            </div>
            <div class="text-end">
                <a href="dashboard.php" class="btn btn-secondary">← Back</a>
                <button type="submit" class="btn btn-primary">Save Changes</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>
