<?php
$pageTitle = 'Profile / Account';
require_once __DIR__ . '/../app/includes/header.php';

$userId = (int)current_user()['id'];
$stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$userId]);
$user = $stmt->fetch();
if (!$user) {
    logout_user();
    redirect('/login.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = (string)post('action');
    $currentPassword = (string)post('current_password');

    if (!password_verify($currentPassword, $user['password_hash'])) {
        flash('error', 'Current password is incorrect.');
        redirect('/profile.php');
    }

    if ($action === 'change_email') {
        $email = strtolower(trim((string)post('new_email')));
        $confirm = strtolower(trim((string)post('confirm_email')));
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid new email address.');
            redirect('/profile.php');
        }
        if ($email !== $confirm) {
            flash('error', 'New email and confirmation email must match.');
            redirect('/profile.php');
        }
        $stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
        $stmt->execute([$email, $userId]);
        if ($stmt->fetch()) {
            flash('error', 'That email address is already used by another account.');
            redirect('/profile.php');
        }
        $stmt = db()->prepare('UPDATE users SET email = ?, updated_at = ? WHERE id = ?');
        $stmt->execute([$email, now(), $userId]);
        log_activity('profile.email_changed', 'Changed login email.');
        refresh_current_user();
        flash('success', 'Login email updated successfully.');
        redirect('/profile.php');
    }

    if ($action === 'change_password') {
        $password = (string)post('new_password');
        $confirm = (string)post('confirm_password');
        if ($password !== $confirm) {
            flash('error', 'New password and confirmation password must match.');
            redirect('/profile.php');
        }
        if (password_verify($password, $user['password_hash'])) {
            flash('error', 'New password cannot be the same as the old password.');
            redirect('/profile.php');
        }
        $errors = validate_strong_password($password);
        if ($errors) {
            flash('error', implode(' ', $errors));
            redirect('/profile.php');
        }
        $stmt = db()->prepare('UPDATE users SET password_hash = ?, must_change_password = 0, updated_at = ? WHERE id = ?');
        $stmt->execute([password_hash($password, PASSWORD_DEFAULT), now(), $userId]);
        log_activity('profile.password_changed', 'Changed account password.');
        refresh_current_user();
        session_regenerate_id(true);
        flash('success', 'Password updated successfully.');
        redirect('/profile.php');
    }

    flash('error', 'Unknown profile action.');
    redirect('/profile.php');
}
?>
<div class="page-head"><div><h1>Profile / Account</h1><p>Manage your login email and password.</p></div></div>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="card app-card p-4">
            <h2>Profile Info</h2>
            <div class="summary-row"><span>Name</span><strong><?= e($user['name']) ?></strong></div>
            <div class="summary-row"><span>Role</span><strong><?= e(ucfirst($user['role'])) ?></strong></div>
            <div class="summary-row"><span>Email</span><strong><?= e($user['email']) ?></strong></div>
            <?php if ((int)$user['must_change_password'] === 1): ?>
                <div class="alert alert-warning mt-3 mb-0">You are using the default temporary password. Please change it before continuing.</div>
            <?php endif; ?>
        </div>
    </div>
    <div class="col-lg-8">
        <form class="card app-card p-4 mb-4" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="change_email">
            <h2>Change Login Email</h2>
            <div class="row g-3">
                <div class="col-md-12"><label class="form-label">Current Password</label><input class="form-control" type="password" name="current_password" required></div>
                <div class="col-md-6"><label class="form-label">New Email</label><input class="form-control" type="email" name="new_email" required></div>
                <div class="col-md-6"><label class="form-label">Confirm New Email</label><input class="form-control" type="email" name="confirm_email" required></div>
            </div>
            <button class="btn btn-primary mt-4" type="submit">Save Email</button>
        </form>

        <form class="card app-card p-4" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="change_password">
            <h2>Change Password</h2>
            <div class="row g-3">
                <div class="col-md-12"><label class="form-label">Current Password</label><input class="form-control" type="password" name="current_password" required></div>
                <div class="col-md-6"><label class="form-label">New Password</label><input class="form-control" type="password" name="new_password" required></div>
                <div class="col-md-6"><label class="form-label">Confirm New Password</label><input class="form-control" type="password" name="confirm_password" required></div>
            </div>
            <div class="form-text mt-2">Minimum 10 characters with uppercase, lowercase, number, and special character.</div>
            <button class="btn btn-primary mt-4" type="submit">Save Password</button>
        </form>
    </div>
</div>
<?php require_once __DIR__ . '/../app/includes/footer.php'; ?>
