import { ref, onMounted } from 'vue';
import axios from 'axios';

export function useSystemSettings() {
    const settings = ref({});
    const groupedSettings = ref({});
    const isLoading = ref(false);
    const error = ref(null);

    /**
     * Fetch settings (admin version).
     */
    const fetchAdminSettings = async () => {
        isLoading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/system-settings');
            if (response.data.success) {
                groupedSettings.value = response.data.data;
            }
        } catch (err) {
            error.value = err.response?.data?.message || 'Failed to fetch settings';
        } finally {
            isLoading.value = false;
        }
    };

    /**
     * Fetch public settings.
     */
    const fetchPublicSettings = async () => {
        isLoading.value = true;
        try {
            const response = await axios.get('/api/public/system-settings');
            if (response.data.success) {
                settings.value = response.data.data;
            }
        } catch (err) {
            error.value = err.response?.data?.message || 'Failed to fetch public settings';
        } finally {
            isLoading.value = false;
        }
    };

    /**
     * Update settings.
     */
    const updateSettings = async (settingsToUpdate) => {
        isLoading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/system-settings/update', {
                settings: settingsToUpdate
            });
            return response.data;
        } catch (err) {
            error.value = err.response?.data?.message || 'Failed to update settings';
            throw err;
        } finally {
            isLoading.value = false;
        }
    };

    /**
     * Upload logo.
     */
    const uploadLogo = async (file) => {
        const formData = new FormData();
        formData.append('logo', file);
        
        isLoading.value = true;
        try {
            const response = await axios.post('/admin/ultimate/system-settings/logo', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            return response.data;
        } catch (err) {
            error.value = err.response?.data?.message || 'Failed to upload logo';
            throw err;
        } finally {
            isLoading.value = false;
        }
    };

    return {
        settings,
        groupedSettings,
        isLoading,
        error,
        fetchAdminSettings,
        fetchPublicSettings,
        updateSettings,
        uploadLogo
    };
}
