@model LittleShop.DTOs.OrderDto

@{
    ViewData["Title"] = $"Order #{Model.Id.ToString().Substring(0, 8)}";
}

<div class="row mb-4">
    <div class="col">
        <h1><i class="fas fa-shopping-cart"></i> Order Details</h1>
        <p class="text-muted">Order ID: @Model.Id</p>
    </div>
    <div class="col-auto">
        @if (Model.Customer != null)
        {
            <a href="@Url.Action("Customer", "Messages", new { area = "Admin", id = Model.Customer.Id })" class="btn btn-success">
                <i class="fas fa-comments"></i> View Conversation
            </a>
            <button type="button" class="btn btn-primary" onclick="showMessageModal('@Model.Id', '@Model.Customer.DisplayName')">
                <i class="fas fa-comment"></i> Send Order Update
            </button>
        }
        <a href="@Url.Action("Edit", new { id = Model.Id })" class="btn btn-primary">
            <i class="fas fa-edit"></i> Edit Order
        </a>
        <a href="@Url.Action("Index")" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back to Orders
        </a>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-info-circle"></i> Order Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        @if (Model.Customer != null)
                        {
                            <p><strong>Customer:</strong> @Model.Customer.DisplayName 
                                @if (!string.IsNullOrEmpty(Model.Customer.TelegramUsername))
                                {
                                    <span class="text-muted">(@@@Model.Customer.TelegramUsername)</span>
                                }
                            </p>
                            <p><strong>Customer Type:</strong> <span class="badge bg-info">@Model.Customer.CustomerType</span></p>
                            @if (Model.Customer.RiskScore > 0)
                            {
                                <p><strong>Risk Score:</strong> 
                                    <span class="badge @(Model.Customer.RiskScore > 50 ? "bg-danger" : Model.Customer.RiskScore > 25 ? "bg-warning" : "bg-success")">
                                        @Model.Customer.RiskScore/100
                                    </span>
                                </p>
                            }
                        }
                        else if (!string.IsNullOrEmpty(Model.IdentityReference))
                        {
                            <p><strong>Identity Reference:</strong> @Model.IdentityReference</p>
                        }
                        <p><strong>Status:</strong> 
                            @{
                                var badgeClass = Model.Status switch
                                {
                                    LittleShop.Enums.OrderStatus.PendingPayment => "bg-warning",
                                    LittleShop.Enums.OrderStatus.PaymentReceived => "bg-success",
                                    LittleShop.Enums.OrderStatus.Processing => "bg-info",
                                    LittleShop.Enums.OrderStatus.Shipped => "bg-primary",
                                    LittleShop.Enums.OrderStatus.Delivered => "bg-success",
                                    LittleShop.Enums.OrderStatus.Cancelled => "bg-danger",
                                    _ => "bg-secondary"
                                };
                            }
                            <span class="badge @badgeClass">@Model.Status</span>
                        </p>
                        <p><strong>Total Amount:</strong> £@Model.TotalAmount</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Created:</strong> @Model.CreatedAt.ToString("MMM dd, yyyy HH:mm")</p>
                        @if (Model.PaidAt.HasValue)
                        {
                            <p><strong>Paid:</strong> @Model.PaidAt.Value.ToString("MMM dd, yyyy HH:mm")</p>
                        }
                        @if (Model.ShippedAt.HasValue)
                        {
                            <p><strong>Shipped:</strong> @Model.ShippedAt.Value.ToString("MMM dd, yyyy HH:mm")</p>
                        }
                        @if (!string.IsNullOrEmpty(Model.TrackingNumber))
                        {
                            <p><strong>Tracking:</strong> @Model.TrackingNumber</p>
                        }
                    </div>
                </div>
                @if (!string.IsNullOrEmpty(Model.Notes))
                {
                    <div class="mt-3">
                        <strong>Notes:</strong>
                        <p class="text-muted">@Model.Notes</p>
                    </div>
                }
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-truck"></i> Shipping Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Name:</strong> @Model.ShippingName</p>
                        <p><strong>Address:</strong> @Model.ShippingAddress</p>
                        <p><strong>City:</strong> @Model.ShippingCity</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Post Code:</strong> @Model.ShippingPostCode</p>
                        <p><strong>Country:</strong> @Model.ShippingCountry</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-list"></i> Order Items</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Quantity</th>
                                <th>Unit Price</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var item in Model.Items)
                            {
                                <tr>
                                    <td>@item.ProductName</td>
                                    <td>@item.Quantity</td>
                                    <td>£@item.UnitPrice</td>
                                    <td><strong>£@item.TotalPrice</strong></td>
                                </tr>
                            }
                        </tbody>
                        <tfoot>
                            <tr>
                                <th colspan="3">Total</th>
                                <th>£@Model.TotalAmount</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header">
                <h5><i class="fas fa-edit"></i> Update Status</h5>
            </div>
            <div class="card-body">
                <form method="post" action="@Url.Action("UpdateStatus", new { id = Model.Id })">
                    <div class="mb-3">
                        <label for="Status" class="form-label">Status</label>
                        <select name="Status" class="form-select">
                            <option value="0" selected="@(Model.Status == LittleShop.Enums.OrderStatus.PendingPayment)">Pending Payment</option>
                            <option value="1" selected="@(Model.Status == LittleShop.Enums.OrderStatus.PaymentReceived)">Payment Received</option>
                            <option value="2" selected="@(Model.Status == LittleShop.Enums.OrderStatus.Processing)">Processing</option>
                            <option value="3" selected="@(Model.Status == LittleShop.Enums.OrderStatus.PickingAndPacking)">Picking & Packing</option>
                            <option value="4" selected="@(Model.Status == LittleShop.Enums.OrderStatus.Shipped)">Shipped</option>
                            <option value="5" selected="@(Model.Status == LittleShop.Enums.OrderStatus.Delivered)">Delivered</option>
                            <option value="6" selected="@(Model.Status == LittleShop.Enums.OrderStatus.Cancelled)">Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="TrackingNumber" class="form-label">Tracking Number</label>
                        <input name="TrackingNumber" value="@Model.TrackingNumber" class="form-control" placeholder="Royal Mail tracking number" />
                    </div>
                    
                    <div class="mb-3">
                        <label for="Notes" class="form-label">Notes</label>
                        <textarea name="Notes" class="form-control" rows="3" placeholder="Additional notes">@Model.Notes</textarea>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Update Order
                    </button>
                </form>
            </div>
        </div>

        @if (Model.Payments.Any())
        {
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-coins"></i> Crypto Payments</h5>
                </div>
                <div class="card-body">
                    @foreach (var payment in Model.Payments)
                    {
                        <div class="mb-3 p-2 border rounded">
                            <div class="d-flex justify-content-between">
                                <strong>@payment.Currency</strong>
                                <span class="badge bg-info">@payment.Status</span>
                            </div>
                            <small class="text-muted d-block">Required: @payment.RequiredAmount @payment.Currency</small>
                            <small class="text-muted d-block">Paid: @payment.PaidAmount @payment.Currency</small>
                            @if (!string.IsNullOrEmpty(payment.WalletAddress))
                            {
                                <small class="text-muted d-block">Address: @payment.WalletAddress.Substring(0, 10)...</small>
                            }
                        </div>
                    }
                </div>
            </div>
        }
    </div>
</div>

@if (Model.Customer != null)
{
    <!-- Customer Messaging Modal -->
    <div class="modal fade" id="messageModal" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="messageModalLabel">
                        <i class="fas fa-comment"></i> Message Customer: <span id="customerName"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="messageForm">
                        <input type="hidden" id="orderId" name="orderId" />
                        <input type="hidden" id="customerId" name="customerId" value="@Model.Customer.Id" />
                        
                        <div class="mb-3">
                            <label for="messageType" class="form-label">Message Type</label>
                            <select class="form-select" id="messageType" name="messageType" required>
                                <option value="0">Order Update</option>
                                <option value="1">Payment Reminder</option>
                                <option value="2">Shipping Information</option>
                                <option value="3">Customer Service</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="messageSubject" class="form-label">Subject</label>
                            <input type="text" class="form-control" id="messageSubject" name="subject" required 
                                   placeholder="Brief subject line..." maxlength="100">
                        </div>
                        
                        <div class="mb-3">
                            <label for="messageContent" class="form-label">Message</label>
                            <textarea class="form-control" id="messageContent" name="content" rows="4" required 
                                      placeholder="Type your message to the customer..." maxlength="1000"></textarea>
                            <div class="form-text">Message will be delivered via Telegram</div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="isUrgent" name="isUrgent">
                                <label class="form-check-label" for="isUrgent">
                                    Mark as urgent (higher priority delivery)
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="sendMessage()">
                        <i class="fas fa-paper-plane"></i> Send Message
                    </button>
                </div>
            </div>
        </div>
    </div>
}

<script>
function showMessageModal(orderId, customerName) {
    document.getElementById('orderId').value = orderId;
    document.getElementById('customerName').textContent = customerName;
    
    // Clear previous form data
    document.getElementById('messageForm').reset();
    document.getElementById('orderId').value = orderId; // Reset cleared this
    
    // Show modal
    var modal = new bootstrap.Modal(document.getElementById('messageModal'));
    modal.show();
}

function sendMessage() {
    const form = document.getElementById('messageForm');
    const formData = new FormData(form);
    
    const messageData = {
        customerId: formData.get('customerId'),
        orderId: formData.get('orderId'),
        type: parseInt(formData.get('messageType')),
        subject: formData.get('subject'),
        content: formData.get('content'),
        isUrgent: formData.get('isUrgent') === 'on',
        priority: formData.get('isUrgent') === 'on' ? 1 : 5
    };
    
    // Send message via API
    fetch('/api/messages', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + sessionStorage.getItem('authToken')
        },
        body: JSON.stringify(messageData)
    })
    .then(response => {
        if (response.ok) {
            // Close modal and show success
            var modal = bootstrap.Modal.getInstance(document.getElementById('messageModal'));
            modal.hide();
            
            // Show success message
            alert('Message sent successfully! The customer will receive it via Telegram.');
            
            // Optionally refresh the page to show updated communication history
            window.location.reload();
        } else {
            response.text().then(error => {
                alert('Failed to send message: ' + error);
            });
        }
    })
    .catch(error => {
        console.error('Error sending message:', error);
        alert('Error sending message. Please try again.');
    });
}
</script>