<div class="row mb-4">
    <div class="col-12">
        <h2><i class="bi bi-person"></i> Mi Perfil</h2>
        <p class="text-muted">Actualiza tu información personal y contraseña</p>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Información Personal</h5>
            </div>
            <div class="card-body">
                <form id="profileForm">
                    <div class="mb-3">
                        <label class="form-label">Usuario</label>
                        <input type="text" class="form-control" value="<?= Auth::user()['username'] ?>" disabled>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" value="<?= Auth::user()['email'] ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nombre</label>
                        <input type="text" class="form-control" name="first_name" value="<?= Auth::user()['first_name'] ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Apellido</label>
                        <input type="text" class="form-control" name="last_name" value="<?= Auth::user()['last_name'] ?>" required>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check"></i> Guardar Cambios
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Cambiar Contraseña</h5>
            </div>
            <div class="card-body">
                <form id="passwordForm">
                    <div class="mb-3">
                        <label class="form-label">Contraseña Actual</label>
                        <input type="password" class="form-control" name="current_password" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nueva Contraseña</label>
                        <input type="password" class="form-control" name="new_password" id="newPassword" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirmar Contraseña</label>
                        <input type="password" class="form-control" name="confirm_password" id="confirmPassword" required>
                    </div>
                    <button type="submit" class="btn btn-warning">
                        <i class="bi bi-lock"></i> Cambiar Contraseña
                    </button>
                </form>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-header">
                <h5 class="card-title mb-0">Información de Cuenta</h5>
            </div>
            <div class="card-body">
                <p><strong>Rol:</strong> <span class="badge bg-<?= (Auth::isAdmin() ? 'danger' : (Auth::isCapturist() ? 'warning' : 'info')) ?>"><?= Auth::user()['role'] ?></span></p>
                <p><strong>Estado:</strong> <span class="badge bg-success">Activo</span></p>
                <p><strong>Último acceso:</strong> <?= Auth::user()['last_login'] ? date('d/m/Y H:i', strtotime(Auth::user()['last_login'])) : 'No disponible' ?></p>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('profileForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const data = Object.fromEntries(formData.entries());

    fetch('/dashboard.php?page=users_actions&action=update_profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            Swal.fire('Guardado', 'Tu perfil ha sido actualizado', 'success').then(() => {
                location.reload(); // Recargar para ver los cambios en la información de sesión
            });
        } else {
            Swal.fire('Error', res.message || 'Error al guardar', 'error');
        }
    })
    .catch(() => Swal.fire('Error', 'Error de conexión', 'error'));
});

document.getElementById('passwordForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const data = Object.fromEntries(formData.entries());

    if (data.new_password !== data.confirm_password) {
        Swal.fire('Error', 'Las contraseñas no coinciden', 'error');
        return;
    }

    if (data.new_password.length < 6) {
        Swal.fire('Error', 'La contraseña debe tener al menos 6 caracteres', 'error');
        return;
    }

    fetch('/dashboard.php?page=users_actions&action=change_password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            Swal.fire('Éxito', 'Contraseña actualizada', 'success').then(() => {
                document.getElementById('passwordForm').reset();
            });
        } else {
            Swal.fire('Error', res.message || 'Error al cambiar contraseña', 'error');
        }
    })
    .catch(() => Swal.fire('Error', 'Error de conexión', 'error'));
});
</script>
