<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();
Auth::requireRole('admin');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: settings.php');
    exit;
}

$userId   = (int)($_POST['user_id']  ?? 0);
$password = $_POST['password']       ?? '';
$confirm  = $_POST['confirm']        ?? '';
$errors   = [];

if (!$userId) {
    header('Location: settings.php');
    exit;
}

$stmt = Database::get()->prepare('SELECT username FROM app_users WHERE id = ?');
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: settings.php');
    exit;
}

if (strlen($password) < 6) {
    $errors[] = 'Le mot de passe doit comporter au moins 6 caractères.';
}
if ($password !== $confirm) {
    $errors[] = 'Les mots de passe ne correspondent pas.';
}

if ($errors) {
    $_SESSION['flash'] = ['type' => 'danger', 'message' => implode(' ', $errors)];
} else {
    Auth::changePassword($userId, $password);
    AuditLog::log('user.reset_password', 'user', $userId, $user['username']);
    $_SESSION['flash'] = [
        'type'    => 'success',
        'message' => "Mot de passe de « {$user['username']} » réinitialisé.",
    ];
}

header('Location: settings.php');
exit;
