let currentOrderId = null;

function showNotification(message, type = 'success') {
    const notification = document.createElement('div');
    notification.className = `delivery-notification ${type}`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#d4edda' : '#f8d7da'};
        color: ${type === 'success' ? '#155724' : '#721c24'};
        padding: 15px 25px;
        border-radius: 8px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        z-index: 10000;
        max-width: 400px;
        animation: slideInRight 0.3s ease;
        border-left: 4px solid ${type === 'success' ? '#28a745' : '#dc3545'};
    `;
    
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}"></i>
        <span style="margin-left: 10px;">${message}</span>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => notification.remove(), 300);
    }, 4000);
}

function showCodeModal(orderId) {
    currentOrderId = orderId;
    document.getElementById('codeModal').style.display = 'flex';
    const input = document.getElementById('codeInput');
    input.value = '';
    input.focus();
    
    input.onkeypress = function(e) {
        if (e.key === 'Enter') {
            verifyCode();
        }
        return /[0-9]/.test(e.key) || e.key === 'Enter' || e.key === 'Backspace';
    };
    
    fetch('../php/send_delivery_code.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'order_id=' + orderId
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showNotification('Code sent to customer!', 'success');
        } else {
            showNotification('Error sending code: ' + data.message, 'error');
        }
    })
    .catch(() => {
        showNotification('Failed to send code', 'error');
    });
}

function closeCodeModal() {
    document.getElementById('codeModal').style.display = 'none';
    currentOrderId = null;
}

function verifyCode() {
    const code = document.getElementById('codeInput').value;
    
    if (!code || code.length !== 6) {
        showNotification('Enter 6 digit code', 'error');
        return;
    }
    
    fetch('../php/verify_delivery_code.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'order_id=' + currentOrderId + '&code=' + code
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showNotification('Order delivered!', 'success');
            closeCodeModal();
            setTimeout(() => location.reload(), 1500);
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(() => {
        showNotification('Error verifying code', 'error');
    });
}

function updateOrderStatus(orderId, newStatus) {
    const confirmMessages = {
        'ready': 'Are you sure you want to mark this order as READY?',
        'delivered': 'Are you sure you want to mark this order as DELIVERED?'
    };
    
    if (!confirm(confirmMessages[newStatus])) {
        return;
    }
    
    const formData = new FormData();
    formData.append('order_id', orderId);
    formData.append('order_status', newStatus);
    formData.append('update_order_status', '1');
    
    fetch('dashboard.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.text();
    })
    .then(data => {
        const successMessages = {
            'ready': 'Order marked as READY successfully! Customer has been notified.',
            'delivered': 'Order marked as DELIVERED successfully! Customer has been notified.'
        };
        
        showNotification(successMessages[newStatus], 'success');
        
        setTimeout(() => {
            location.reload();
        }, 1500);
    })
    .catch(error => {
        console.error('Update error:', error);
        showNotification('Failed to update order status. Please try again.', 'error');
    });
}

function pickupOrder(orderId) {
    if (!confirm('Are you sure you want to pickup this order from the customer?\n\nThis will:\n- Mark the order as picked up\n- Start processing\n- Notify the customer')) {
        return;
    }
    
    fetch('../php/pickup_order.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ order_id: orderId })
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showNotification('Order picked up successfully! Customer has been notified.', 'success');
            setTimeout(() => location.reload(), 1500);
        } else {
            showNotification(`Error: ${data.error}`, 'error');
        }
    })
    .catch(error => {
        console.error('Pickup error:', error);
        showNotification('Failed to pickup order. Please try again.', 'error');
    });
}

function notifyCustomerArrival(orderId) {
    if (!confirm('Are you sure you want to notify the customer of your arrival?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('order_id', orderId);
    
    fetch('../php/notify_customer_arrival.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showNotification(`Customer has been notified!\n\nCustomer: ${data.customer_name}\nPhone: ${data.customer_phone}`, 'success');
        } else {
            showNotification(`Error: ${data.message}`, 'error');
        }
    })
    .catch(error => {
        console.error('Notification error:', error);
        showNotification('Failed to send notification. Please try again.', 'error');
    });
}

setInterval(function() {
    const forms = document.querySelectorAll('form');
    let formActive = false;
    
    forms.forEach(form => {
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            if (input === document.activeElement) {
            }
        });
    });
    
    if (!formActive) {
        location.reload();
    }
}, 30000);

document.addEventListener('DOMContentLoaded', function() {
    const orderForms = document.querySelectorAll('form[method="POST"]');
    
    orderForms.forEach(form => {
        const submitBtn = form.querySelector('button[name="update_order_status"]');
        if (submitBtn) {
            form.addEventListener('submit', function(e) {
                e.preventDefault(); 
                
                const orderStatus = form.querySelector('input[name="order_status"]').value;
                const orderId = form.querySelector('input[name="order_id"]').value;
                
                let confirmMessage = '';
                if (orderStatus === 'delivered') {
                    confirmMessage = `Are you sure you want to mark Order #${orderId} as DELIVERED?`;
                } else if (orderStatus === 'ready') {
                    confirmMessage = `Are you sure you want to mark Order #${orderId} as READY for pickup?`;
                }
                
                if (confirmMessage && !confirm(confirmMessage)) {
                    return;
                }
                
                const originalText = submitBtn.innerHTML;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
                
                const formData = new FormData(form);
                
                fetch('../php/update_delivery.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        
                        const row = form.closest('tr');
                        const statusCell = row.querySelector('.delivery-status-badge');
                        const actionsCell = row.querySelector('td:last-child');
                        
                        statusCell.className = `delivery-status-badge delivery-status-${data.new_status}`;
                        statusCell.textContent = capitalizeFirst(data.new_status);
                        
                        if (data.new_status === 'delivered') {
                            actionsCell.innerHTML = '<span style="color: #28a745;"><i class="fas fa-check-circle"></i> Delivered</span>';
                        }
                        
                    } else {
                        showNotification(data.error || 'Failed to update order status', 'error');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('Network error occurred', 'error');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                });
            });
        }
    });
});

function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

document.addEventListener('DOMContentLoaded', function() {
    const successMsg = document.querySelector('.delivery-success-message');
    const errorMsg = document.querySelector('.delivery-error-message');
    
    if (successMsg) {
        setTimeout(() => {
            successMsg.style.opacity = '0';
            setTimeout(() => {
                successMsg.style.display = 'none';
            }, 300);
        }, 3000);
    }
    
    if (errorMsg) {
        setTimeout(() => {
            errorMsg.style.opacity = '0';
            setTimeout(() => {
                errorMsg.style.display = 'none';
            }, 300);
        }, 5000);
    }
});

document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function() {
            const submitBtn = form.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            }
        });
    });
});


document.addEventListener('DOMContentLoaded', function() {
    const statusSelect = document.getElementById('status');
    const locationInput = document.getElementById('location');
    
    if (statusSelect) {
        statusSelect.title = 'Keyboard shortcut: Alt + S';
    }
    
    if (locationInput) {
        locationInput.title = 'Keyboard shortcut: Alt + L';
    }
});

function updateClock() {
    const now = new Date();
    const timeString = now.toLocaleTimeString();
    const dateString = now.toLocaleDateString();
    
    let clockElement = document.getElementById('delivery-clock');
    if (!clockElement) {
        clockElement = document.createElement('div');
        clockElement.id = 'delivery-clock';
        clockElement.style.cssText = `
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 8px 12px;
            border-radius: 5px;
            font-size: 12px;
            z-index: 1000;
        `;
        document.body.appendChild(clockElement);
    }
    
    clockElement.innerHTML = `
        <div>${timeString}</div>
        <div style="font-size: 10px; opacity: 0.8;">${dateString}</div>
    `;
}

setInterval(updateClock, 1000);
updateClock(); 
