<?php
require_once __DIR__ . '/includes/auth.php';
requireLogin();

$user = getCurrentUser();
if ($user['user_type'] === 'admin') {
    redirectToDashboard();
}

$message = '';
$message_type = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if ($name === '' || $email === '') {
        $message = 'Name and email are required.';
        $message_type = 'danger';
    } else {
        $conn = getDBConnection();
        $stmt = $conn->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
        $stmt->bind_param('si', $email, $_SESSION['user_id']);
        $stmt->execute();
        $email_exists = $stmt->get_result()->num_rows > 0;
        $stmt->close();

        if ($email_exists) {
            $message = 'That email address is already in use by another account.';
            $message_type = 'danger';
        } else {
            if ($new_password !== '' || $confirm_password !== '' || $current_password !== '') {
                if (!password_verify($current_password, $user['password'])) {
                    $message = 'Current password is incorrect.';
                    $message_type = 'danger';
                } elseif (strlen($new_password) < 6) {
                    $message = 'New password must be at least 6 characters long.';
                    $message_type = 'danger';
                } elseif ($new_password !== $confirm_password) {
                    $message = 'New password and confirm password do not match.';
                    $message_type = 'danger';
                } else {
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt = $conn->prepare('UPDATE users SET name = ?, email = ?, phone = ?, password = ? WHERE id = ?');
                    $stmt->bind_param('ssssi', $name, $email, $phone, $hashed_password, $_SESSION['user_id']);
                    if ($stmt->execute()) {
                        $_SESSION['user_name'] = $name;
                        $message = 'Profile and password updated successfully.';
                        $user['password'] = $hashed_password;
                    } else {
                        $message = 'Unable to update your profile right now.';
                        $message_type = 'danger';
                    }
                    $stmt->close();
                }
            } else {
                $stmt = $conn->prepare('UPDATE users SET name = ?, email = ?, phone = ? WHERE id = ?');
                $stmt->bind_param('sssi', $name, $email, $phone, $_SESSION['user_id']);
                if ($stmt->execute()) {
                    $_SESSION['user_name'] = $name;
                    $message = 'Profile updated successfully.';
                } else {
                    $message = 'Unable to update your profile right now.';
                    $message_type = 'danger';
                }
                $stmt->close();
            }
        }

        $conn->close();
        $user = getCurrentUser();
    }
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>My Profile - Oldage Home</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'>
    <link href='https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap' rel='stylesheet'>
    <link rel='stylesheet' href='css/style.css'>
</head>
<body>
    <?php include 'includes/header.php'; ?>

    <section class='py-5'>
        <div class='container'>
            <div class='row justify-content-center'>
                <div class='col-lg-8'>
                    <div class='card shadow'>
                        <div class='card-body p-5'>
                            <div class='d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4'>
                                <div>
                                    <h2 class='mb-1'>My Profile</h2>
                                    <p class='text-muted mb-0'>Update your account details and password.</p>
                                </div>
                                <a href='dashboard.php' class='btn btn-outline-primary btn-sm'>Back to Dashboard</a>
                            </div>

                            <?php if ($message !== ''): ?>
                                <div class='alert alert-<?php echo $message_type; ?>'><?php echo htmlspecialchars($message); ?></div>
                            <?php endif; ?>

                            <form method='post'>
                                <div class='row'>
                                    <div class='col-md-6 mb-3'>
                                        <label for='name' class='form-label'>Full Name</label>
                                        <input type='text' class='form-control' id='name' name='name' value='<?php echo htmlspecialchars($user['name']); ?>' required>
                                    </div>
                                    <div class='col-md-6 mb-3'>
                                        <label for='email' class='form-label'>Email Address</label>
                                        <input type='email' class='form-control' id='email' name='email' value='<?php echo htmlspecialchars($user['email']); ?>' required>
                                    </div>
                                </div>
                                <div class='mb-4'>
                                    <label for='phone' class='form-label'>Phone Number</label>
                                    <input type='text' class='form-control' id='phone' name='phone' value='<?php echo htmlspecialchars($user['phone'] ?? ''); ?>'>
                                </div>

                                <hr class='my-4'>
                                <h5 class='mb-3'>Change Password</h5>
                                <p class='text-muted small mb-3'>Leave these fields blank if you do not want to change your password.</p>

                                <div class='mb-3'>
                                    <label for='current_password' class='form-label'>Current Password</label>
                                    <input type='password' class='form-control' id='current_password' name='current_password'>
                                </div>
                                <div class='row'>
                                    <div class='col-md-6 mb-3'>
                                        <label for='new_password' class='form-label'>New Password</label>
                                        <input type='password' class='form-control' id='new_password' name='new_password'>
                                    </div>
                                    <div class='col-md-6 mb-4'>
                                        <label for='confirm_password' class='form-label'>Confirm New Password</label>
                                        <input type='password' class='form-control' id='confirm_password' name='confirm_password'>
                                    </div>
                                </div>

                                <div class='d-grid'>
                                    <button type='submit' class='btn btn-primary'>Save Changes</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <?php include 'includes/footer.php'; ?>

    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js'></script>
    <script src='js/main.js'></script>
</body>
</html>

