<?php
// Helper function to get badge class based on status
function getStatusBadgeClass($status) {
    switch ($status) {
        case 'pending':
            return 'warning';
        case 'confirmed':
            return 'info';
        case 'processing':
            return 'primary';
        case 'shipped':
            return 'secondary';
        case 'delivered':
            return 'success';
        case 'completed':
            return 'success';
       case 'rated':
            return 'success';
        case 'cancelled':
            return 'danger';
        default:
            return 'secondary';
    }
}
?>

<!-- Begin Page Content -->
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="row column_title">
        <div class="col-md-12">
            <div class="page_title">
                <h2>Orders Management</h2>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filter Orders</h6>
        </div>
        <div class="card-body">
            <form method="GET" action="<?= base_url('dashboard/orders') ?>">
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="filter">Filter Type:</label>
                            <select class="form-control" name="filter" id="filter" onchange="toggleDateInputs()">
                                <option value="today" <?= ($filter_type == 'today') ? 'selected' : '' ?>>Today's Orders</option>
                                <option value="date_range" <?= ($filter_type == 'date_range') ? 'selected' : '' ?>>Date Range</option>
                                <option value="all" <?= ($filter_type == 'all') ? 'selected' : '' ?>>All Orders</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3" id="start_date_div" style="<?= ($filter_type == 'date_range') ? '' : 'display: none;' ?>">
                        <div class="form-group">
                            <label for="start_date">Start Date:</label>
                            <input type="date" class="form-control" name="start_date" id="start_date" 
                                   value="<?= isset($start_date) ? $start_date : '' ?>">
                        </div>
                    </div>
                    <div class="col-md-3" id="end_date_div" style="<?= ($filter_type == 'date_range') ? '' : 'display: none;' ?>">
                        <div class="form-group">
                            <label for="end_date">End Date:</label>
                            <input type="date" class="form-control" name="end_date" id="end_date" 
                                   value="<?= isset($end_date) ? $end_date : '' ?>">
                        </div>
                    </div>
                    <div class="col-md-3" id="status_div" style="<?= ($filter_type == 'date_range') ? '' : 'display: none;' ?>">
                        <div class="form-group">
                            <label for="status">Status:</label>
                            <select class="form-control" name="status" id="status">
                                <option value="">All Status</option>
                                <option value="pending" <?= (isset($status) && $status == 'pending') ? 'selected' : '' ?>>Pending</option>
                                <option value="confirmed" <?= (isset($status) && $status == 'confirmed') ? 'selected' : '' ?>>Confirmed</option>
                                <option value="processing" <?= (isset($status) && $status == 'processing') ? 'selected' : '' ?>>Processing</option>
                                <option value="shipped" <?= (isset($status) && $status == 'shipped') ? 'selected' : '' ?>>Shipped</option>
                                <option value="delivered" <?= (isset($status) && $status == 'delivered') ? 'selected' : '' ?>>Delivered</option>
                                <option value="cancelled" <?= (isset($status) && $status == 'cancelled') ? 'selected' : '' ?>>Cancelled</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <button type="submit" class="btn btn-primary">Apply Filter</button>
                        <a href="<?= base_url('dashboard/orders') ?>" class="btn btn-secondary">Reset</a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Today's Orders</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?= $today_count ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-day fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Orders</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?= $total_count ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-shopping-cart fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Filtered Results</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?= count($orders) ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-filter fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Current Filter</div>
                            <div class="text-sm mb-0 font-weight-bold text-gray-800"><?= $filter_label ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-search fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Orders Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><?= $filter_label ?></h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="ordersTable" width="100%" cellspacing="0">
                    <thead class="thead-dark">
                        <tr>
                            <th>Order ID</th>
                            <th>Customer</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Total Amount</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($orders)): ?>
                            <?php foreach ($orders as $order_id => $order): ?>
                                <tr>
                                    <td><?= $order_id ?></td>
                                    <td>
                                        <?php 

                                        $user=$this->common->readdatadocument('Users', $order['userId']);
                                        if (isset($order['userId'])) {
                                            echo $user['userName'];
                                        }  else {
                                            echo 'N/A';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php 
                                        if (isset($order['date'])) {
                                            echo date('M d, Y H:i', $order['date'] / 1000);
                                        } else {
                                            echo 'N/A';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?= getStatusBadgeClass($order['orderStatus'] ?? 'pending') ?>">
                                            <?= ucfirst($order['orderStatus'] ?? 'pending') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php 
                                        if (isset($order['price'])) {
                                            echo '$' . number_format($order['price'], 2);
                                        } else {
                                            echo 'N/A';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <a href="<?= base_url('dashboard/view_order/' . $order_id) ?>" class="btn btn-info btn-sm">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-warning btn-sm dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fas fa-edit"></i> Status
                                                </button>
                                                <div class="dropdown-menu">
                                                    <a class="dropdown-item" href="#" onclick="updateStatus('<?= $order_id ?>', 'pending')">Pending</a>
                                                    <a class="dropdown-item" href="#" onclick="updateStatus('<?= $order_id ?>', 'confirmed')">Confirmed</a>
                                                    <a class="dropdown-item" href="#" onclick="updateStatus('<?= $order_id ?>', 'processing')">Processing</a>
                                                    <a class="dropdown-item" href="#" onclick="updateStatus('<?= $order_id ?>', 'shipped')">Shipped</a>
                                                    <a class="dropdown-item" href="#" onclick="updateStatus('<?= $order_id ?>', 'delivered')">Delivered</a>
                                                    <a class="dropdown-item" href="#" onclick="updateStatus('<?= $order_id ?>', 'cancelled')">Cancelled</a>
                                                </div>
                                            </div>
                                            <a href="<?= base_url('dashboard/delete_order/' . $order_id) ?>" 
                                               class="btn btn-danger btn-sm" 
                                               onclick="return confirm('Are you sure you want to delete this order?')">
                                                <i class="fas fa-trash"></i> Delete
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center">No orders found</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>
<!-- /.container-fluid -->

<script>
function toggleDateInputs() {
    var filterType = document.getElementById('filter').value;
    var startDateDiv = document.getElementById('start_date_div');
    var endDateDiv = document.getElementById('end_date_div');
    var statusDiv = document.getElementById('status_div');
    
    if (filterType === 'date_range') {
        startDateDiv.style.display = 'block';
        endDateDiv.style.display = 'block';
        statusDiv.style.display = 'block';
    } else {
        startDateDiv.style.display = 'none';
        endDateDiv.style.display = 'none';
        statusDiv.style.display = 'none';
    }
}

function updateStatus(orderId, status) {
    if (confirm('Are you sure you want to update the order status to ' + status + '?')) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = '<?= base_url('dashboard/update_order_status') ?>';
        
        var orderIdInput = document.createElement('input');
        orderIdInput.type = 'hidden';
        orderIdInput.name = 'order_id';
        orderIdInput.value = orderId;
        
        var statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'status';
        statusInput.value = status;
        
        form.appendChild(orderIdInput);
        form.appendChild(statusInput);
        document.body.appendChild(form);
        form.submit();
    }
}

// Initialize DataTable
$(document).ready(function() {
    $('#ordersTable').DataTable({
        "pageLength": 25,
        "order": [[ 2, "desc" ]], // Sort by date descending
        "columnDefs": [
            { "orderable": false, "targets": 5 } // Disable sorting on Actions column
        ]
    });
});
</script>

