<template>
    <div class="layout-px-spacing">
        <teleport to="#breadcrumb">
            <ul class="navbar-nav flex-row">
                <li>
                    <div class="page-header">
                        <nav class="breadcrumb-one" aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="javascript:;">Users</a></li>
                                <li class="breadcrumb-item active" aria-current="page"><span>Profile</span></li>
                            </ol>
                        </nav>
                    </div>
                </li>
            </ul>
        </teleport>

        <div class="row layout-spacing">
            <div class="col-xl-7 col-lg-7 col-md-7 col-sm-12 mx-auto layout-top-spacing">
                <div class="user-profile layout-spacing">
                    <div class="panel">
                        <div class="panel-body">
                            <div class="d-flex justify-content-between">
                                <h4 class="">Perfil</h4>
                            </div>
                            <div class="text-center user-info">
                                <img src="@/assets/images/profile-13.jpeg" alt="avatar" />
                                <p class="">{{ form.name }}</p>
                            </div>
                            <div class="user-info-list">
                                <div class="">
                                    <ul class="contacts-block list-unstyled">
                                        <li class="contacts-block__item">
                                            <a href="mailto:example@mail.com"
                                                ><svg
                                                    xmlns="http://www.w3.org/2000/svg"
                                                    width="24"
                                                    height="24"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    stroke-width="2"
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                    class="feather feather-mail"
                                                >
                                                    <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path>
                                                    <polyline points="22,6 12,13 2,6"></polyline></svg>{{ form.email }}</a
                                            >
                                        </li>
                                        <li class="contacts-block__item">
                                            <svg
                                                xmlns="http://www.w3.org/2000/svg"
                                                width="24"
                                                height="24"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                stroke-width="2"
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                class="feather feather-phone"
                                            >
                                                <path
                                                    d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"
                                                ></path>
                                            </svg>
                                            {{ form.celular }}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="d-flex justify-content-between">
                                <a
                                    class="btn btn-black"
                                    href="javascript:void(0);"
                                    title="cambio de contraseña"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    @click="changePw()"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-key" data-v-5522efca=""><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>
                                </a>
                                <a
                                    v-if="form.cliente_id"
                                    class="btn btn-black"
                                    :href="'/datos-fiscales/lista/'+form.cliente_id"
                                    title="Edit"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                >
                                    <svg 
                                        xmlns="http://www.w3.org/2000/svg" 
                                        width="24" 
                                        height="24" 
                                        viewBox="0 0 24 24" 
                                        fill="none" 
                                        stroke="currentColor" 
                                        stroke-width="2" 
                                        stroke-linecap="round" 
                                        stroke-linejoin="round" 
                                        class="feather feather-plus-square" 
                                        data-v-5522efca=""
                                    >
                                        <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                                        <line x1="12" y1="8" x2="12" y2="16"></line>
                                        <line x1="8" y1="12" x2="16" y2="12"></line>
                                    </svg>&nbsp
                                    Agregar datos fiscales
                                </a>
                                <a
                                    v-if="form.cliente_id"
                                    class="btn btn-black"
                                    :href="'/direcciones/entrega/'+form.cliente_id"
                                    title="Edit"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                >
                                <svg 
                                    xmlns="http://www.w3.org/2000/svg" 
                                    width="24" 
                                    height="24" 
                                    viewBox="0 0 24 24" 
                                    fill="none" 
                                    stroke="currentColor" 
                                    stroke-width="2" 
                                    stroke-linecap="round" 
                                    stroke-linejoin="round" 
                                    class="feather feather-plus-square" 
                                    data-v-5522efca=""
                                >
                                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                                    <line x1="12" y1="8" x2="12" y2="16"></line>
                                    <line x1="8" y1="12" x2="16" y2="12"></line>
                                </svg>&nbsp
                                    Agregar direcciones de entrega
                                </a>
                                <a
                                    class="btn btn-black"
                                    href="javascript:void(0);"
                                    title="Edit"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    @click="getUserId()"
                                >
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        width="24"
                                        height="24"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="2"
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        class="feather feather-edit-3"
                                    >
                                        <path d="M12 20h9"></path>
                                        <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
                                    </svg>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Register Modal -->
        <div
            class="modal fade"
            id="registerModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="registerModalLabel"
            aria-hidden="true"
            v-show="true"
        >
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div
                        class="modal-header titulo-dorado"
                        id="registerModalLabel"
                    >
                        <h4 class="modal-title" v-show="!is_password">
                            {{ editedIndex === -1 ? "Nuevo " : "Editar" }}
                        </h4>
                        <h4 class="modal-title" v-show="is_password">
                            Cambio de contraseña
                        </h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <form
                            class="mt-0"
                            ref="formComponent"
                            @submit.stop.prevent=""
                            autocomplete="off"
                        >
                            <div class="row">
                                <div class="col-md-12 col-sm-12 col-12" v-show="!is_password">
                                    <div class="form-group">
                                        <label>Nombre</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Nombre"
                                            v-model="form.name"
                                            :class="[is_entrada ? (!errors.name ? 'is-valid' : 'is-invalid') : '']"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.name">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6" v-show="editedIndex === -1 || is_password">
                                    <div class="form-group">
                                        <label>Password</label>
                                        <input
                                            v-model="form.password"
                                            type="password"
                                            class="form-control"
                                            placeholder="Contraseña"
                                            autocomplete="off"
                                            :class="[is_entrada ? (!errors.password ? 'is-valid' : 'is-invalid') : '']"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.password">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6" v-show="editedIndex === -1 || is_password">
                                    <div class="form-group">
                                        <label>Confirmar password</label>
                                        <input
                                            v-model="form.password_confirmation"
                                            type="password"
                                            class="form-control"
                                            placeholder="Contraseña"
                                            :class="[is_entrada ? (!errors.password_confirmation ? 'is-valid' : 'is-invalid') : '']"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.password_confirmation">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-12 mt-4">
                                    <div class="form-group">
                                        <button
                                            type="button"
                                            class="btn btn-black w-100"
                                            v-show="editedIndex !== -1 && !is_password"
                                            @click="updateUser"
                                        >
                                            Actualizar
                                        </button>
                                        <button
                                            type="button"
                                            class="btn btn-black w-100"
                                            v-show="editedIndex !== -1 && is_password"
                                            @click="updatePw"
                                        >
                                            Actualizar Contraseña
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <loading 
        v-model:active="isLoading"
        :can-cancel="false"
        :is-full-page="true"/>
    </div>
</template>

<script setup>
    import '@/assets/sass/scrollspyNav.scss';
    import '@/assets/sass/users/user-profile.scss';

    import { useMeta } from '@/composables/use-meta';
    import { useAuthStore } from '@/store/AuthStore';
    import * as UserRepository from '@/repositories/UserRepository';
    import { onMounted, ref } from "vue";

    // loading
    import Loading from 'vue-loading-overlay';
    import 'vue-loading-overlay/dist/css/index.css';

    import axios from "axios";

    useMeta({ title: 'EGURROLA' });

    const store = useAuthStore();

    const isLoading = ref(true);

    //formulario crear y eliminar
    let registerModal = ref(false);
    const is_entrada = ref(false);
    const is_password = ref(false);
    const editedIndex = ref(-1);
    const formComponent = ref(null);
    const errors = ref({});
    const form = ref({
        name:null,
        email:null,
        password:null,
        password_confirmation:null,
        role:"Terapista",
        cliente_id:null,
        celular:null,
    });

    const obtener_user = async ()=>{
        try {
            isLoading.value=true;
            const response = await UserRepository.getuser();
            form.value = {
                name: response.name,           
                email: response.email,           
                role: response.roles['0'].name,        
                cliente_id: response.cliente_id,
                celular: response.cliente?response.cliente.celular:null,
                password:null,
                password_confirmation:null,  
            };
            store.current_user.id=response.id;
            store.current_user.name=response.name;
            store.current_user.email=response.email;
            editedIndex.value= response.id;
            return response;
        } catch (error) {
            console.log(error);
        }
    }

    const getUserId = async (entra_pw=false) => {
        try {
            if(!entra_pw){
                is_password.value=false;
            }
            errors.value = {};
            form.value.password=null;
            form.value.password_confirmation=null;
            registerModal.show();
        } catch (error) {
            console.log(error);
        }
    };

    const changePw = ()=>{
        is_password.value=true;
        getUserId(true);
    }

    const updateUser = async () => {
        try {
            isLoading.value=true;
            is_entrada.value = true;
            const response = await UserRepository.updateUser(
                form.value,
                editedIndex.value
            );
            showMessage("Actualizado correctamente");
            registerModal.hide();
            obtener_user();
            isLoading.value=false;
        } catch (error) {
            if (axios.isAxiosError(error))
                errors.value = error.response.data.errors;
            isLoading.value=false;
        }
    };

    const updatePw = async () => {
        try {
            isLoading.value=true;
            is_entrada.value = true;
            const response = await UserRepository.passwordUser(
                form.value,
                editedIndex.value
            );
            showMessage("Actualizado correctamente");
            registerModal.hide();
            obtener_user();
            isLoading.value=false;
        } catch (error) {
            if (axios.isAxiosError(error))
                errors.value = error.response.data.errors;
            isLoading.value=false;
        }
    };

    const showMessage = (msg = "", type = "success") => {
        const toast = window.Swal.mixin({
            toast: true,
            position: "top",
            showConfirmButton: false,
            timer: 3000,
        });
        toast.fire({
            icon: type,
            title: msg,
            padding: "10px 20px",
        });
    };

    onMounted(async ()=>{
        await obtener_user();
        registerModal = new window.bootstrap.Modal(
            document.getElementById("registerModal")
        );
        isLoading.value=false;
    });
</script>
