<?php
include "include/db.php"; // Include database connection
include "include/header.php";

// Initialize variables
$errors = [];
$success = '';
$per_page = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $per_page;

// Handle Filter Parameters
$filters = [
    'order_number' => trim($_GET['order_number'] ?? ''),
    'customer_name' => trim($_GET['customer_name'] ?? ''),
    'product_name' => trim($_GET['product_name'] ?? ''),
    'date_start' => trim($_GET['date_start'] ?? ''),
    'date_end' => trim($_GET['date_end'] ?? '')
];

// Build Query with Filters
$query = "SELECT SQL_CALC_FOUND_ROWS po.id, po.order_number, po.customer_name, po.customer_phone, po.product_id, po.quantity, po.price, po.total, 
                 p.name AS product_name, p.image AS product_image
          FROM product_orders po
          LEFT JOIN products p ON po.product_id = p.id
          WHERE 1=1";
$params = [];
$types = '';

if ($filters['order_number']) {
    $query .= " AND po.order_number LIKE ?";
    $params[] = '%' . $filters['order_number'] . '%';
    $types .= 's';
}
if ($filters['customer_name']) {
    $query .= " AND po.customer_name LIKE ?";
    $params[] = '%' . $filters['customer_name'] . '%';
    $types .= 's';
}
if ($filters['product_name']) {
    $query .= " AND p.name LIKE ?";
    $params[] = '%' . $filters['product_name'] . '%';
    $types .= 's';
}
if ($filters['date_start']) {
    $query .= " AND po.created_at >= ?";
    $params[] = $filters['date_start'] . ' 00:00:00';
    $types .= 's';
}
if ($filters['date_end']) {
    $query .= " AND po.created_at <= ?";
    $params[] = $filters['date_end'] . ' 23:59:59';
    $types .= 's';
}

$query .= " ORDER BY po.id DESC LIMIT ?, ?";
$params[] = $offset;
$params[] = $per_page;
$types .= 'ii';

// Execute Query
$stmt = $conn->prepare($query);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$orders = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get Total Rows for Pagination
$total_result = $conn->query("SELECT FOUND_ROWS() AS total");
$total_rows = $total_result->fetch_assoc()['total'];
$total_pages = ceil($total_rows / $per_page);

// Handle Order Deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_order'])) {
    $order_id = trim($_POST['order_id'] ?? '');
    if (empty($order_id) || !is_numeric($order_id)) {
        $errors[] = "Invalid order ID.";
    } else {
        // Check if order exists
        $stmt = $conn->prepare("SELECT id FROM product_orders WHERE id = ?");
        $stmt->bind_param("i", $order_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $errors[] = "Order not found.";
        } else {
            // Delete order
            $stmt = $conn->prepare("DELETE FROM product_orders WHERE id = ?");
            $stmt->bind_param("i", $order_id);
            if ($stmt->execute()) {
                $success = "Order deleted successfully!";
            } else {
                $errors[] = "Failed to delete order: " . $conn->error;
            }
        }
        $stmt->close();
    }
}
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        /* Tailwind CSS CDN */
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');

        /* Custom styles for enhanced design */
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .filter-section, .table-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .filter-section:hover, .table-section:hover { transform: translateY(-5px); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        input, select { transition: all 0.2s ease; }
        input:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; font-size: 1.25rem; font-weight: bold; }
        table { width: 100%; border-collapse: separate; border-spacing: 0; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #E5E7EB; }
        th { background: #1F2937; color: white; position: sticky; top: 0; z-index: 10; }
        tr:nth-child(even) { background: #F9FAFB; }
        tr:hover { background: #E5E7EB; }
        .pagination { display: flex; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
        .pagination a, .pagination span { padding: 0.5rem 1rem; border: 1px solid #D1D5DB; border-radius: 0.375rem; text-decoration: none; color: #1F2937; }
        .pagination a:hover { background: #F59E0B; color: white; }
        .pagination .active { background: #1F2937; color: white; }
        .pagination .disabled { color: #9CA3AF; pointer-events: none; }
        .customer-phone { font-family: 'Courier New', Courier, monospace; }
        .product-image { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; border: 1px solid #E5E7EB; }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
            table { font-size: 0.875rem; }
            .filter-section { flex-direction: column; }
            .table-section { overflow-x: auto; }
            .product-image { width: 40px; height: 40px; }
        }
        @media (min-width: 769px) {
            .content { margin-left: 250px; }
        }
    </style>

    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search orders..." class="w-full p-2 border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-yellow-500">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Notifications"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Messages"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full">
                <span class="text-white">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Toggle Menu"></i>
        </div>
    </nav>

    <!-- Filter Section -->
    <div class="filter-section bg-white p-6 rounded-lg shadow-md w-full my-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Filter Orders</h2>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label for="order_number" class="block text-sm font-medium text-gray-700">Order Number</label>
                <input type="text" id="order_number" name="order_number" value="<?php echo htmlspecialchars($filters['order_number']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div>
                <label for="customer_name" class="block text-sm font-medium text-gray-700">Customer Name</label>
                <input type="text" id="customer_name" name="customer_name" value="<?php echo htmlspecialchars($filters['customer_name']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div>
                <label for="product_name" class="block text-sm font-medium text-gray-700">Product Name</label>
                <input type="text" id="product_name" name="product_name" value="<?php echo htmlspecialchars($filters['product_name']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div>
                <label for="date_start" class="block text-sm font-medium text-gray-700">Date Start</label>
                <input type="date" id="date_start" name="date_start" value="<?php echo htmlspecialchars($filters['date_start']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div>
                <label for="date_end" class="block text-sm font-medium text-gray-700">Date End</label>
                <input type="date" id="date_end" name="date_end" value="<?php echo htmlspecialchars($filters['date_end']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div class="md:col-span-3 flex gap-4">
                <button type="submit" class="bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Apply Filters</button>
                <a href="product_order.php" class="bg-gray-500 text-white p-2 rounded-md hover:bg-gray-600 transition-colors">Clear Filters</a>
            </div>
        </form>
    </div>

    <!-- Orders Table -->
    <div class="table-section bg-white p-6 rounded-lg shadow-md w-full my-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">All Orders</h2>
        
        <!-- Success/Error Messages -->
        <?php if ($success): ?>
            <p class="success text-center mb-4"><?php echo htmlspecialchars($success); ?></p>
        <?php endif; ?>
        <?php if (!empty($errors)): ?>
            <ul class="error mb-4">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <!-- Orders Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Order Number</th>
                        <th>Customer Name</th>
                        <th>Customer Phone</th>
                        <th>Product Image</th>
                        <th>Product</th>
                        <th>Quantity</th>
                        <th>Price</th>
                        <th>Total</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)): ?>
                        <tr>
                            <td colspan="9" class="text-center py-4">No orders found.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($order['id']); ?></td>
                                <td><?php echo htmlspecialchars($order['order_number']); ?></td>
                                <td><?php echo htmlspecialchars($order['customer_name'] ?? 'N/A'); ?></td>
                                <td class="customer-phone"><?php echo htmlspecialchars($order['customer_phone'] ?? 'N/A'); ?></td>
                                <td>
                                    <?php if ($order['product_image'] && file_exists($order['product_image'])): ?>
                                        <img src="<?php echo htmlspecialchars($order['product_image']); ?>" alt="<?php echo htmlspecialchars($order['product_name'] ?? 'Product'); ?>" class="product-image" loading="lazy">
                                    <?php else: ?>
                                        <img src="https://via.placeholder.com/50" alt="No Image" class="product-image" loading="lazy">
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($order['product_name'] ?? $order['product_id']); ?></td>
                                <td><?php echo htmlspecialchars($order['quantity']); ?></td>
                                <td>$<?php echo number_format($order['price'], 2); ?></td>
                                <td>$<?php echo number_format($order['total'], 2); ?></td>
                                <td class="flex gap-2">
                                    <a href="edit_order.php?id=<?php echo htmlspecialchars($order['id']); ?>" class="bg-blue-900 text-white px-3 py-1 rounded-md hover:bg-blue-800 transition-colors">Edit</a>
                                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete this order?');">
                                        <input type="hidden" name="order_id" value="<?php echo htmlspecialchars($order['id']); ?>">
                                        <input type="hidden" name="delete_order" value="1">
                                        <button type="submit" class="bg-red-600 text-white px-3 py-1 rounded-md hover:bg-red-700 transition-colors">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php
                $query_params = $_GET;
                unset($query_params['page']);
                $query_string = http_build_query($query_params);
                $base_url = 'product_order.php' . ($query_string ? '?' . $query_string . '&' : '?');

                if ($page > 1) {
                    echo '<a href="' . $base_url . 'page=' . ($page - 1) . '">Previous</a>';
                } else {
                    echo '<span class="disabled">Previous</span>';
                }

                for ($i = 1; $i <= $total_pages; $i++) {
                    echo '<a href="' . $base_url . 'page=' . $i . '" class="' . ($i === $page ? 'active' : '') . '">' . $i . '</a>';
                }

                if ($page < $total_pages) {
                    echo '<a href="' . $base_url . 'page=' . ($page + 1) . '">Next</a>';
                } else {
                    echo '<span class="disabled">Next</span>';
                }
                ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php
include "include/footer.php";
$conn->close(); // Close database connection
?>