window.app = {
    async api(action, data = {}) {
        const r = await fetch('pages/api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({action, ...data})
        });
        
        const text = await r.text();
        try {
            return JSON.parse(text);
        } catch (e) {
            console.error("Server Error Response:", text);
            alert("Server Error! Check console for details.");
            return {success: false};
        }
    },

    // --- Create Functions ---
    async addGroup() {
        const name = document.getElementById('groupInput').value;
        if(!name) return alert('Enter Group Name');
        const res = await this.api('add_group', { name });
        if(res.success) location.reload();
    },

    async addRDP() {
        const name = document.getElementById('rdpInput').value;
        const groupId = document.getElementById('rdpGroupSelect').value;
        const ip = document.getElementById('rdpIp')?.value || '';
        const user = document.getElementById('rdpUsername')?.value || '';
        
        if(!name || !groupId) return alert('Name and Group are required');
        const res = await this.api('add_rdp', { name, group_id: groupId, ip: ip, username: user });
        if(res.success) location.reload();
    },

 filterRdpList(groupId) {
        const rdpSelect = document.getElementById('vmRdpSelect');
        rdpSelect.innerHTML = '<option value="">-- Select RDP --</option>';
        
        if (!groupId || !window.groupData) return;

        const group = window.groupData.find(g => g.id == groupId);
        if (group && group.rdps) {
            group.rdps.forEach(rdp => {
                const opt = document.createElement('option');
                opt.value = rdp.id;
                opt.textContent = rdp.name;
                rdpSelect.appendChild(opt);
            });
        }
    },

    async addVM() {
        const rdpId = document.getElementById('vmRdpSelect').value;
        const vmName = document.getElementById('vmInput').value;

        if (!rdpId || !vmName) {
            alert("Please select RDP and enter VM Name");
            return;
        }

        const res = await this.api('add_vm', {
            rdp_id: rdpId,
            name: vmName
        });

        if (res.success) {
            location.reload();
        } else {
            alert("Error: " + (res.error || "Failed to add VM"));
        }
    },


    // --- UI Helpers ---
    openModal(type) {
        document.getElementById('overlay').style.display = 'block';
        const modal = document.getElementById('modal-' + type) || document.getElementById(type + 'Modal');
        if(modal) modal.style.display = 'flex';
    },

    closeModal() {
        document.getElementById('overlay').style.display = 'none';
        document.querySelectorAll('.modal').forEach(m => m.style.display = 'none');
    },

    search() {
        const term = document.getElementById('searchInput').value.toLowerCase();
        document.querySelectorAll('.searchable-item').forEach(el => {
            const name = el.getAttribute('data-name').toLowerCase();
            el.style.display = name.includes(term) ? '' : 'none';
        });
    },

    // --- Actions ---
    async bulkDelete(type) {
        const ids = [...document.querySelectorAll('.' + type + '-check:checked')].map(c => c.value);
        if(!ids.length || !confirm('Delete ' + ids.length + ' items?')) return;
        const res = await this.api('delete_' + type + 's', {ids});
        if(res.success) location.reload();
    },

    openTerminal(v, rName, gName) {
        const base = window.location.origin + window.location.pathname.split('/index.php')[0];
        document.getElementById('termTitle').innerText = v.unit_id;
        document.getElementById('termVmId').innerText = v.v_id;
        document.getElementById('termGroup').innerText = gName;
        document.getElementById('termRdp').innerText = rName;
        document.getElementById('installCmd').value = `irm "${base}/static/install.ps1" -OutFile i.ps1; .\\i.ps1 -VMId ${v.v_id} -UnitId "${v.unit_id}" -Group "${gName}" -RdpNickname "${rName}" -BackendUrl "${base}"`;
        this.openModal('terminal');
    },

    async fetchBalance(vmId) {
        const res = await this.api('send_command', {vm_id: vmId, command: 'FETCH_BALANCE'});
        if(res.success) alert('Command queued');
    },

    copy(id) {
        const el = document.getElementById(id);
        navigator.clipboard.writeText(el.value);
    }
}; 