<?php
session_start();
include "../config/db.php";

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

// Update order status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $status = mysqli_real_escape_string($conn, $_POST['status'] ?? '');
    $order_id = mysqli_real_escape_string($conn, $_POST['order_id'] ?? '');
    
    if (empty($order_id)) {
        $success = "Error: Order ID is missing from the request.";
    } else {
        if (mysqli_query($conn, "UPDATE orders SET status='$status' WHERE id='$order_id'")) {
            // Add to order history if table exists
            $check_history_table = mysqli_query($conn, "SHOW TABLES LIKE 'order_history'");
            if(mysqli_num_rows($check_history_table) > 0) {
                $admin_user = $_SESSION['admin_user'] ?? 'admin';
                mysqli_query($conn, 
                    "INSERT INTO order_history (order_id, status, updated_by, notes) 
                     VALUES ('$order_id', '$status', '$admin_user', 'Status updated from purchase orders page')"
                );
            }
            $success = "Order #$order_id status forcefully updated to '$status' successfully!";
        } else {
            $success = "Failed to update order status: " . mysqli_error($conn);
        }
    }
}

// Filter orders
$where = "";
if (isset($_GET['status']) && $_GET['status'] != 'all') {
    $status_filter = mysqli_real_escape_string($conn, $_GET['status']);
    $where = "WHERE orders.status = '$status_filter'";
}

// Search orders
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = mysqli_real_escape_string($conn, $_GET['search']);
    $where = $where ? $where . " AND " : "WHERE ";
    $where .= "(orders.id LIKE '%$search%' OR users.name LIKE '%$search%' OR users.email LIKE '%$search%')";
}

$orders = mysqli_query($conn,
    "SELECT orders.*, users.name, users.email, users.phone
     FROM orders
     JOIN users ON orders.user_id = users.id
     " . ($where ? $where . " AND " : "WHERE ") . "orders.rental_days = 0
     ORDER BY orders.id DESC"
);

$total_orders = mysqli_num_rows($orders);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Purchase Orders - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .main-content {
            margin-left: 220px;
            padding: 30px;
            background: #f8f9fa;
            min-height: 100vh;
        }
        .orders-container {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        .filter-badge {
            display: inline-block;
            padding: 8px 15px;
            margin: 0 5px 10px 0;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
            text-decoration: none;
            color: #333;
        }
        .filter-badge.active {
            border-color: var(--primary-orange);
            background: rgba(255,107,53,0.1);
        }
        .order-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid;
            transition: all 0.3s;
        }
        .order-card:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .order-id {
            font-family: monospace;
            background: var(--dark-blue);
            color: white;
            padding: 3px 10px;
            border-radius: 5px;
            display: inline-block;
        }
        .status-badge {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .status-paid { background: #d4edda; color: #155724; }
        .status-shipped { background: #fff3cd; color: #856404; }
        .status-delivered { background: #cce5ff; color: #004080; }
        .status-cancelled { background: #f8d7da; color: #721c24; }
        .status-return-requested { background: #ffe5d0; color: #d35400; }
        .status-returned { background: #e2e3e5; color: #383d41; }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <?php include "includes/sidebar.php"; ?>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 style="color: var(--dark-blue);">
                <i class="fas fa-shopping-bag me-2"></i>Manage Purchase Orders
            </h2>
            <div>
                <span class="badge bg-success p-2">
                    <i class="fas fa-box me-1"></i> Total Purchase Orders: <?php echo $total_orders; ?>
                </span>
            </div>
        </div>

        <?php if(isset($success)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo $success; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filters and Search -->
        <div class="orders-container mb-4">
            <div class="row">
                <div class="col-md-8">
                    <h5>Filter by Status:</h5>
                    <div>
                        <a href="purchase_orders.php" class="filter-badge <?php echo !isset($_GET['status']) || $_GET['status'] == 'all' ? 'active' : ''; ?>">
                            <i class="fas fa-boxes me-1"></i>All
                        </a>
                        <a href="purchase_orders.php?status=Paid" class="filter-badge status-paid <?php echo (isset($_GET['status']) && $_GET['status'] == 'Paid') ? 'active' : ''; ?>">
                            <i class="fas fa-money-bill me-1"></i>Paid
                        </a>
                        <a href="purchase_orders.php?status=Shipped" class="filter-badge status-shipped <?php echo (isset($_GET['status']) && $_GET['status'] == 'Shipped') ? 'active' : ''; ?>">
                            <i class="fas fa-shipping-fast me-1"></i>Shipped
                        </a>
                        <a href="purchase_orders.php?status=Delivered" class="filter-badge status-delivered <?php echo (isset($_GET['status']) && $_GET['status'] == 'Delivered') ? 'active' : ''; ?>">
                            <i class="fas fa-check-circle me-1"></i>Delivered
                        </a>
                        <a href="purchase_orders.php?status=Cancelled" class="filter-badge status-cancelled <?php echo (isset($_GET['status']) && $_GET['status'] == 'Cancelled') ? 'active' : ''; ?>">
                            <i class="fas fa-times-circle me-1"></i>Cancelled
                        </a>
                        <a href="purchase_orders.php?status=Return Requested" class="filter-badge status-return-requested <?php echo (isset($_GET['status']) && $_GET['status'] == 'Return Requested') ? 'active' : ''; ?>">
                            <i class="fas fa-undo me-1"></i>Return Requested
                        </a>
                        <a href="purchase_orders.php?status=Returned" class="filter-badge status-returned <?php echo (isset($_GET['status']) && $_GET['status'] == 'Returned') ? 'active' : ''; ?>">
                            <i class="fas fa-box-open me-1"></i>Returned
                        </a>
                    </div>
                </div>
                <div class="col-md-4">
                    <form method="GET" class="d-flex">
                        <input type="text" 
                               name="search" 
                               class="form-control me-2" 
                               placeholder="Search orders..."
                               value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Orders List -->
        <div class="orders-container">
            <?php if(mysqli_num_rows($orders) > 0): ?>
                <?php while($order = mysqli_fetch_assoc($orders)): ?>
                <div class="order-card" style="border-left-color: 
                    <?php 
                    switch($order['status']) {
                        case 'Paid': echo '#28a745'; break;
                        case 'Shipped': echo '#ffc107'; break;
                        case 'Delivered': echo '#17a2b8'; break;
                        case 'Cancelled': echo '#dc3545'; break;
                        case 'Return Requested': echo '#fd7e14'; break;
                        case 'Returned': echo '#6c757d'; break;
                        default: echo '#6c757d';
                    }
                    ?>;">
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <span class="order-id">ORDER #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></span>
                                    <span class="status-badge ms-2 
                                        <?php 
                                        switch($order['status']) {
                                            case 'Paid': echo 'status-paid'; break;
                                            case 'Shipped': echo 'status-shipped'; break;
                                            case 'Delivered': echo 'status-delivered'; break;
                                            case 'Cancelled': echo 'status-cancelled'; break;
                                            case 'Return Requested': echo 'status-return-requested'; break;
                                            case 'Returned': echo 'status-returned'; break;
                                        }
                                        ?>">
                                        <?php echo $order['status'] ?? 'Pending'; ?>
                                    </span>
                                    <?php if(!empty($order['return_image'])): ?>
                                        <span class="badge bg-info ms-2" title="Damage photo attached">
                                            <i class="fas fa-camera me-1"></i>Photo
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <span class="text-muted">
                                    <?php 
                                    echo isset($order['created_at']) ? date('M d, Y h:i A', strtotime($order['created_at'])) : 
                                        (isset($order['order_date']) ? date('M d, Y h:i A', strtotime($order['order_date'])) : 'N/A');
                                    ?>
                                </span>
                            </div>
                            
                            <div class="mb-3">
                                <h5 class="mb-1">
                                    <i class="fas fa-user me-2"></i><?php echo htmlspecialchars($order['name']); ?>
                                </h5>
                                <div class="text-muted">
                                    <i class="fas fa-envelope me-1"></i><?php echo htmlspecialchars($order['email']); ?> |
                                    <i class="fas fa-phone me-1 ms-2"></i><?php echo htmlspecialchars($order['phone'] ?? 'N/A'); ?>
                                </div>
                            </div>
                            
                            <?php
                            $items = mysqli_query($conn,
                                "SELECT * FROM order_items WHERE order_id='".$order['id']."'"
                            );
                            ?>
                            
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Purchase Price</th>
                                            <th>Qty</th>
                                            <th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while($item = mysqli_fetch_assoc($items)): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                                            <td>₹<?php echo number_format($item['price'], 2); ?></td>
                                            <td><?php echo $item['quantity']; ?></td>
                                            <td>₹<?php echo number_format($item['price'] * $item['quantity'], 2); ?></td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-body">
                                    <h6 class="card-title">Purchase Summary</h6>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Subtotal:</span>
                                        <span>₹<?php echo number_format($order['total_price'], 2); ?></span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Shipping:</span>
                                        <span>₹0.00</span>
                                    </div>
                                    <hr>
                                    <div class="d-flex justify-content-between fw-bold">
                                        <span>Purchase Amount:</span>
                                        <span class="text-success">₹<?php echo number_format($order['total_price'], 2); ?></span>
                                    </div>
                                    
                                    <hr>
                                    
                                    <!-- Update Status Form -->
                                    <form method="POST" class="mt-3">
                                        <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                        <label class="form-label">Update Status:</label>
                                        <select name="status" class="form-select mb-2">
                                            <option value="Pending" <?php echo ($order['status'] ?? '') == 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                            <option value="Paid" <?php echo ($order['status'] ?? '') == 'Paid' ? 'selected' : ''; ?>>Paid</option>
                                            <option value="Shipped" <?php echo ($order['status'] ?? '') == 'Shipped' ? 'selected' : ''; ?>>Shipped</option>
                                            <option value="Delivered" <?php echo ($order['status'] ?? '') == 'Delivered' ? 'selected' : ''; ?>>Delivered</option>
                                            <option value="Cancelled" <?php echo ($order['status'] ?? '') == 'Cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                            <option value="Return Requested" <?php echo ($order['status'] ?? '') == 'Return Requested' ? 'selected' : ''; ?>>Return Requested</option>
                                            <option value="Returned" <?php echo ($order['status'] ?? '') == 'Returned' ? 'selected' : ''; ?>>Returned</option>
                                        </select>
                                        <button type="submit" name="update" class="btn btn-sm btn-primary w-100">
                                            <i class="fas fa-sync me-1"></i>Update Status
                                        </button>
                                    </form>
                                    
                                    <div class="mt-3">
                                        <a href="view-order.php?id=<?php echo $order['id']; ?>" 
                                           class="btn btn-sm btn-outline-primary w-100">
                                            <i class="fas fa-eye me-1"></i>View Details
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
                
            <?php else: ?>
                <div class="text-center py-5">
                    <i class="fas fa-shopping-bag fa-4x mb-3" style="color: #ddd;"></i>
                    <h4>No purchase orders found</h4>
                    <p class="text-muted">No orders match your search criteria</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
