// Data structure
let items = [
    {
        "id": "0000260513",
        "kode": "19",
        "name": "Kwetiau Goreng",
        "meja": "17",
        "quantity": 3,
        "split": ""
    },
    {
        "id": "0000059509",
        "kode": "17",
        "name": "Mie Goreng",
        "meja": "17",
        "quantity": 2,
        "split": ""
    },
    {
        "id": "0000160851",
        "kode": "18",
        "name": "Mie Ayam",
        "meja": "17",
        "quantity": 4,
        "split": ""
    },
    {
        "id": "00002605131",
        "kode": "19",
        "name": "Kwetiau Goreng",
        "meja": "17",
        "quantity": 3,
        "split": ""
    },
    {
        "id": "00000595091",
        "kode": "17",
        "name": "Mie Goreng",
        "meja": "17",
        "quantity": 2,
        "split": ""
    },
    {
        "id": "00001608511",
        "kode": "18",
        "name": "Mie Ayam",
        "meja": "17",
        "quantity": 4,
        "split": ""
    },
    {
        "id": "00002605132",
        "kode": "19",
        "name": "Kwetiau Goreng",
        "meja": "17",
        "quantity": 3,
        "split": ""
    },
    {
        "id": "00000595092",
        "kode": "17",
        "name": "Mie Goreng",
        "meja": "17",
        "quantity": 2,
        "split": ""
    },
    {
        "id": "00001608512",
        "kode": "18",
        "name": "Mie Ayam",
        "meja": "17",
        "quantity": 4,
        "split": ""
    } ,
    {
        "id": "0000260513",
        "kode": "19",
        "name": "Kwetiau Goreng",
        "meja": "17",
        "quantity": 3,
        "split": ""
    },
    {
        "id": "0000059509",
        "kode": "17",
        "name": "Mie Goreng",
        "meja": "17",
        "quantity": 2,
        "split": ""
    },
    {
        "id": "0000160851",
        "kode": "18",
        "name": "Mie Ayam",
        "meja": "17",
        "quantity": 4,
        "split": ""
    }           
];

let splitGrids = {};
let selectedGridCode = '';
let selectedMasterItem = '';
let selectedSplitItem = ''; // Track selected item in split grid
const GRID_CODES = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Get table number from URL parameter
function getTableNumber() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('meja') || '';
}

// DOM Elements
const masterGridBody = document.getElementById('masterGridBody');
const splitGridsContainer = document.getElementById('splitGridsContainer');
const addGridBtn = document.getElementById('addGridBtn');
const masterTitle = document.getElementById('masterTitle');

// Update master grid title
function updateMasterTitle() {
    const tableNumber = getTableNumber();
    if (tableNumber) {
        masterTitle.textContent = `Master Grid ${tableNumber}`;
    }
}

// Split 1 pc function
function moveOnePiece() {
    if (!selectedGridCode || !selectedMasterItem) return;
    
    const itemIndex = items.findIndex(item => item.id === selectedMasterItem);
    if (itemIndex === -1 || items[itemIndex].quantity <= 0) return;

    // If item already exists in target grid
    const existingInTarget = items.find(item => 
        item.id === selectedMasterItem && 
        item.split === selectedGridCode
    );

    if (existingInTarget) {
        // Increase quantity in target
        existingInTarget.quantity++;
        // Decrease quantity in source
        items[itemIndex].quantity--;

        // Remove source item if quantity reaches 0
        if (items[itemIndex].quantity === 0) {
            items.splice(itemIndex, 1);
        }
    } else {
        // Create new item in target with quantity 1
        const sourceItem = items[itemIndex];
        const newItem = {
            ...sourceItem,
            quantity: 1,
            split: selectedGridCode
        };
        items.push(newItem);
        
        // Decrease quantity in source
        sourceItem.quantity--;
        
        // Remove source item if quantity reaches 0
        if (sourceItem.quantity === 0) {
            items.splice(itemIndex, 1);
        }
    }

    renderAll();
}

// Move entire menu
function moveEntireMenu() {
    if (!selectedGridCode || !selectedMasterItem) return;
    
    const itemIndex = items.findIndex(item => item.id === selectedMasterItem);
    if (itemIndex === -1) return;

    const sourceItem = items[itemIndex];
    
    // If item already exists in target grid
    const existingInTarget = items.find(item => 
        item.id === selectedMasterItem && 
        item.split === selectedGridCode
    );

    if (existingInTarget) {
        existingInTarget.quantity += sourceItem.quantity;
        items.splice(itemIndex, 1);
    } else {
        items[itemIndex].split = selectedGridCode;
    }

    renderAll();
}

// Move all items
function moveAllItems() {
    if (!selectedGridCode) return;
    
    const unsplitItems = items.filter(item => item.split === '');
    unsplitItems.forEach(item => {
        item.split = selectedGridCode;
    });

    renderAll();
}

// Return 1 pc to master
function returnOnePiece() {
    if (!selectedGridCode || !selectedSplitItem) {
        alert('Please select an item from split grid first');
        return;
    }
    
    const itemIndex = items.findIndex(item => 
        item.id === selectedSplitItem && 
        item.split === selectedGridCode
    );
    
    if (itemIndex === -1) return;

    const splitItem = items[itemIndex];
    
    // Cari atau buat item di master grid
    let masterItem = items.find(item => 
        item.id === selectedSplitItem && 
        item.split === ''
    );

    if (masterItem) {
        // Jika item sudah ada di master, tambah quantity
        masterItem.quantity++;
    } else {
        // Jika item belum ada di master, buat baru
        masterItem = {
            ...splitItem,
            quantity: 1,
            split: ''
        };
        items.push(masterItem);
    }

    // Kurangi quantity di split grid
    splitItem.quantity--;
    
    // Hapus item dari split grid jika quantity 0
    if (splitItem.quantity === 0) {
        items.splice(itemIndex, 1);
    }

    renderAll();
}

// Perbaikan fungsi returnEntireMenu
function returnEntireMenu() {
    if (!selectedGridCode || !selectedSplitItem) {
        alert('Please select an item from split grid first');
        return;
    }
    
    const itemIndex = items.findIndex(item => 
        item.id === selectedSplitItem && 
        item.split === selectedGridCode
    );
    
    if (itemIndex === -1) return;

    const splitItem = items[itemIndex];
    
    // Cari atau buat item di master grid
    let masterItem = items.find(item => 
        item.id === selectedSplitItem && 
        item.split === ''
    );

    if (masterItem) {
        // Jika item sudah ada di master, tambah semua quantity
        masterItem.quantity += splitItem.quantity;
        items.splice(itemIndex, 1);
    } else {
        // Jika item belum ada di master, pindahkan langsung
        splitItem.split = '';
    }

    selectedSplitItem = ''; // Reset selection
    renderAll();
}

// Return all items to master
function returnAllItems() {
    if (!selectedGridCode) return;
    
    items.forEach(item => {
        if (item.split === selectedGridCode) {
            const masterItem = items.find(i => 
                i.id === item.id && 
                i.split === ''
            );
            
            if (masterItem) {
                masterItem.quantity += item.quantity;
                const index = items.indexOf(item);
                items.splice(index, 1);
            } else {
                item.split = '';
            }
        }
    });

    renderAll();
}

// Functions for bill and payment
function handleBill(code) {
    alert(`Bill for Grid ${code}`);
}

function handlePayment(code) {
    alert(`Payment for Grid ${code}`);
}

// Render functions
function renderMasterGrid() {
    const unsplitItems = items.filter(item => item.split === '');
    masterGridBody.innerHTML = unsplitItems.map(item => `
        <tr onclick="selectMasterItem('${item.id}')" 
            class="master-item ${selectedMasterItem === item.id ? 'selected' : ''}">
            <td>${item.name}</td>
            <td>${item.quantity}</td>
            <td>${item.kode}</td>
        </tr>
    `).join('');
}

function renderSplitGrids() {
    splitGridsContainer.innerHTML = Object.keys(splitGrids).map(code => `
        <div class="grid ${selectedGridCode === code ? 'grid-selected' : ''}" id="grid-${code}">
            <div class="grid-header">
                <h3 class="grid-title">Grid ${code}</h3>
                <div class="grid-header-buttons">
                    <button class="btn btn-primary" onclick="handleBill('${code}')">Bill</button>
                    <button class="btn btn-success" onclick="handlePayment('${code}')">Payment</button>
                    <button class="btn btn-danger" onclick="removeGrid('${code}')">Remove</button>
                </div>
            </div>
            <div class="table-container" onclick="selectGrid('${code}')">
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Quantity</th>
                            <th>Code</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${renderSplitGridItems(code)}
                    </tbody>
                </table>
            </div>
        </div>
    `).join('');
}

function renderSplitGridItems(code) {
    const splitItems = items.filter(item => item.split === code);
    return splitItems.map(item => `
        <tr onclick="selectSplitItem('${item.id}', event, '${code}')" 
            class="${selectedSplitItem === item.id && selectedGridCode === code ? 'selected' : ''}">
            <td>${item.name}</td>
            <td>${item.quantity}</td>
            <td>${item.kode}</td>
        </tr>
    `).join('');
}

function renderControlButtons() {
    const controlsContainer = document.getElementById('controlButtons');
    if (!controlsContainer) return;

    controlsContainer.innerHTML = `
        <button class="control-button" onclick="moveOnePiece()">→ Move 1pc</button>
        <button class="control-button" onclick="moveEntireMenu()">⇒ Move Menu</button>
        <button class="control-button" onclick="moveAllItems()">⇛ Move All</button>
        <div class="control-spacer"></div>
        <button class="control-button" onclick="returnOnePiece()">← Return 1pc</button>
        <button class="control-button" onclick="returnEntireMenu()">⇐ Return Menu</button>
        <button class="control-button" onclick="returnAllItems()">⇚ Return All</button>
    `;
}

function renderAll() {
    renderMasterGrid();
    renderSplitGrids();
    renderControlButtons();
}

// Selection functions
function selectMasterItem(id) {
    selectedMasterItem = id;
    selectedSplitItem = ''; // Reset split item selection when selecting master item
    renderAll();
}

function selectGrid(code) {
    selectedGridCode = code;
    selectedSplitItem = ''; // Reset split item selection when changing grids
    renderAll();
}

function selectSplitItem(id, event, code) {
    // Hentikan event bubbling
    event.stopPropagation();
    
    selectedSplitItem = id;
    selectedGridCode = code; // Pastikan grid yang benar terpilih
    selectedMasterItem = ''; // Reset master item selection
    renderAll();
}

// Helper functions
function getNextAvailableGridCode() {
    const usedCodes = Object.keys(splitGrids);
    return GRID_CODES.split('').find(code => !usedCodes.includes(code));
}

function addGrid() {
    const nextCode = getNextAvailableGridCode();
    if (nextCode) {
        splitGrids[nextCode] = [];
        selectGrid(nextCode);
        renderAll();
    }
}

function removeGrid(code) {
    returnAllItems(); // Return all items to master before removing
    delete splitGrids[code];
    if (selectedGridCode === code) {
        selectedGridCode = '';
        selectedSplitItem = ''; // Reset selected split item
    }
    renderAll();
}

function logSelections() {
    console.log('Selected Grid:', selectedGridCode);
    console.log('Selected Split Item:', selectedSplitItem);
    console.log('Selected Master Item:', selectedMasterItem);
}

// Modifikasi renderControlButtons untuk menambah visual feedback
function renderControlButtons() {
    const controlsContainer = document.getElementById('controlButtons');
    if (!controlsContainer) return;

    const isItemSelected = selectedSplitItem !== '';
    const buttonClass = isItemSelected ? 'control-button active' : 'control-button disabled';

    controlsContainer.innerHTML = `
        <button class="control-button" onclick="moveOnePiece()">→ Move 1pc</button>
        <button class="control-button" onclick="moveEntireMenu()">⇒ Move Menu</button>
        <button class="control-button" onclick="moveAllItems()">⇛ Move All</button>
        <div class="control-spacer"></div>
        <button class="${buttonClass}" onclick="returnOnePiece()">← Return 1pc</button>
        <button class="${buttonClass}" onclick="returnEntireMenu()">⇐ Return Menu</button>
        <button class="control-button" onclick="returnAllItems()">⇚ Return All</button>
    `;
}

// Initialize
addGridBtn.addEventListener('click', addGrid);
updateMasterTitle(); // Initialize master title with table number
renderAll();