/**
 * Asset Card Database Manager
 * Handles communication with backend database for asset card persistence
 */

class AssetCardDatabase {
    constructor() {
        this.apiUrl = './php/asset_card_manager.php';
    }

    async load() {
        try {
            const response = await fetch(`${this.apiUrl}?action=load`);
            const data = await response.json();
            return data.success ? data.data : {};
        } catch (error) {
            console.error('Failed to load asset cards:', error);
            return {};
        }
    }

    async add(assetName, active = true, pinned = false) {
        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'add',
                    assetName,
                    active,
                    pinned
                })
            });
            const data = await response.json();
            return data.success;
        } catch (error) {
            console.error('Failed to add asset card:', error);
            return false;
        }
    }

    async update(assetName, updates) {
        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'update',
                    assetName,
                    ...updates
                })
            });
            const data = await response.json();
            return data.success;
        } catch (error) {
            console.error('Failed to update asset card:', error);
            return false;
        }
    }

    async remove(assetName) {
        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'remove',
                    assetName
                })
            });
            const data = await response.json();
            return data.success;
        } catch (error) {
            console.error('Failed to remove asset card:', error);
            return false;
        }
    }

    async sync(cards) {
        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'sync',
                    cards
                })
            });
            const data = await response.json();
            return data.success;
        } catch (error) {
            console.error('Failed to sync asset cards:', error);
            return false;
        }
    }
}

// Initialize global instance
window.assetCardDB = new AssetCardDatabase();
