$(document).ready(function() {
    // Check current shift status
    checkShiftStatus();
    
    // Start Shift Button
    $('#startShiftBtn').click(function() {
        const startingCash = $('#startingCash').val();
        if (!startingCash || isNaN(startingCash)) {
            showAlert('Please enter a valid starting cash amount', 'danger');
            return;
        }
        
        $.ajax({
            url: './database/start_shift.kts.php',
            method: 'POST',
            data: { starting_cash: startingCash },
            beforeSend: function() {
                showLoading(true);
            },
            success: function(response) {
                const data = JSON.parse(response);
                if (data.success) {
                    showAlert('Shift started successfully', 'success');
                    checkShiftStatus();
                    $('#startingCashModal').modal('hide');
                    $('#startingCash').val('');
                } else {
                    showAlert(data.message, 'danger');
                }
            },
            error: function() {
                showAlert('Error starting shift', 'danger');
            },
            complete: function() {
                showLoading(false);
            }
        });
    });
    
    // End Shift Button
    $('#endShiftBtn').click(function() {
        const endingCash = $('#endingCash').val();
        if (!endingCash || isNaN(endingCash)) {
            showAlert('Please enter a valid ending cash amount', 'danger');
            return;
        }
        
        $.ajax({
            url: './database/end_shift.kts.php',
            method: 'POST',
            data: { ending_cash: endingCash },
            beforeSend: function() {
                showLoading(true);
            },
            success: function(response) {
                const data = JSON.parse(response);
                if (data.success) {
                    showAlert('Shift ended successfully', 'success');
                    checkShiftStatus();
                    $('#endingCashModal').modal('hide');
                    $('#endingCash').val('');
                    loadShiftReport(data.shift_id);
                } else {
                    showAlert(data.message, 'danger');
                }
            },
            error: function() {
                showAlert('Error ending shift', 'danger');
            },
            complete: function() {
                showLoading(false);
            }
        });
    });
    
    // Print Report Button
    $('#printReportBtn').click(function() {
        window.print();
    });
    
    // Check shift status
    function checkShiftStatus() {
        $.ajax({
            url: './database/get_shift_data.kts.php',
            method: 'GET',
            data: { action: 'check_status' },
            success: function(response) {
                const data = JSON.parse(response);
                updateShiftUI(data);
                
                if (data.active_shift) {
                    loadShiftReport(data.shift_id);
                }
            },
            error: function() {
                showAlert('Error checking shift status', 'danger');
            }
        });
    }
    
    // Load shift report
    function loadShiftReport(shiftId) {
        $.ajax({
            url: './database/get_shift_data.kts.php',
            method: 'GET',
            data: { action: 'get_report', shift_id: shiftId },
            beforeSend: function() {
                showLoading(true);
                $('.report-content').html('');
            },
            success: function(response) {
                const data = JSON.parse(response);
                if (data.success) {
                    updateReportUI(data);
                } else {
                    showAlert(data.message, 'danger');
                }
            },
            error: function() {
                showAlert('Error loading shift report', 'danger');
            },
            complete: function() {
                showLoading(false);
            }
        });
    }
    
    // Update UI based on shift status
    function updateShiftUI(data) {
        if (data.active_shift) {
            $('.shift-status').html('<span class="badge badge-success">Shift Active</span>');
            $('.shift-info').html(`
                <strong>Started:</strong> ${data.start_time} | 
                <strong>Employee:</strong> ${data.employee_name} | 
                <strong>Starting Cash:</strong> $${data.starting_cash}
            `);
            $('#startShiftSection').hide();
            $('#endShiftSection').show();
            $('#reportSection').show();
        } else {
            $('.shift-status').html('<span class="badge badge-secondary">No Active Shift</span>');
            $('.shift-info').html('No active shift. Please start a new shift.');
            $('#startShiftSection').show();
            $('#endShiftSection').hide();
            $('#reportSection').hide();
        }
    }
    
    // Update report UI
    function updateReportUI(data) {
        // Update payment methods summary
        let paymentMethodsHTML = '';
        data.payment_methods.forEach(method => {
            paymentMethodsHTML += `
                <div class="payment-method-card ${method.payment_method.toLowerCase()}">
                    <div class="method-name">${method.payment_method}</div>
                    <div class="method-amount">$${method.total_amount.toFixed(2)}</div>
                    <div class="method-count">${method.transaction_count} transactions</div>
                </div>
            `;
        });
        $('.payment-methods').html(paymentMethodsHTML);
        
        // Update totals
        $('#totalAmount').text(`$${data.totals.total_amount.toFixed(2)}`);
        $('#totalTransactions').text(data.totals.transaction_count);
        
        // Update transactions table
        let transactionsHTML = '';
        data.transactions.forEach(trans => {
            transactionsHTML += `
                <tr>
                    <td>${trans.trans_id}</td>
                    <td>${trans.seller_name}</td>
                    <td>${trans.seller_date}</td>
                    <td>$${trans.total}</td>
                    <td>${trans.payment_method}</td>
                    <td>$${trans.amount}</td>
                </tr>
            `;
        });
        $('#transactionsTable tbody').html(transactionsHTML);
    }
    
    // Show loading indicator
    function showLoading(show) {
        if (show) {
            $('.loading').show();
        } else {
            $('.loading').hide();
        }
    }
    
    // Show alert message
    function showAlert(message, type) {
        const alertHTML = `
            <div class="alert alert-${type}">
                ${message}
            </div>
        `;
        $('#alertContainer').html(alertHTML);
        setTimeout(() => {
            $('#alertContainer').empty();
        }, 5000);
    }
});