<div class="container mt-4">
    <h2 class="mb-4">Configuración de Perfil</h2>

    <div class="row">
        <div class="col-lg-4">
            <div class="card shadow-sm p-4 text-center">
                <div class="position-relative d-inline-block">
                    <div class="profile-container">
                    <img id="profileImage" src="/assets/profile/<?= htmlspecialchars($user->profile_picture ?? 'default.jpg') ?>" 
                        class="rounded-circle mb-3" width="120" height="120" alt="Foto de perfil">

                    <!-- Botón de edición sobre la imagen -->
                    <label for="profileInput" class="edit-icon">
                        <i class="fe fe-camera"></i>
                    </label>
                    
                    <!-- Input de archivo oculto -->
                    <input type="file" id="profileInput" accept="image/*" style="display: none;">
                    </div>
                </div>

                <h5><?= htmlspecialchars($userDetails->name) . ' ' . htmlspecialchars($userDetails->paternal_surname) ?></h5>
                <p class="text-muted"><?= htmlspecialchars(
                    $_SESSION['role'] === 'UGEL' ? 'Usuario Ugel' :
                    ($_SESSION['role'] === 'COMUNITY' ? 'Usuario Comunidad' :
                    ($_SESSION['role'] === 'ADMIN' ? 'Administrador' : 'Usuario'))
                ) ?></p>

                <?php if ($_SESSION['role'] === 'UGEL'): ?>
                    <p class="text-muted">
                        <?php if (!empty($userDetails->subgroup_name)): ?>
                            <?= htmlspecialchars($userDetails->subgroup()->description) ?>
                        <?php else: ?>
                            <?= htmlspecialchars($userDetails->group()->description) ?>
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card shadow-sm p-4">
                <h5>Información Personal</h5>
                <form method="POST" action="<?= BASE_ACTION ?>profile/update">
                    <div class="mb-3">
                        <label class="form-label">Nombre de usuario</label>
                        <input type="text" class="form-control" value="<?= htmlspecialchars($user->username) ?>" disabled>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Correo Electrónico</label>
                        <input type="email" name="email" id="email" class="form-control" required value="<?= htmlspecialchars($userDetails->email ?? '') ?>" disabled>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Teléfono</label>
                        <input type="text" name="phone" class="form-control" id="phone" value="<?= htmlspecialchars($userDetails->phone) ?>">
                        <div class="form-text text-muted">Ingrese solo el número sin el código de país. Ejemplo: 987654321</div>
                        
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Dirección</label>
                        <input type="text" name="address" id="address" class="form-control" value="<?= htmlspecialchars($userDetails->address ?? '') ?>">
                    </div>

                    <?php if ($_SESSION['role'] === 'COMUNITY' && $_SESSION['person_type'] === 'JURIDICA'): ?>
                        <hr>
                        <h5>Información de Empresa</h5>
                        <div class="mb-3">
                            <label class="form-label">Nombre de la Empresa</label>
                            <input type="text" name="company_name" id="company_name" class="form-control" value="<?= htmlspecialchars($userDetails->company_name ?? '') ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">RUC</label>
                            <input type="text" name="ruc" id="ruc" class="form-control" value="<?= htmlspecialchars($userDetails->ruc ?? '') ?>">
                        </div>
                    <?php endif; ?>

                    <div class="mt-3">
                        <button type="submit" class="btn btn-primary">Guardar cambios</button>
                    </div>
                </form>
            </div>

            <div class="card shadow-sm p-4 mt-4">
                <h5>Cambiar Contraseña</h5>
                <form id="change-password-form" method="POST" action="<?= BASE_ACTION ?>profile/update-password">
                    <div class="mb-3">
                        <label class="form-label">Contraseña Actual</label>
                        <input type="password" name="current_password" id="current_password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nueva Contraseña</label>
                        <input type="password" name="new_password" id="new_password" class="form-control" required>
                        <div id="password_requirements" class="mt-2 text-muted small">
                            <div id="req-length">✘ Mínimo 8 caracteres</div>
                            <div id="req-alphanumeric">✘ Contener letras y números</div>
                            <div id="req-no-special">✘ Sin caracteres especiales</div>
                        </div>


                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirmar Nueva Contraseña</label>
                        <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
                        <div id="password_feedback" class="mt-1"></div>
                    </div>
                    <div class="mt-3">
                        <button type="submit" class="btn btn-warning">Actualizar Contraseña</button>
                    </div>
                </form>
            </div>

        </div>
    </div>
</div>

<style>
    .profile-container {
        position: relative;
        width: 120px;
        height: 120px;
        display: flex;
        justify-content: center; 
        align-items: center;
        margin: 0 auto;
    }

    .profile-pic {
        width: 100%;
        height: 100%;
        object-fit: cover;
        aspect-ratio: 1/1;
        border-radius: 50%;
        border: 3px solid #ddd;
    }

    .edit-icon {
        position: absolute;
        bottom: 5px;
        right: 5px;
        width: 30px;
        height: 30px;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 14px;
        transition: 0.3s;
    }

    .edit-icon:hover {
        background: rgba(0, 0, 0, 0.9);
    }
</style>


<script>
    document.addEventListener("DOMContentLoaded", function () {
        const newPassword = document.getElementById("new_password");
        const confirmPassword = document.getElementById("confirm_password");
        const passwordFeedback = document.getElementById("password_feedback");
        const form = document.querySelector("form");

        const reqLength = document.getElementById("req-length");
        const reqAlphaNum = document.getElementById("req-alphanumeric");
        const reqNoSpecial = document.getElementById("req-no-special");

        const minLength = 8;

        function updateRequirement(element, condition) {
            element.textContent = (condition ? "✔" : "✘") + " " + element.textContent.slice(2);
            element.classList.toggle("text-success", condition);
            element.classList.toggle("text-danger", !condition);
        }

        function validatePassword() {
            const password = newPassword.value;

            const hasMinLength = password.length >= minLength;
            const hasLetter = /[A-Z]/i.test(password);
            const hasNumber = /\d/.test(password);
            const noSpecialChars = /^[A-Z0-9]+$/i.test(password);

            updateRequirement(reqLength, hasMinLength);
            updateRequirement(reqAlphaNum, hasLetter && hasNumber);
            updateRequirement(reqNoSpecial, noSpecialChars);

            if (password.toUpperCase() !== confirmPassword.value.toUpperCase()) {
                passwordFeedback.textContent = "Las contraseñas no coinciden";
                passwordFeedback.classList.add("text-danger");
                passwordFeedback.classList.remove("text-success");
            } else {
                passwordFeedback.textContent = "Las contraseñas coinciden";
                passwordFeedback.classList.add("text-success");
                passwordFeedback.classList.remove("text-danger");
            }
        }

        newPassword.addEventListener("input", validatePassword);
        confirmPassword.addEventListener("input", validatePassword);

        document.getElementById("change-password-form").addEventListener("submit", function (e) {
            const value = newPassword.value;

            const hasMinLength = value.length >= minLength;
            const hasLetterAndNumber = /[a-zA-Z]/.test(value) && /\d/.test(value);
            const noSpecialChars = /^[a-zA-Z0-9]+$/.test(value);

            const valid = hasMinLength && hasLetterAndNumber && noSpecialChars;

            if (!valid) {
                e.preventDefault();
                passwordFeedback.textContent = "La contraseña no cumple con todos los requisitos.";
                passwordFeedback.className = "text-danger";
            }
        });

        const fieldsToUpper = ["confirm_password", "new_password", "current_password", "address", "company_name"];
        fieldsToUpper.forEach(id => {
            const field = document.getElementById(id);
            if (field) {
                field.addEventListener("input", function (event) {
                    event.target.value = event.target.value.toUpperCase();
                });
            }
        });

        const phoneInput = document.getElementById("phone");
        if (phoneInput) {
            phoneInput.addEventListener("input", function () {
                this.value = this.value.replace(/\D/g, '').slice(0, 9);
            });
        }

        validatePassword();
    });
</script>

<script>
    document.getElementById('profileInput').addEventListener('change', function(event) {
        let file = event.target.files[0];
        if (file) {
            let formData = new FormData();
            formData.append('profile_picture', file);

            fetch(BASE_HREF +'profile/update-profile-picture', { 
                method: 'POST', 
                body: formData 
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('profileImage').src = "/assets/profile/" + data.filename;
                } else {
                    alert("Error al subir la imagen.");
                }
            })
            .catch(error => console.error('Error:', error));
        }
    });
</script>