<template>
    <div class="coverage-container">
        <div class="coverage-list">
            <h3>Danh sách tỉnh, quận, phường</h3>
            <Tree :data="locations" @add="addLocation" />
        </div>
        <div class="coverage-selected">
            <h3>Danh sách đã thêm</h3>
            <Tree :data="selectedLocations" />
        </div>
        <button @click="submit">Submit</button>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import Tree from '@/components/Tree.vue'; // Assuming you have a Tree component

export default {
    name: 'Coverage',
    props: {
        AgencyId: {
            type: String,
            required: true
        }
    },
    setup(props) {
        const locations = ref([]);
        const selectedLocations = ref([]);

        onMounted(async () => {
            await fetchLocations();
            await fetchSelectedLocations();
        });

        const fetchLocations = async () => {
            // Fetch locations from the database
            const response = await fetch('/api/locations');
            locations.value = await response.json();
        };

        const fetchSelectedLocations = async () => {
            // Fetch selected locations from the database
            const response = await fetch(`/api/selected-locations?agencyId=${props.AgencyId}`);
            selectedLocations.value = await response.json();
        };

        const addLocation = (location) => {
            selectedLocations.value.push(location);
        };

        const submit = async () => {
            // Submit selected locations to the database
            await fetch(`/api/update-locations?agencyId=${props.AgencyId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(selectedLocations.value)
            });
        };

        return {
            locations,
            selectedLocations,
            addLocation,
            submit
        };
    }
};
</script>

<style scoped>
.coverage-container {
    display: flex;
    justify-content: space-between;
}

.coverage-list,
.coverage-selected {
    width: 45%;
}

button {
    margin-top: 20px;
}
</style>
<template>
    <div>
        <ul>
            <li v-for="node in data" :key="node.id">
                {{ node.name }}
                <button @click="$emit('add', node)">+</button>
                <Tree v-if="node.children" :data="node.children" @add="$emit('add', $event)" />
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    name: 'Tree',
    props: {
        data: {
            type: Array,
            required: true
        }
    }
};
</script>

<style scoped>
ul {
    list-style-type: none;
    padding-left: 20px;
}

button {
    margin-left: 10px;
}
</style>