<?php

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

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-key me-2"></i>
            Changer le mot de passe
        </h1>

        <p class="text-muted mb-0">
            Définir un nouveau mot de passe pour
            <?= htmlspecialchars($fullName) ?>.
        </p>
    </div>

    <a
        href="index.php?page=utilisateurs_show&id=<?= (int)($user['id'] ?? 0) ?>"
        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="index.php?page=utilisateurs_password_update"
    class="darlink-form-card"
>
    <input
        type="hidden"
        name="id"
        value="<?= (int)($user['id'] ?? 0) ?>"
    >

    <div class="darlink-form-header">
        <h2 class="darlink-form-title">
            Nouveau mot de passe
        </h2>
    </div>

    <div class="darlink-form-body">
        <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"
                    >
                        <i class="bi bi-eye"></i>
                    </button>
                </div>
            </div>

            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">
                    Confirmation *
                </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"
                    >
                        <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>
    </div>

    <div class="darlink-form-actions">
        <a
            href="index.php?page=utilisateurs_show&id=<?= (int)($user['id'] ?? 0) ?>"
            class="btn btn-outline-secondary"
        >
            Annuler
        </a>

        <button
            type="submit"
            class="btn darlink-btn-primary"
        >
            <i class="bi bi-check-lg me-1"></i>
            Enregistrer le mot de passe
        </button>
    </div>
</form>

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

                if (!input) {
                    return;
                }

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

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

                button.innerHTML = show
                    ? '<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'
    );

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

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

        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);

                const label = element.textContent.trim();

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

        strengthValue.style.width = (score * 20) + '%';

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

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

    if (password) {
        password.addEventListener(
            'input',
            updatePasswordStrength
        );

        updatePasswordStrength();
    }
});
</script>