<?php
require_once '../includes/auth.php';
if ($_SESSION['user_role'] !== 'superadmin') {
    header('Location: ../dashboard.php');
    exit;
}

$user_id = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
if (!$user_id) {
    header('Location: gestion_utilisateurs.php');
    exit;
}

require_once '../config/database.php';
require_once '../includes/functions.php';

$pdo = getPDO();
$error = '';
$success = '';

// Récupérer les infos de l'utilisateur
$stmt = $pdo->prepare("SELECT username, nom, email FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();
if (!$user) {
    header('Location: gestion_utilisateurs.php');
    exit;
}

// Réinitialisation du mot de passe
if (isset($_POST['reset_password'])) {
    $new_password = trim($_POST['new_password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');
    
    if (empty($new_password)) {
        $error = "Le nouveau mot de passe ne peut pas être vide.";
    } elseif (strlen($new_password) < 6) {
        $error = "Le mot de passe doit contenir au moins 6 caractères.";
    } elseif ($new_password !== $confirm_password) {
        $error = "Les mots de passe ne correspondent pas.";
    } else {
        $new_hash = password_hash($new_password, PASSWORD_BCRYPT);
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
            $stmt->execute([$new_hash, $user_id]);
            savePasswordHistory($pdo, $user_id, $new_hash);
            logAction($pdo, $_SESSION['user_id'], 'reset_password', "Mot de passe réinitialisé pour l'utilisateur ID $user_id");
            $pdo->commit();
            $success = "Mot de passe réinitialisé avec succès. Le nouvel historique a été enregistré.";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Erreur : " . $e->getMessage();
        }
    }
}

// Récupérer l'historique des mots de passe
$stmt = $pdo->prepare("SELECT * FROM password_history WHERE user_id = ? ORDER BY changed_at DESC");
$stmt->execute([$user_id]);
$historique = $stmt->fetchAll();

require_once '../includes/header.php';
?>

<h1>Gestion du compte : <?= htmlspecialchars($user['nom']) ?> (<?= htmlspecialchars($user['username']) ?>)</h1>
<p><strong>Email :</strong> <?= htmlspecialchars($user['email']) ?></p>

<div class="row mt-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header bg-warning text-dark">
                <h5 class="mb-0"><i class="fas fa-key me-2"></i>Réinitialiser le mot de passe</h5>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?= $error ?></div>
                <?php endif; ?>
                <?php if ($success): ?>
                    <div class="alert alert-success"><?= $success ?></div>
                <?php endif; ?>
                <form method="post">
                    <div class="mb-3">
                        <label for="new_password" class="form-label">Nouveau mot de passe</label>
                        <input type="password" class="form-control" id="new_password" name="new_password" required minlength="6">
                        <small class="text-muted">Minimum 6 caractères</small>
                    </div>
                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Confirmer le mot de passe</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                    </div>
                    <button type="submit" name="reset_password" class="btn btn-warning">Réinitialiser</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-history me-2"></i>Historique des mots de passe</h5>
            </div>
            <div class="card-body">
                <?php if (empty($historique)): ?>
                    <p class="text-muted">Aucun historique disponible.</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Hash (début)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($historique as $h): ?>
                                    <tr>
                                        <td><?= date('d/m/Y H:i:s', strtotime($h['changed_at'])) ?></td>
                                        <td><code><?= substr($h['password_hash'], 0, 30) ?>...</code></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="mt-3">
    <a href="gestion_utilisateurs.php" class="btn btn-secondary">Retour à la liste des utilisateurs</a>
</div>

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