<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\Security;

Auth::requireLogin('public/login.php');
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        $error = 'Invalid security token. Refresh the page and try again.';
    } else {
        $current = (string)($_POST['current_password'] ?? '');
        $password = (string)($_POST['password'] ?? '');
        $confirmation = (string)($_POST['password_confirmation'] ?? '');
        $user = Database::safeFetchOne('SELECT id,email,password_hash,COALESCE(auth_version,1) auth_version FROM users WHERE id=? LIMIT 1', [Auth::id()]);
        if (!$user || !password_verify($current, (string)$user['password_hash'])) {
            $error = 'Current password is incorrect.';
        } elseif ($password !== $confirmation) {
            $error = 'Password confirmation does not match.';
        } elseif ($passwordError = Security::passwordError($password, (string)($user['email'] ?? ''))) {
            $error = $passwordError;
        } elseif (password_verify($password, (string)$user['password_hash'])) {
            $error = 'The new password must be different from the current password.';
        } else {
            $newVersion = (int)$user['auth_version'] + 1;
            $columns = Database::columns('users');
            if (in_array('must_change_password', $columns, true)) {
                Database::execute(
                    'UPDATE users SET password_hash=?,auth_version=?,must_change_password=0,password_changed_at=NOW(),updated_at=NOW() WHERE id=?',
                    [password_hash($password, PASSWORD_DEFAULT), $newVersion, Auth::id()]
                );
            } else {
                Database::execute(
                    'UPDATE users SET password_hash=?,auth_version=?,password_changed_at=NOW(),updated_at=NOW() WHERE id=?',
                    [password_hash($password, PASSWORD_DEFAULT), $newVersion, Auth::id()]
                );
            }
            Auth::clearPasswordChangeRequirement($newVersion);
            Security::logActivity(Auth::id(), 'password_changed');
            set_flash('success', 'Password updated successfully.');
            redirect(role_dashboard_url());
        }
    }
}

$pageTitle = 'Change Password | ' . BRAND_NAME;
include ROOT_PATH . '/app/Layouts/frontend_header.php';
?>
<section class="container py-5"><div class="row justify-content-center"><div class="col-lg-5">
<div class="card border-0 shadow-sm"><div class="card-body p-4 p-lg-5">
<h3>Change your password</h3>
<p class="text-muted"><?= Auth::requiresPasswordChange() ? 'This account is using a temporary or seeded password. Set a private password before continuing.' : 'Update your account password.' ?></p>
<?php if ($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>
<form method="post" autocomplete="off">
<?= csrf_field() ?>
<label class="form-label">Current password</label>
<input class="form-control mb-3" type="password" name="current_password" autocomplete="current-password" required>
<label class="form-label">New password</label>
<input class="form-control mb-3" type="password" name="password" minlength="<?= PASSWORD_MIN_LENGTH ?>" autocomplete="new-password" required>
<label class="form-label">Confirm new password</label>
<input class="form-control mb-3" type="password" name="password_confirmation" minlength="<?= PASSWORD_MIN_LENGTH ?>" autocomplete="new-password" required>
<button class="btn btn-primary w-100">Save password</button>
</form>
<?php if (!Auth::requiresPasswordChange()): ?><a class="btn btn-link w-100 mt-2" href="<?= url(role_dashboard_url()) ?>">Cancel</a><?php endif; ?>
</div></div>
</div></div></section>
<?php include ROOT_PATH . '/app/Layouts/frontend_footer.php'; ?>
