<?php
include 'dashboard.php';
if (!isset($_SESSION['user_id'])) header("Location: login.php");
require 'db.php';

$user_id = $_SESSION['user_id'];
$errors = [];
$success = "";

// Fetch existing user info
$stmt = $conn->prepare("SELECT fullname, email, phoneno FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if(isset($_POST['update_profile'])){
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $password = trim($_POST['password']);

    if(empty($email) || empty($phone)){
        $errors[] = "Email and phone number are required.";
    } else {
        // If password is provided, update it
        if(!empty($password)){
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $update = $conn->prepare("UPDATE users SET email=?, phoneno=?, password=? WHERE id=?");
            $update->bind_param("sssi", $email, $phone, $hashed, $user_id);
        } else {
            // Update without password
            $update = $conn->prepare("UPDATE users SET email=?, phoneno=? WHERE id=?");
            $update->bind_param("ssi", $email, $phone, $user_id);
        }

        if($update->execute()){
            $success = "Profile updated successfully!";
        } else {
            $errors[] = "Update failed. Try again.";
        }
        $update->close();
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
<title>Edit Profile</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<div class="container mt-5">

<h3>Edit Profile</h3>

<?php if(!empty($errors)): ?>
<div class="alert alert-danger"><?= implode("<br>", $errors); ?></div>
<?php endif; ?>

<?php if($success): ?>
<div class="alert alert-success"><?= $success; ?></div>
<?php endif; ?>

<form method="POST">
    
    <div class="mb-3">
        <label>Email</label>
        <input type="email" name="email" class="form-control" value="<?= $user['email']; ?>" required>
    </div>

    <div class="mb-3">
        <label>Phone Number</label>
        <input type="text" name="phone" class="form-control" value="<?= $user['phoneno']; ?>" required>
    </div>

    <div class="mb-3">
        <label>New Password (leave empty if not changing)</label>
        <input type="password" name="password" class="form-control">
    </div>

    <button type="submit" name="update_profile" class="btn btn-primary">Save Changes</button>
</form>

<a href="dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>

</div>
</body>
</html>
