<?php

$roleLabels = [
    'ADMINISTRATEUR' => 'Administrateur',
    'COMMERCIAL' => 'Commercial',
    'MAGASIN' => 'Magasin',
    'LECTURE' => 'Lecture seule',
];

$roleBadges = [
    'ADMINISTRATEUR' => 'darlink-badge-danger',
    'COMMERCIAL' => 'darlink-badge-primary',
    'MAGASIN' => 'darlink-badge-success',
    'LECTURE' => 'darlink-badge-light',
];

$formatDateTime = static function (?string $value): string {
    $value = trim((string)$value);

    if ($value === '') {
        return 'Jamais';
    }

    $timestamp = strtotime($value);

    return $timestamp
        ? date('d/m/Y à H:i', $timestamp)
        : $value;
};
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-people me-2"></i>
            Utilisateurs
        </h1>

        <p class="text-muted mb-0">
            Gérer les comptes, les rôles et les accès à Darlink ERP.
        </p>
    </div>

    <a
        href="index.php?page=utilisateurs_create"
        class="btn darlink-btn-primary"
    >
        <i class="bi bi-person-plus me-1"></i>
        Nouvel utilisateur
    </a>
</div>

<?php if (!empty($success)): ?>
    <div class="alert alert-success">
        <?= htmlspecialchars($success) ?>
    </div>
<?php endif; ?>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger">
        <?= htmlspecialchars($error) ?>
    </div>
<?php endif; ?>

<div class="darlink-card darlink-table-card">
    <div class="darlink-table-toolbar">
        <div class="darlink-table-toolbar-left">
            <div class="darlink-table-search">
                <i class="bi bi-search"></i>

                <input
                    type="search"
                    id="userSearch"
                    placeholder="Rechercher un utilisateur..."
                    autocomplete="off"
                >
            </div>
        </div>

        <div class="darlink-table-toolbar-right">
            <span class="darlink-badge darlink-badge-light">
                <?= count($users) ?>
                utilisateur<?= count($users) > 1 ? 's' : '' ?>
            </span>
        </div>
    </div>

    <div class="darlink-table-wrapper">
        <table
            class="table darlink-table-modern align-middle"
            id="usersTable"
        >
            <thead>
                <tr>
                    <th>Utilisateur</th>
                    <th>Identifiant</th>
                    <th>E-mail</th>
                    <th>Rôle</th>
                    <th>État</th>
                    <th>Dernière connexion</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>

            <tbody>
                <?php if (empty($users)): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-5">
                            Aucun utilisateur enregistré.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($users as $user): ?>
                        <?php
                        $role = strtoupper(
                            trim((string)($user['role'] ?? 'LECTURE'))
                        );

                        $fullName = trim(
                            (string)($user['prenom'] ?? '')
                            . ' '
                            . (string)($user['nom'] ?? '')
                        );

                        if ($fullName === '') {
                            $fullName = (string)($user['login'] ?? '');
                        }

                        $isActive = (int)($user['actif'] ?? 0) === 1;
                        ?>

                        <tr
                            data-edit-url="index.php?page=utilisateurs_show&id=<?= (int)$user['id'] ?>"
                            data-search="<?= htmlspecialchars(
                                strtolower(
                                    implode(
                                        ' ',
                                        [
                                            $fullName,
                                            (string)($user['login'] ?? ''),
                                            (string)($user['email'] ?? ''),
                                            $roleLabels[$role] ?? $role,
                                        ]
                                    )
                                ),
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>"
                        >
                            <td>
                                <div class="d-flex align-items-center gap-3">
                                    <div class="darlink-user-avatar">
                                        <?= htmlspecialchars(
                                            strtoupper(
                                                substr(
                                                    trim(
                                                        (string)($user['prenom'] ?? '')
                                                        . (string)($user['nom'] ?? '')
                                                    ),
                                                    0,
                                                    2
                                                )
                                            )
                                        ) ?>
                                    </div>

                                    <div>
                                        <div class="fw-semibold">
                                            <?= htmlspecialchars($fullName) ?>
                                        </div>

                                        <div class="small text-muted">
                                            Créé le
                                            <?= htmlspecialchars(
                                                $formatDateTime(
                                                    (string)($user['date_creation'] ?? '')
                                                )
                                            ) ?>
                                        </div>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <span class="darlink-table-code">
                                    <?= htmlspecialchars(
                                        (string)($user['login'] ?? '')
                                    ) ?>
                                </span>
                            </td>

                            <td>
                                <?= htmlspecialchars(
                                    (string)($user['email'] ?? '')
                                ) ?>
                            </td>

                            <td>
                                <span class="darlink-badge <?= htmlspecialchars(
                                    $roleBadges[$role]
                                        ?? 'darlink-badge-light'
                                ) ?>">
                                    <?= htmlspecialchars(
                                        $roleLabels[$role] ?? $role
                                    ) ?>
                                </span>
                            </td>

                            <td>
                                <?php if ($isActive): ?>
                                    <span class="darlink-badge darlink-badge-success">
                                        Actif
                                    </span>
                                <?php else: ?>
                                    <span class="darlink-badge darlink-badge-danger">
                                        Inactif
                                    </span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?= htmlspecialchars(
                                    $formatDateTime(
                                        (string)($user['derniere_connexion'] ?? '')
                                    )
                                ) ?>
                            </td>

                            <td class="text-end darlink-actions">
                                <a
                                    href="index.php?page=utilisateurs_show&id=<?= (int)$user['id'] ?>"
                                    class="darlink-icon-btn darlink-icon-btn-view"
                                    title="Consulter"
                                >
                                    <i class="bi bi-eye"></i>
                                </a>

                                <a
                                    href="index.php?page=utilisateurs_edit&id=<?= (int)$user['id'] ?>"
                                    class="darlink-icon-btn darlink-icon-btn-edit"
                                    title="Modifier"
                                >
                                    <i class="bi bi-pencil"></i>
                                </a>

                                <a
                                    href="index.php?page=utilisateurs_password&id=<?= (int)$user['id'] ?>"
                                    class="darlink-icon-btn darlink-icon-btn-order"
                                    title="Changer le mot de passe"
                                >
                                    <i class="bi bi-key"></i>
                                </a>

                                <?php if ($isActive): ?>
                                    <form
                                        method="post"
                                        action="index.php?page=utilisateurs_deactivate"
                                        class="d-inline"
                                        onsubmit="return confirm('Désactiver cet utilisateur ?');"
                                    >
                                        <input
                                            type="hidden"
                                            name="id"
                                            value="<?= (int)$user['id'] ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="darlink-icon-btn darlink-icon-btn-delete"
                                            title="Désactiver"
                                        >
                                            <i class="bi bi-person-x"></i>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const search = document.getElementById('userSearch');
    const rows = Array.from(
        document.querySelectorAll('#usersTable tbody tr')
    ).filter(function (row) {
        return row.querySelectorAll('td').length > 1;
    });

    if (!search) {
        return;
    }

    search.addEventListener('input', function () {
        const value = String(search.value || '')
            .trim()
            .toLowerCase();

        rows.forEach(function (row) {
            const haystack = String(
                row.dataset.search || ''
            ).toLowerCase();

            row.style.display =
                value === '' || haystack.includes(value)
                    ? ''
                    : 'none';
        });
    });
});
</script>