const app = Vue.createApp({
    data() {
        return {
            orders: [], // Data pesanan yang diproses dan ditampilkan
            showDashboard: true,
            history: [],
            currentHistoryIndex: -1,
            maxHistory: 10,
            completedOrders: [], // Menyimpan pesanan yang sudah selesai untuk statistik
            showResumeDialog: false,
            dataFetchIntervalId: null, // Menyimpan ID interval untuk refresh
            showSettingsDialog: false,
            settings: {
                kdsId: 1, // **PENGATURAN BARU: ID untuk KDS ini**
                refreshIntervalSec: 5, // Default refresh 5 detik
                showSimilarItems: true,
            },
            tempSettings: {} // Untuk menampung perubahan settings sementara
        }
    },

    computed: {
        canUndo() {
            return this.currentHistoryIndex > 0;
        },
        canRedo() {
            return this.currentHistoryIndex < this.history.length - 1;
        },
        orderStats() {
            const stats = {};
            [...this.orders, ...this.completedOrders].forEach(order => {
                order.items.forEach(item => {
                    if (!stats[item.name]) {
                        stats[item.name] = { name: item.name, qty: 0, times: [] };
                    }
                    stats[item.name].qty += item.quantity;
                    if (item.startTime && item.endTime) {
                        const processTime = (new Date(item.endTime) - new Date(item.startTime)) / 1000;
                        stats[item.name].times.push(processTime);
                    }
                });
            });
            return Object.values(stats).map(stat => ({
                ...stat,
                fastest: stat.times.length ? Math.min(...stat.times) : 0,
                slowest: stat.times.length ? Math.max(...stat.times) : 0,
                average: stat.times.length ? stat.times.reduce((a, b) => a + b, 0) / stat.times.length : 0
            })).sort((a, b) => b.qty - a.qty);
        }
    },

    methods: {
        // --- MANAJEMEN PENGATURAN ---
        loadSettings() {
            const savedSettings = localStorage.getItem('kdsSettings');
            if (savedSettings) {
                this.settings = Object.assign({}, this.settings, JSON.parse(savedSettings));
            }
        },
        openSettingsDialog() {
            this.tempSettings = JSON.parse(JSON.stringify(this.settings));
            this.showSettingsDialog = true;
        },
        closeSettingsDialog() {
            this.showSettingsDialog = false;
        },
        saveSettings() {
            this.settings = JSON.parse(JSON.stringify(this.tempSettings));
            localStorage.setItem('kdsSettings', JSON.stringify(this.settings));
            this.closeSettingsDialog();
            
            clearInterval(this.dataFetchIntervalId);
            this.startDataFetching();
            this.fetchData(); // Langsung refresh data setelah simpan
            
            alert('Settings saved!');
        },

        // --- PENGAMBILAN & PEMROSESAN DATA ---
        async fetchData() {
            console.log(`Fetching data for KDS ID: ${this.settings.kdsId}...`);
            try {
                const response = await ambilPromise('kds_orders', 'kds_id', this.settings.kdsId, this.settings.kdsId);
                const newOrdersData = JSON.parse(response);
                this.processKdsData(newOrdersData);
            } catch (error) {
                console.error('Error fetching KDS data:', error);
            }
        },
        processKdsData(kdsData) {
            const groupedByOrder = kdsData.reduce((acc, item) => {
                if (!acc[item.order_id]) {
                    acc[item.order_id] = {
                        tableId: item.table_id,
                        orderId: item.order_id,
                        orderTime: item.order_time,
                        waiter: item.waiter,
                        items: [],
                    };
                }
                let toppingsArray = [];
                try { toppingsArray = JSON.parse(item.toppings); } catch (e) {}

                acc[item.order_id].items.push({
                    id: item.item_id,
                    db_id: item.id,
                    name: item.item_name,
                    quantity: parseInt(item.quantity),
                    note: item.note,
                    status: item.status || 'new', // Pastikan status ada
                    startTime: item.start_time || null,
                    endTime: item.end_time || null,
                    toppings: toppingsArray,
                    kgroup: item.kgroup
                });
                return acc;
            }, {});

            const processedOrders = Object.values(groupedByOrder).map(order => ({
                ...order,
                items: order.items.sort((a, b) => a.kgroup.localeCompare(b.kgroup) || a.name.localeCompare(b.name))
            }));
            
            if (JSON.stringify(this.orders) !== JSON.stringify(processedOrders)) {
                 this.orders = processedOrders;
                 // Hanya tambahkan ke history jika ini bukan hasil dari undo/redo
                 if (this.history[this.currentHistoryIndex] !== processedOrders) {
                    this.addToHistory(processedOrders);
                 }
                 console.log('KDS data updated!');
            }
        },
        startDataFetching() {
            const intervalMs = (this.settings.refreshIntervalSec >= 3 ? this.settings.refreshIntervalSec : 3) * 1000;
            this.dataFetchIntervalId = setInterval(this.fetchData, intervalMs);
        },

        // --- AKSI PADA PESANAN ---
        async cycleItemStatus(orderId, item) {
            let newStatus = '';
            if (!item.status || item.status === 'new') {
                newStatus = 'cooking';
                item.startTime = new Date().toISOString();
            } else if (item.status === 'cooking') {
                newStatus = 'done';
                item.endTime = new Date().toISOString();
            } else {
                return;
            }
            
            try {
                await updateKdsStatusPromise([item.db_id], newStatus);
                item.status = newStatus;
                this.updateOrders([...this.orders]);
            } catch (error) {
                console.error("Gagal update status item:", error);
                alert("Gagal update status item ke server.");
            }
        },
        async startAllItems(order) {
            const itemsToUpdate = order.items.filter(item => !item.status || item.status === 'new');
            if (itemsToUpdate.length === 0) return;

            const itemDbIds = itemsToUpdate.map(item => item.db_id);

            try {
                await updateKdsStatusPromise(itemDbIds, 'cooking');
                itemsToUpdate.forEach(item => {
                    item.status = 'cooking';
                    item.startTime = new Date().toISOString();
                });
                this.updateOrders([...this.orders]);
            } catch (error) {
                console.error("Gagal memulai semua item:", error);
                alert("Gagal memulai semua item di server.");
            }
        },
        async doneAll(order) {
            const itemDbIds = order.items.map(item => item.db_id);
            try {
                const response = await hapusPromise('kds_orders', 'id', itemDbIds);
                if (response.trim() === '1') {
                    this.completedOrders.push(order);
                    this.orders = this.orders.filter(o => o.orderId !== order.orderId);
                    this.addToHistory([...this.orders]);
                } else {
                    alert('Gagal menghapus pesanan dari server: ' + response);
                }
            } catch (error) {
                console.error('Error saat menyelesaikan pesanan:', error);
                alert('Terjadi kesalahan saat menghubungi server.');
            }
        },

        // --- FUNGSI BANTUAN & UI ---
        getSimilarItems(currentOrderId, itemName) {
            return this.orders
                .filter(order => order.orderId !== currentOrderId)
                .map(order => ({
                    table: order.tableId,
                    qty: order.items.filter(item => item.name === itemName && (!item.status || item.status === 'new'))
                                   .reduce((sum, item) => sum + item.quantity, 0)
                }))
                .filter(item => item.qty > 0);
        },
        getItemClass(item) {
            return {
                'status-new': !item.status || item.status === 'new',
                'status-cooking': item.status === 'cooking',
                'status-done': item.status === 'done',
                'undo-highlight': item.isUndoHighlight
            }
        },
        calculateOrderTime(order) {
            const start = moment(order.orderTime);
            const now = moment();
            const duration = moment.duration(now.diff(start));
            const minutes = Math.floor(duration.asMinutes());
            const seconds = Math.floor(duration.asSeconds() % 60);
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        },
        toggleDashboard() { this.showDashboard = !this.showDashboard; },
        toggleResumeDialog() { this.showResumeDialog = !this.showResumeDialog; },
        getUnprocessedSummary() {
            const summary = {};
            this.orders.forEach(order => {
                order.items.forEach(item => {
                    if (!item.status || item.status === 'new') {
                        if (!summary[item.name]) summary[item.name] = { total: 0, tables: {} };
                        summary[item.name].total += item.quantity;
                        if (!summary[item.name].tables[order.tableId]) summary[item.name].tables[order.tableId] = 0;
                        summary[item.name].tables[order.tableId] += item.quantity;
                    }
                });
            });
            return summary;
        },
        formatDateTime(dateTimeStr) { return moment(dateTimeStr).format('HH:mm:ss'); },
        formatTime(seconds) {
            if (!seconds) return '00:00';
            const m = Math.floor(seconds / 60);
            const s = Math.floor(seconds % 60);
            return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
        },
        formatToppings(toppings) {
            if (!toppings || !toppings.length) return '';
            return toppings
                .map(t => t.items.filter(i => i.checked).map(i => i.nama_toping).join(', '))
                .filter(Boolean).join(' | ');
        },

        // --- MANAJEMEN HISTORY (UNDO/REDO) ---
        updateOrders(newOrders) {
            this.orders = newOrders;
            this.addToHistory(newOrders);
        },
        addToHistory(orders) {
            this.history = this.history.slice(0, this.currentHistoryIndex + 1);
            this.history.push(JSON.parse(JSON.stringify(orders)));
            if (this.history.length > this.maxHistory) {
                this.history.shift();
            }
            this.currentHistoryIndex = this.history.length - 1;
        },
        // <<< GANTI SELURUH FUNGSI undoAction DENGAN INI >>>
        async undoAction() {
            if (!this.canUndo) return;

            const currentState = this.history[this.currentHistoryIndex];
            const previousState = this.history[this.currentHistoryIndex - 1];

            // --- Bagian 1: Tangani update status ---
            const currentStateItems = new Map(currentState.flatMap(o => o.items).map(i => [i.db_id, i]));
            const previousStateItems = new Map(previousState.flatMap(o => o.items).map(i => [i.db_id, i]));
            const updatesToPush = new Map();
            for (const [db_id, currentItem] of currentStateItems.entries()) {
                const previousItem = previousStateItems.get(db_id);
                if (previousItem && currentItem.status !== previousItem.status) {
                    const targetStatus = previousItem.status;
                    if (!updatesToPush.has(targetStatus)) {
                        updatesToPush.set(targetStatus, []);
                    }
                    updatesToPush.get(targetStatus).push(db_id);
                }
            }

            // --- Bagian 2: Tangani re-insert pesanan yang terhapus ---
            const itemsToReinsert = [];
            const currentStateOrderIds = new Set(currentState.map(o => o.orderId));
            const ordersToReinsert = previousState.filter(o => !currentStateOrderIds.has(o.orderId));

            if (ordersToReinsert.length > 0) {
                ordersToReinsert.forEach(order => {
                    order.items.forEach(item => {
                        itemsToReinsert.push({
                            kds_id: this.settings.kdsId,
                            order_id: order.orderId,
                            table_id: order.tableId,
                            waiter: order.waiter,
                            order_time: order.orderTime,
                            item_id: item.id,
                            item_name: item.name,
                            quantity: item.quantity,
                            note: item.note || '',
                            toppings: JSON.stringify(item.toppings || []),
                            kgroup: item.kgroup || '',
                            status: item.status || 'new',
                            brand: xbrand,
                            cab: xcab
                        });
                    });
                });
            }

            // --- Bagian 3: Eksekusi semua operasi database ---
            try {
                const dbPromises = [];
                for (const [status, ids] of updatesToPush.entries()) {
                    dbPromises.push(updateKdsStatusPromise(ids, status));
                }
                if (itemsToReinsert.length > 0) {
                    dbPromises.push(reinsertKdsPromise(itemsToReinsert));
                }
                
                if (dbPromises.length === 0) {
                     this.currentHistoryIndex--;
                     this.orders = JSON.parse(JSON.stringify(this.history[this.currentHistoryIndex]));
                     return;
                }

                await Promise.all(dbPromises);

                // --- Bagian 4: Ambil data terbaru dari server setelah undo berhasil ---
                await this.fetchData();
                alert('Undo berhasil disimpan ke server.');

            } catch (error) {
                console.error("Gagal melakukan undo di server:", error);
                alert("Gagal melakukan undo di server. Data mungkin tidak sinkron.");
            }
        },
        redoAction() {
            if (this.canRedo) {
                this.currentHistoryIndex++;
                this.orders = JSON.parse(JSON.stringify(this.history[this.currentHistoryIndex]));
            }
        },
    },

    created() {
        this.loadSettings();
        this.fetchData();
    },
    mounted() {
        this.startDataFetching();
        setInterval(() => { this.$forceUpdate(); }, 1000);
    },
    beforeUnmount() {
        clearInterval(this.dataFetchIntervalId);
    }
});

app.mount('#app');

var xbrand = '001';
var xcab = '002';

function ambilPromise(table, field, value1, value2) {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: "crud.php",
            data: {
                action: 'xambil',
                table: table,
                field: field,
                value: [value1, value2 || value1],
                xbrand : 'yyy',
                xcab   : 'yyy'
            },
            success: resolve,
            error: reject
        });
    });
}

function hapusPromise(table, idField, idValue) {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: "crud.php",
            data: {
                action: 'hapus_kds_items',
                ids: JSON.stringify(Array.isArray(idValue) ? idValue : [idValue])
            },
            success: resolve,
            error: reject
        });
    });
}

function updateKdsStatusPromise(ids, status) {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: "crud.php",
            data: {
                action: 'update_kds_status',
                ids: JSON.stringify(ids),
                status: status
            },
            success: resolve,
            error: reject
        });
    });
}

// <<< TAMBAHKAN FUNGSI BARU INI UNTUK RE-INSERT >>>
function reinsertKdsPromise(itemsData) {
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "POST",
            url: "crud.php",
            data: {
                action: 'tambah_kds', // Menggunakan kembali action yang sudah ada
                data: JSON.stringify(itemsData)
            },
            success: resolve,
            error: reject
        });
    });
}
