<div class="page-header">
    <h1>Pet Head Orders</h1>
    <div class="header-actions">
        <button class="button button-primary" onclick="window.location.href='/petprint/listPetOrders'">
            <span class="material-icons">refresh</span>
            Refresh Orders
        </button>
    </div>
</div>

<div class="orders-table">
    <div class="table-header">
        <div class="column order-id">Print Job ID</div> 
        <div class="column customer">Customer</div>
        <div class="column date">Date</div>
        <div class="column actions">Actions</div>
        <div class="column status">Status</div>
    </div>

    {{#each orders as |order|}}
    <div class="table-row">
        <div class="column order-id">{{order.id}}</div>
        <div class="column customer">
            <div class="customer-info">
                <span class="customer-name" onclick="toggleCustomerDetails('customer-{{order.id}}')">
                    {{order.customer.first_name}} {{order.customer.last_name}}
                    <span class="material-icons">expand_more</span>
                </span>
                <div id="customer-{{order.id}}" class="customer-details">
                    <div class="customer-email">
                        <span class="material-icons">email</span>
                        {{order.customer.email}}
                    </div>
                    <div class="customer-address">
                        <span class="material-icons">location_on</span>
                        <div>
                            {{order.customer.address1}}
                            {{#if order.customer.address2}}<br>{{order.customer.address2}}{{/if}}
                            <br>{{order.customer.city}}, {{order.customer.country}} {{order.customer.zip}}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="column date">{{order.date_created}}</div>
        <div class="column actions">
            <div class="action-buttons">
                <a href="/print_jobs/{{order.id}}.pdf" target="_blank" class="button button-secondary">
                    <span class="material-icons">description</span>
                    View Print File
                </a>
                <button onclick="regeneratePrintFile('{{order.id}}')" class="button button-secondary">
                    <span class="material-icons">refresh</span>
                    Regenerate
                </button>
            </div>
        </div>
        <div class="column status">
            <select class="status-select status-{{order.status}}" data-order-id="{{order.id}}" onchange="updateStatus(this)">
                <option value="pending" {{#if (selectCheck order.status 'pending')}}selected{{/if}}>
                    Pending
                </option>
                <option value="in_progress" {{#if (selectCheck order.status 'in_progress')}}selected{{/if}}>
                    In Progress
                </option>
                <option value="shipped" {{#if (selectCheck order.status 'shipped')}}selected{{/if}}>
                    Shipped
                </option>
            <option value="queued" {{#if (selectCheck order.status 'queued')}}selected{{/if}}>
                Queued
            </option>
            </select>
        </div>
    </div>
    {{/each}}

    {{#unless orders}}
    <div class="no-orders">
        <span class="material-icons">inbox</span>
        <p>No orders found</p>
    </div>
    {{/unless}}
</div>

<style>
.orders-table {
    background: var(--bg-secondary);
    border-radius: 8px;
    overflow: hidden;
    margin-top: 2rem;
}

.table-header {
    display: flex;
    padding: 1rem;
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    font-weight: 500;
    color: var(--text-secondary);
}

.table-row {
    display: flex;
    padding: 1rem;
    border-bottom: 1px solid var(--border-color);
    align-items: center;
}

.column {
    padding: 0 1rem;
}

.column.order-id {
    width: 150px;
}

.column.customer {
    flex: 1;
}

.column.date {
    width: 150px;
}

.column.actions {
    width: 250px;
}

.column.status {
    width: 150px;
}

.customer-info {
    position: relative;
}

.customer-name {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
    color: var(--accent-color);
}

.customer-details {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 1rem;
    margin-top: 0.5rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    min-width: 300px;
}

.customer-email,
.customer-address {
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
    color: var(--text-secondary);
}

.customer-address:last-child {
    margin-bottom: 0;
}

.action-buttons {
    display: flex;
    gap: 0.5rem;
}

.status-select {
    padding: 0.5rem;
    border-radius: 4px;
    border: 1px solid var(--border-color);
    background: var(--bg-secondary);
    color: var(--text-primary);
    width: 100%;
    cursor: pointer;
}

.status-select.status-pending {
    background-color: #FFF3CD;
    color: #856404;
}

.status-select.status-in_progress {
    background-color: #D4EDDA;
    color: #155724;
}

.status-select.status-shipped {
    background-color: #D4D4D4;
    color: #383838;
}

.no-orders {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 3rem;
    color: var(--text-secondary);
    gap: 1rem;
}

.no-orders .material-icons {
    font-size: 48px;
    opacity: 0.5;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.spinning {
    animation: spin 1s linear infinite;
}
</style>

<script>
function startup() {
    setInitialStatus();
}

function toggleCustomerDetails(customerId) {
    const customerDetails = document.getElementById(customerId);
    const allDetails = document.querySelectorAll('.customer-details');
    
    // Close all other open details
    allDetails.forEach(detail => {
        if (detail.id !== customerId && detail.style.display === 'block') {
            detail.style.display = 'none';
        }
    });
    
    customerDetails.style.display = customerDetails.style.display === 'block' ? 'none' : 'block';
}

function setInitialStatus() {
    const selectElements = document.querySelectorAll('.status-select');
    selectElements.forEach(selectElement => {
        const orderId = selectElement.dataset.orderId;
        const newStatus = selectElement.value;
        selectElement.className = `status-select status-${newStatus}`;
    });
}

function updateStatus(selectElement) {
    const orderId = selectElement.dataset.orderId;
    const newStatus = selectElement.value;
    
    fetch('/orders/updateOrderStatus', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            orderId: orderId,
            status: newStatus
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status == 1) {
            selectElement.className = `status-select status-${newStatus}`;
        } else {
            alert('Failed to update status');
            selectElement.value = selectElement.getAttribute('data-previous-status');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating status');
        selectElement.value = selectElement.getAttribute('data-previous-status');
    });
}

function regeneratePrintFile(orderId) {
    const button = event.target.closest('button');
    const icon = button.querySelector('.material-icons');

    // Start spinning
    icon.classList.add('spinning');
    button.disabled = true;

    fetch('/petprint/regeneratePrintFile', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ orderId: orderId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status == 1) {
            alert('Print file regenerated successfully');
        } else {
            alert('Failed to regenerate print file');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error regenerating print file');
    })
    .finally(() => {
        // Stop spinning and re-enable the button
        icon.classList.remove('spinning');
        button.disabled = false;
    });   
}
</script>
