<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../includes/functions.php';

if ($_SESSION['user_role'] !== 'personnel') {
    header('Location: ' . BASE_URL . 'dashboard.php');
    exit;
}

$pdo = getPDO();
$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Changement de mot de passe
if (isset($_POST['change_password'])) {
    $current = $_POST['current_password'] ?? '';
    $new = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $hash = $stmt->fetchColumn();

    if (!password_verify($current, $hash)) {
        $error = "Mot de passe actuel incorrect.";
    } elseif (strlen($new) < 6) {
        $error = "Le nouveau mot de passe doit contenir au moins 6 caractères.";
    } elseif ($new !== $confirm) {
        $error = "Les mots de passe ne correspondent pas.";
    } else {
        $new_hash = password_hash($new, PASSWORD_BCRYPT);
        $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
        $stmt->execute([$new_hash, $user_id]);
        savePasswordHistory($pdo, $user_id, $new_hash);
        logAction($pdo, $user_id, 'changement_mot_de_passe');
        $success = "Mot de passe modifié avec succès.";
    }
}

// Upload signature
if (isset($_POST['upload_signature']) && isset($_FILES['signature'])) {
    $file = $_FILES['signature'];
    $allowed = ['image/png', 'image/jpeg', 'image/jpg'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error = "Erreur lors de l'upload.";
    } elseif (!in_array($file['type'], $allowed)) {
        $error = "Format non autorisé. Utilisez PNG ou JPG.";
    } elseif ($file['size'] > 2 * 1024 * 1024) {
        $error = "L'image ne doit pas dépasser 2 Mo.";
    } else {
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'signature_' . $user_id . '_' . time() . '.' . $extension;
        $upload_dir = '../uploads/signatures/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $path = $upload_dir . $filename;
        if (move_uploaded_file($file['tmp_name'], $path)) {
            $stmt = $pdo->prepare("SELECT signature_path FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $old = $stmt->fetchColumn();
            if ($old && file_exists($old)) unlink($old);

            $stmt = $pdo->prepare("UPDATE users SET signature_path = ? WHERE id = ?");
            $stmt->execute([$path, $user_id]);
            $_SESSION['user_signature'] = $path;
            logAction($pdo, $user_id, 'upload_signature');
            $success = "Signature uploadée avec succès.";
        } else {
            $error = "Erreur lors de la sauvegarde.";
        }
    }
}

// Récupérer les informations de l'utilisateur
$stmt = $pdo->prepare("SELECT username, nom, email, signature_path FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Récupérer l'historique des mots de passe
$historique = [];
$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';
?>

<div class="row">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-id-card me-2"></i>Mon profil</h5>
            </div>
            <div class="card-body">
                <p><strong>Nom d'utilisateur :</strong> <?= htmlspecialchars($user['username']) ?></p>
                <p><strong>Nom :</strong> <?= htmlspecialchars($user['nom']) ?></p>
                <p><strong>Email :</strong> <?= htmlspecialchars($user['email']) ?></p>
                <p><strong>Rôle :</strong> <?= $_SESSION['user_role'] ?></p>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-signature me-2"></i>Ma signature</h5>
            </div>
            <div class="card-body text-center">
                <?php if (!empty($user['signature_path']) && file_exists($user['signature_path'])): ?>
                    <img src="<?= BASE_URL . ltrim($user['signature_path'], '../') ?>" alt="Signature" class="img-fluid border p-2 mb-3" style="max-height:150px;">
                    <form method="post" enctype="multipart/form-data">
                        <input type="file" name="signature" accept="image/png,image/jpeg" class="form-control mb-2">
                        <button type="submit" name="upload_signature" class="btn btn-primary w-100">Remplacer</button>
                    </form>
                <?php else: ?>
                    <p class="text-muted">Aucune signature enregistrée.</p>
                    <form method="post" enctype="multipart/form-data">
                        <input type="file" name="signature" accept="image/png,image/jpeg" class="form-control mb-2" required>
                        <button type="submit" name="upload_signature" class="btn btn-success w-100">Uploader ma signature</button>
                    </form>
                <?php endif; ?>
                <small class="text-muted">Formats acceptés : PNG, JPG (max 2 Mo).<br>
                Cette signature sera automatiquement ajoutée aux fiches que vous créez.</small>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header bg-warning">
                <h5 class="mb-0"><i class="fas fa-key me-2"></i>Changer mon 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="current_password" class="form-label">Mot de passe actuel</label>
                        <input type="password" class="form-control" id="current_password" name="current_password" required>
                    </div>
                    <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">
                    </div>
                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Confirmer le nouveau mot de passe</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                    </div>
                    <button type="submit" name="change_password" class="btn btn-warning">Modifier</button>
                </form>
            </div>
        </div>

        <?php if (!empty($historique)): ?>
        <div class="card mt-3">
            <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>
            <ul class="list-group list-group-flush">
                <?php foreach ($historique as $h): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span><?= date('d/m/Y H:i', strtotime($h['changed_at'])) ?></span>
                        <small class="text-muted">Hash: <?= substr($h['password_hash'], 0, 20) ?>...</small>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
    </div>
</div>

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