// Trade Payout Storage Manager
// Manages ongoing trade payout information in database

class TradePayoutStorage {
    constructor() {
        this.endpoint = './php/trade_payout_manager.php';
    }

    // Save trade payout info when trade is placed
    async saveTradeInfo(tradeId, assetName, payoutPercentage, expiryTime) {
        try {
            const response = await fetch(this.endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'save',
                    tradeId: tradeId,
                    assetName: assetName,
                    payoutPercentage: payoutPercentage,
                    timestamp: Date.now(),
                    expiryTime: expiryTime
                })
            });
            
            const result = await response.json();
            return result.success;
        } catch (error) {
            console.error('Error saving trade info:', error);
            return false;
        }
    }

    // Get trade payout info by trade ID
    async getTradeInfo(tradeId) {
        try {
            const response = await fetch(this.endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'get',
                    tradeId: tradeId
                })
            });
            
            const result = await response.json();
            if (result.success) {
                return result.data;
            }
            return null;
        } catch (error) {
            console.error('Error getting trade info:', error);
            return null;
        }
    }

    // Delete trade info (called 5 seconds after trade ends)
    async deleteTradeInfo(tradeId) {
        try {
            const response = await fetch(this.endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'delete',
                    tradeId: tradeId
                })
            });
            
            const result = await response.json();
            return result.success;
        } catch (error) {
            console.error('Error deleting trade info:', error);
            return false;
        }
    }

    // Schedule auto-deletion 5 seconds after trade ends
    scheduleCleanup(tradeId, tradeEndTime) {
        const cleanupDelay = (tradeEndTime + 5000) - Date.now();
        
        if (cleanupDelay > 0) {
            setTimeout(async () => {
                await this.deleteTradeInfo(tradeId);
            }, cleanupDelay);
        } else {
            // Trade already ended, delete immediately
            this.deleteTradeInfo(tradeId);
        }
    }

    // Calculate payout using stored percentage
    async calculatePayout(tradeId, investmentAmount) {
        const tradeInfo = await this.getTradeInfo(tradeId);
        
        if (!tradeInfo) {
            console.warn(`No payout info found for trade ${tradeId}`);
            return undefined;
        }
        
        const percentage = tradeInfo.payoutPercentage;
        const profit = investmentAmount * (percentage / 100);
        const totalPayout = investmentAmount + profit;
        
        return totalPayout;
    }
}

// Make globally available
window.TradePayoutStorage = TradePayoutStorage;
window.tradePayoutStorage = new TradePayoutStorage();
