<?php

$source = $old ?? $user ?? [];

$value = static function (
    string $key,
    string $default = ''
) use ($source): string {
    return htmlspecialchars(
        (string)($source[$key] ?? $default),
        ENT_QUOTES,
        'UTF-8'
    );
};

$isActive = array_key_exists('actif', $source)
    ? (int)$source['actif'] === 1
    : true;

$title = $isEdit
    ? 'Modifier l’utilisateur'
    : 'Nouvel utilisateur';

$action = $isEdit
    ? 'index.php?page=utilisateurs_update'
    : 'index.php?page=utilisateurs_store';

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-person-gear me-2"></i>
            <?= htmlspecialchars($title) ?>
        </h1>

        <p class="text-muted mb-0">
            Configurer l’identité, le rôle et l’accès de l’utilisateur.
        </p>
    </div>

    <a
        href="index.php?page=utilisateurs"
        class="btn btn-outline-secondary"
    >
        <i class="bi bi-arrow-left me-1"></i>
        Retour
    </a>
</div>

<?php if (!empty($errors['general'])): ?>
    <div class="alert alert-danger">
        <?= htmlspecialchars($errors['general']) ?>
    </div>
<?php endif; ?>

<form
    method="post"
    action="<?= htmlspecialchars($action) ?>"
    class="darlink-form-card"
>
    <?php if ($isEdit): ?>
        <input
            type="hidden"
            name="id"
            value="<?= (int)($user['id'] ?? 0) ?>"
        >
    <?php endif; ?>

    <div class="darlink-form-header">
        <h2 class="darlink-form-title">
            Informations de l’utilisateur
        </h2>
    </div>

    <div class="darlink-form-body">
        <div class="row g-4">
            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    Nom *
                </label>

                <input
                    type="text"
                    name="nom"
                    class="darlink-input"
                    required
                    maxlength="120"
                    value="<?= $value('nom') ?>"
                >
            </div>

            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    Prénom
                </label>

                <input
                    type="text"
                    name="prenom"
                    class="darlink-input"
                    maxlength="120"
                    value="<?= $value('prenom') ?>"
                >
            </div>

            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    Identifiant de connexion *
                </label>

                <input
                    type="text"
                    name="login"
                    class="darlink-input"
                    required
                    maxlength="100"
                    autocomplete="username"
                    value="<?= $value('login') ?>"
                >

                <div class="form-text">
                    Lettres, chiffres, points, tirets et underscores uniquement.
                </div>
            </div>

            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    Adresse e-mail
                </label>

                <input
                    type="email"
                    name="email"
                    class="darlink-input"
                    maxlength="190"
                    autocomplete="email"
                    value="<?= $value('email') ?>"
                >
            </div>

            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    Rôle *
                </label>

                <select
                    name="role"
                    class="darlink-select"
                    required
                >
                    <?php foreach ($roles as $role): ?>
                        <option
                            value="<?= htmlspecialchars($role) ?>"
                            <?= strtoupper($value('role', 'LECTURE')) === $role
                                ? 'selected'
                                : '' ?>
                        >
                            <?= htmlspecialchars(
                                $roleLabels[$role] ?? $role
                            ) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    État du compte
                </label>

                <div class="darlink-switch-card">
                    <div>
                        <div class="fw-semibold">
                            Compte actif
                        </div>

                        <div class="small text-muted">
                            L’utilisateur pourra se connecter à Darlink ERP.
                        </div>
                    </div>

                    <div class="form-check form-switch m-0">
                        <input
                            class="form-check-input"
                            type="checkbox"
                            role="switch"
                            name="actif"
                            value="1"
                            id="userActive"
                            <?= $isActive ? 'checked' : '' ?>
                        >
                    </div>
                </div>
            </div>
        </div>

        <?php if (!$isEdit): ?>
            <hr class="my-4">

            <div class="row g-4">
                <div class="col-md-6 darlink-form-group">
                    <label class="darlink-label">
                        Mot de passe *
                    </label>

                    <div class="darlink-password-field">
                        <input
                            type="password"
                            name="password"
                            id="userPassword"
                            class="darlink-input"
                            required
                            autocomplete="new-password"
                        >

                        <button
                            type="button"
                            class="darlink-password-toggle"
                            data-target="userPassword"
                            title="Afficher le mot de passe"
                        >
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="col-md-6 darlink-form-group">
                    <label class="darlink-label">
                        Confirmation du mot de passe *
                    </label>

                    <div class="darlink-password-field">
                        <input
                            type="password"
                            name="password_confirmation"
                            id="userPasswordConfirmation"
                            class="darlink-input"
                            required
                            autocomplete="new-password"
                        >

                        <button
                            type="button"
                            class="darlink-password-toggle"
                            data-target="userPasswordConfirmation"
                            title="Afficher le mot de passe"
                        >
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="col-12">
                    <div class="darlink-password-strength">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="fw-semibold">
                                Robustesse du mot de passe
                            </span>

                            <span
                                id="passwordStrengthLabel"
                                class="text-muted"
                            >
                                Non renseigné
                            </span>
                        </div>

                        <div class="darlink-password-strength-bar">
                            <div
                                id="passwordStrengthValue"
                                class="darlink-password-strength-value"
                            ></div>
                        </div>

                        <div class="darlink-password-rules mt-3">
                            <div data-password-rule="length">
                                <i class="bi bi-circle"></i>
                                10 caractères minimum
                            </div>

                            <div data-password-rule="uppercase">
                                <i class="bi bi-circle"></i>
                                Une majuscule
                            </div>

                            <div data-password-rule="lowercase">
                                <i class="bi bi-circle"></i>
                                Une minuscule
                            </div>

                            <div data-password-rule="number">
                                <i class="bi bi-circle"></i>
                                Un chiffre
                            </div>

                            <div data-password-rule="special">
                                <i class="bi bi-circle"></i>
                                Un caractère spécial
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="alert alert-info mt-4 mb-0">
                <i class="bi bi-info-circle me-1"></i>
                Le mot de passe se modifie depuis l’action
                « Changer le mot de passe ».
            </div>
        <?php endif; ?>
    </div>

    <div class="darlink-form-actions">
        <a
            href="index.php?page=utilisateurs"
            class="btn btn-outline-secondary"
        >
            Annuler
        </a>

        <button
            type="submit"
            class="btn darlink-btn-primary"
        >
            <i class="bi bi-check-lg me-1"></i>
            <?= $isEdit
                ? 'Enregistrer les modifications'
                : 'Créer l’utilisateur' ?>
        </button>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document
        .querySelectorAll('.darlink-password-toggle')
        .forEach(function (button) {
            button.addEventListener('click', function () {
                const targetId = button.dataset.target;
                const input = document.getElementById(targetId);

                if (!input) {
                    return;
                }

                const isPassword = input.type === 'password';

                input.type = isPassword
                    ? 'text'
                    : 'password';

                button.innerHTML = isPassword
                    ? '<i class="bi bi-eye-slash"></i>'
                    : '<i class="bi bi-eye"></i>';
            });
        });

    const password = document.getElementById('userPassword');
    const strengthValue = document.getElementById(
        'passwordStrengthValue'
    );
    const strengthLabel = document.getElementById(
        'passwordStrengthLabel'
    );

    if (!password || !strengthValue || !strengthLabel) {
        return;
    }

    const rules = {
        length: function (value) {
            return value.length >= 10;
        },
        uppercase: function (value) {
            return /[A-Z]/.test(value);
        },
        lowercase: function (value) {
            return /[a-z]/.test(value);
        },
        number: function (value) {
            return /[0-9]/.test(value);
        },
        special: function (value) {
            return /[^A-Za-z0-9]/.test(value);
        }
    };

    function updatePasswordStrength() {
        const value = password.value;
        let score = 0;

        Object.entries(rules).forEach(function ([name, validator]) {
            const element = document.querySelector(
                '[data-password-rule="' + name + '"]'
            );

            const valid = validator(value);

            if (valid) {
                score++;
            }

            if (element) {
                element.classList.toggle(
                    'is-valid',
                    valid
                );

                element.innerHTML = valid
                    ? '<i class="bi bi-check-circle-fill"></i> ' +
                        element.textContent.trim()
                    : '<i class="bi bi-circle"></i> ' +
                        element.textContent.trim();
            }
        });

        const percentage = score * 20;
        strengthValue.style.width = percentage + '%';

        const labels = [
            'Non renseigné',
            'Très faible',
            'Faible',
            'Moyen',
            'Fort',
            'Très fort'
        ];

        strengthLabel.textContent =
            value === ''
                ? labels[0]
                : labels[score];
    }

    password.addEventListener(
        'input',
        updatePasswordStrength
    );

    updatePasswordStrength();
});
</script>