<?php
// admin/orders.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Get filter
$status_filter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT o.*, u.name as user_name 
        FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id";
$params = [];
$where = [];

if ($status_filter) {
    $where[] = "o.order_status = ?";
    $params[] = $status_filter;
}

if ($search) {
    $where[] = "(o.invoice_no LIKE ? OR o.name LIKE ? OR o.phone LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($where)) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY o.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();

// Get order counts
$stmt = $pdo->query("SELECT COUNT(*) as total FROM orders");
$total_orders = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM orders WHERE order_status = 'pending'");
$pending_orders = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM orders WHERE order_status = 'delivered'");
$delivered_orders = $stmt->fetch()['total'];

// Check which orders already have shipments
$shipment_exists = [];
if (!empty($orders)) {
    $order_ids = array_column($orders, 'id');
    $placeholders = implode(',', array_fill(0, count($order_ids), '?'));
    $stmt = $pdo->prepare("SELECT order_id FROM shipments WHERE order_id IN ($placeholders)");
    $stmt->execute($order_ids);
    $shipment_exists = $stmt->fetchAll(PDO::FETCH_COLUMN);
}

include 'header.php';
?>

<style>
.order-status {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.order-status.pending { background: #fcd34d; color: #92400e; }
.order-status.processing { background: #93c5fd; color: #1e40af; }
.order-status.shipped { background: #86efac; color: #166534; }
.order-status.delivered { background: #22c55e; color: #fff; }
.order-status.cancelled { background: #fca5a5; color: #991b1b; }

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.btn-sm {
    padding: 4px 8px;
    font-size: 12px;
}

.btn-shipment {
    background: #8b5cf6;
    color: #fff;
    border: none;
    transition: all 0.3s ease;
}

.btn-shipment:hover {
    background: #7c3aed;
    color: #fff;
}

.btn-shipment.has-shipment {
    background: #22c55e;
}

.btn-shipment.has-shipment:hover {
    background: #16a34a;
}
</style>

<div class="admin-card">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
        <h5 class="card-title">Orders (<?php echo $total_orders; ?>)</h5>
        
        <div class="d-flex gap-2 flex-wrap">
            <a href="orders.php" class="btn btn-sm btn-outline-secondary <?php echo !$status_filter ? 'active' : ''; ?>">
                All (<?php echo $total_orders; ?>)
            </a>
            <a href="orders.php?status=pending" class="btn btn-sm btn-outline-warning <?php echo $status_filter == 'pending' ? 'active' : ''; ?>">
                Pending (<?php echo $pending_orders; ?>)
            </a>
            <a href="orders.php?status=processing" class="btn btn-sm btn-outline-info">Processing</a>
            <a href="orders.php?status=shipped" class="btn btn-sm btn-outline-primary">Shipped</a>
            <a href="orders.php?status=delivered" class="btn btn-sm btn-outline-success <?php echo $status_filter == 'delivered' ? 'active' : ''; ?>">
                Delivered (<?php echo $delivered_orders; ?>)
            </a>
            <a href="orders.php?status=cancelled" class="btn btn-sm btn-outline-danger">Cancelled</a>
        </div>
    </div>
    
    <!-- Search -->
    <div class="mt-3 mb-3">
        <form method="GET" class="d-flex gap-2">
            <?php if ($status_filter): ?>
            <input type="hidden" name="status" value="<?php echo $status_filter; ?>">
            <?php endif; ?>
            <input type="text" name="search" class="form-control" style="max-width:300px;" placeholder="Search by invoice, name, phone..." value="<?php echo $search; ?>">
            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-search"></i></button>
            <?php if ($search): ?>
            <a href="orders.php<?php echo $status_filter ? '?status=' . $status_filter : ''; ?>" class="btn btn-secondary">Clear</a>
            <?php endif; ?>
        </form>
    </div>
    
    <div class="table-responsive">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Invoice</th>
                    <th>Customer</th>
                    <th>Phone</th>
                    <th>Total</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                <tr><td colspan="7" class="text-center">No orders found</td></tr>
                <?php else: ?>
                <?php foreach ($orders as $order): 
                    $has_shipment = in_array($order['id'], $shipment_exists);
                ?>
                <tr>
                    <td><strong><?php echo $order['invoice_no']; ?></strong></td>
                    <td><?php echo $order['name']; ?></td>
                    <td><?php echo $order['phone']; ?></td>
                    <td><?php echo number_format($order['total']); ?> TK</td>
                    <td>
                        <span class="order-status <?php echo $order['order_status']; ?>">
                            <?php echo ucfirst($order['order_status']); ?>
                        </span>
                    </td>
                    <td><?php echo date('d M Y', strtotime($order['created_at'])); ?></td>
                    <td>
                        <div class="action-btns">
                            <!-- View Order -->
                            <a href="order-details.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-primary" title="View Order">
                                <i class="fa-solid fa-eye"></i>
                            </a>
                            
                            <!-- Shipment Button -->
                            <?php if ($has_shipment): ?>
                                <a href="shipments.php" class="btn btn-sm btn-shipment has-shipment" title="View Shipment">
                                    <i class="fa-solid fa-truck"></i>
                                </a>
                            <?php else: ?>
                                <a href="add-shipment.php?order_id=<?php echo $order['id']; ?>" class="btn btn-sm btn-shipment" title="Create Shipment">
                                    <i class="fa-solid fa-truck"></i>
                                </a>
                            <?php endif; ?>
                            
                            <!-- Delivery Report Button (if delivered) -->
                            <?php if ($order['order_status'] == 'delivered'): ?>
                            <a href="add-delivery-report.php?order_id=<?php echo $order['id']; ?>" class="btn btn-sm btn-success" title="Add Delivery Report">
                                <i class="fa-solid fa-bicycle"></i>
                            </a>
                            <?php endif; ?>
                            
                            <!-- Update Status -->
                            <button onclick="updateStatus(<?php echo $order['id']; ?>, 'processing')" class="btn btn-sm btn-info" title="Processing">
                                <i class="fa-solid fa-play"></i>
                            </button>
                            <button onclick="updateStatus(<?php echo $order['id']; ?>, 'delivered')" class="btn btn-sm btn-success" title="Delivered">
                                <i class="fa-solid fa-check"></i>
                            </button>
                            <button onclick="updateStatus(<?php echo $order['id']; ?>, 'cancelled')" class="btn btn-sm btn-danger" title="Cancel">
                                <i class="fa-solid fa-times"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Status Update Modal -->
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Order Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="update-order-status.php">
                <input type="hidden" name="order_id" id="status_order_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="pending">Pending</option>
                            <option value="processing">Processing</option>
                            <option value="shipped">Shipped</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</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function updateStatus(orderId, status) {
    if (!confirm('Change order status to ' + status.toUpperCase() + '?')) return;
    
    $.ajax({
        url: 'update-order-status.php',
        type: 'POST',
        data: {
            order_id: orderId,
            status: status
        },
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                showToast('Order status updated successfully!', 'success');
                setTimeout(function() {
                    location.reload();
                }, 1000);
            } else {
                showToast(res.message || 'Failed to update status', 'error');
            }
        },
        error: function() {
            showToast('Something went wrong', 'error');
        }
    });
}

function showToast(message, type) {
    var colors = {
        success: '#22c55e',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };
    
    var toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        background: ${colors[type] || colors.info};
        color: #fff;
        border-radius: 8px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
        max-width: 400px;
        font-size: 14px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}
</script>

<?php include 'footer.php'; ?>