<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Database;
use App\Core\Security;

$token = (string)($_GET['token'] ?? $_POST['token'] ?? '');
$email = strtolower(trim((string)($_GET['email'] ?? $_POST['email'] ?? '')));
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) $error = 'Invalid security token.';
    elseif ($passwordError = Security::passwordError((string)($_POST['password'] ?? ''), $email)) $error = $passwordError;
    elseif ((string)$_POST['password'] !== (string)($_POST['password_confirmation'] ?? '')) $error = 'Password confirmation does not match.';
    else {
        $row = Database::safeFetchOne('SELECT * FROM password_reset_tokens WHERE email=? AND token_hash=? AND expires_at>NOW() LIMIT 1', [$email,hash('sha256',$token)]);
        if (!$row) $error = 'This reset link is invalid or expired.';
        else {
            Database::transaction(function() use ($row) {
                $columns = Database::columns('users');
                $sql = in_array('must_change_password', $columns, true)
                    ? 'UPDATE users SET password_hash=?,auth_version=COALESCE(auth_version,1)+1,must_change_password=0,password_changed_at=NOW(),updated_at=NOW() WHERE id=?'
                    : 'UPDATE users SET password_hash=?,auth_version=COALESCE(auth_version,1)+1,password_changed_at=NOW(),updated_at=NOW() WHERE id=?';
                Database::execute($sql, [password_hash((string)$_POST['password'], PASSWORD_DEFAULT),$row['user_id']]);
                Database::execute('DELETE FROM password_reset_tokens WHERE user_id=?', [$row['user_id']]);
            });
            Security::logActivity((int)$row['user_id'], 'password_reset');
            set_flash('success', 'Password updated. You can now log in.');
            redirect('public/login.php');
        }
    }
}
$pageTitle = 'Set New 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"><h3>Set a new password</h3><?php if($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?><form method="post"><?= csrf_field() ?><input type="hidden" name="token" value="<?= e($token) ?>"><input type="hidden" name="email" value="<?= e($email) ?>"><label class="form-label">New password</label><input class="form-control mb-3" type="password" name="password" minlength="<?= PASSWORD_MIN_LENGTH ?>" required><label class="form-label">Confirm password</label><input class="form-control mb-3" type="password" name="password_confirmation" minlength="<?= PASSWORD_MIN_LENGTH ?>" required><button class="btn btn-primary w-100">Update password</button></form></div></div></div></div></section>
<?php include ROOT_PATH . '/app/Layouts/frontend_footer.php'; ?>
