<?php
include 'db.php';
include 'layout.php';

// Handle status updates
if ($_POST['action'] === 'update_status') {
    $order_id = intval($_POST['order_id']);
    $new_status = $_POST['new_status'];
    
    $stmt = $conn->prepare("UPDATE delivery_orders SET delivery_status = ? WHERE id = ?");
    $stmt->bind_param("si", $new_status, $order_id);
    
    if ($stmt->execute()) {
        $success_message = "Delivery status updated successfully!";
    } else {
        $error_message = "Error updating status: " . $conn->error;
    }
    $stmt->close();
}

// Fetch delivery orders with customer and rider details
$query = "
    SELECT 
        do.*,
        s.invoice_number,
        s.customer_name,
        s.total_amount,
        c.phone as customer_phone,
        c.email as customer_email,
        r.name as rider_name,
        r.phone as rider_phone,
        r.vehicle_number
    FROM delivery_orders do
    LEFT JOIN sales s ON do.sale_id = s.id
    LEFT JOIN customers c ON do.customer_id = c.id
    LEFT JOIN delivery_riders r ON do.rider_id = r.id
    ORDER BY do.created_at DESC
";

$delivery_orders = $conn->query($query);
?>

<body>
<div class="main-wrapper">
    <div class="page-wrapper">
        <div class="content">
            <div class="page-header">
                <div class="page-title">
                    <h4>Delivery Orders</h4>
                    <h6>Manage and track delivery orders</h6>
                </div>
                <div class="page-btn">
                    <a href="rider_list.php" class="btn btn-secondary">
                        <i class="fa fa-users me-2"></i>Manage Riders
                    </a>
                </div>
            </div>

            <?php if (isset($success_message)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($success_message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($error_message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped datatable">
                            <thead>
                                <tr>
                                    <th>Order #</th>
                                    <th>Customer</th>
                                    <th>Contact</th>
                                    <th>Rider</th>
                                    <th>Address</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Delivery Time</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($order = $delivery_orders->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($order['invoice_number']) ?></strong>
                                        </td>
                                        <td>
                                            <div>
                                                <strong><?= htmlspecialchars($order['customer_name']) ?></strong>
                                                <?php if ($order['customer_email']): ?>
                                                    <br><small class="text-muted"><?= htmlspecialchars($order['customer_email']) ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ($order['customer_phone']): ?>
                                                <a href="tel:<?= htmlspecialchars($order['customer_phone']) ?>" class="text-primary">
                                                    <?= htmlspecialchars($order['customer_phone']) ?>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div>
                                                <strong><?= htmlspecialchars($order['rider_name']) ?></strong>
                                                <?php if ($order['vehicle_number']): ?>
                                                    <br><small class="text-muted"><?= htmlspecialchars($order['vehicle_number']) ?></small>
                                                <?php endif; ?>
                                                <?php if ($order['rider_phone']): ?>
                                                    <br><a href="tel:<?= htmlspecialchars($order['rider_phone']) ?>" class="text-primary">
                                                        <?= htmlspecialchars($order['rider_phone']) ?>
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="text-wrap" style="max-width: 200px;">
                                                <?= nl2br(htmlspecialchars($order['delivery_address'])) ?>
                                            </div>
                                        </td>
                                        <td>
                                            <strong>Rs <?= number_format($order['total_amount'], 2) ?></strong>
                                        </td>
                                        <td>
                                            <?php
                                            $status_colors = [
                                                'pending' => 'warning',
                                                'out_for_delivery' => 'info',
                                                'delivered' => 'success',
                                                'cancelled' => 'danger'
                                            ];
                                            $status_labels = [
                                                'pending' => 'Pending',
                                                'out_for_delivery' => 'Out for Delivery',
                                                'delivered' => 'Delivered',
                                                'cancelled' => 'Cancelled'
                                            ];
                                            $color = $status_colors[$order['delivery_status']] ?? 'secondary';
                                            $label = $status_labels[$order['delivery_status']] ?? ucfirst($order['delivery_status']);
                                            ?>
                                            <span class="badge bg-<?= $color ?>"><?= $label ?></span>
                                        </td>
                                        <td>
                                            <?php if ($order['delivery_time']): ?>
                                                <?= date('M d, Y H:i', strtotime($order['delivery_time'])) ?>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?= date('M d, Y H:i', strtotime($order['created_at'])) ?>
                                        </td>
                                        <td>
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                    Actions
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#updateStatusModal" 
                                                           data-order-id="<?= $order['id'] ?>" 
                                                           data-current-status="<?= $order['delivery_status'] ?>"
                                                           data-customer-name="<?= htmlspecialchars($order['customer_name']) ?>">
                                                            <i class="fa fa-edit me-2"></i>Update Status
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="print_receipt.php?sale_id=<?= $order['sale_id'] ?>" target="_blank">
                                                            <i class="fa fa-print me-2"></i>Print Receipt
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="viewOrderDetails(<?= $order['id'] ?>)">
                                                            <i class="fa fa-eye me-2"></i>View Details
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Update Status Modal -->
<div class="modal fade" id="updateStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Delivery Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="order_id" id="statusOrderId">
                    
                    <div class="mb-3">
                        <label class="form-label">Customer</label>
                        <input type="text" class="form-control" id="statusCustomerName" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Current Status</label>
                        <input type="text" class="form-control" id="currentStatus" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">New Status <span class="text-danger">*</span></label>
                        <select class="form-select" name="new_status" required>
                            <option value="pending">Pending</option>
                            <option value="out_for_delivery">Out for Delivery</option>
                            <option value="delivered">Delivered</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Status</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Order Details Modal -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Order Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="orderDetailsContent">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<script>
// Handle status update modal
document.addEventListener('DOMContentLoaded', function() {
    const updateStatusModal = document.getElementById('updateStatusModal');
    if (updateStatusModal) {
        updateStatusModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const orderId = button.getAttribute('data-order-id');
            const currentStatus = button.getAttribute('data-current-status');
            const customerName = button.getAttribute('data-customer-name');
            
            document.getElementById('statusOrderId').value = orderId;
            document.getElementById('statusCustomerName').value = customerName;
            document.getElementById('currentStatus').value = currentStatus;
            
            // Set the new status dropdown to current status
            const statusSelect = document.querySelector('select[name="new_status"]');
            statusSelect.value = currentStatus;
        });
    }
});

// View order details
function viewOrderDetails(orderId) {
    // This would typically fetch order details via AJAX
    // For now, we'll show a simple message
    const modal = new bootstrap.Modal(document.getElementById('orderDetailsModal'));
    document.getElementById('orderDetailsContent').innerHTML = `
        <div class="text-center p-4">
            <p>Order details for delivery order #${orderId}</p>
            <p class="text-muted">This feature can be expanded to show detailed order information.</p>
        </div>
    `;
    modal.show();
}
</script>

</body>
</html> 