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

// Initialize variables
$errors = [];
$success = '';
$order = null;
$payment_summary = ['paid' => 0, 'pending' => 0, 'failed' => 0];
$product_purchase_data = ['total_quantity' => 0];
$customer_purchase_data = ['total_orders' => 0, 'total_spent' => 0];

// Fetch order data
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $errors[] = "Invalid order ID.";
} else {
    $stmt = $conn->prepare("SELECT id, order_number, customer_id, product_id, quantity, price, discount, total, payment_method, payment_status, order_status, shipping_address FROM product_orders WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        $errors[] = "Order not found.";
    } else {
        $order = $result->fetch_assoc();
    }
    $stmt->close();
}

// Fetch customers and products for dropdowns
$customers = $conn->query("SELECT id, name FROM users ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$products = $conn->query("SELECT id, name FROM products ORDER BY name")->fetch_all(MYSQLI_ASSOC);

// Fetch payment summary
$stmt = $conn->query("SELECT payment_status, SUM(total) AS total_amount FROM product_orders GROUP BY payment_status");
while ($row = $stmt->fetch_assoc()) {
    if ($row['payment_status'] === 'paid') $payment_summary['paid'] = $row['total_amount'];
    if ($row['payment_status'] === 'pending') $payment_summary['pending'] = $row['total_amount'];
    if ($row['payment_status'] === 'failed') $payment_summary['failed'] = $row['total_amount'];
}

// Fetch product purchase data (if order exists)
if ($order) {
    $stmt = $conn->prepare("SELECT SUM(quantity) AS total_quantity FROM product_orders WHERE product_id = ?");
    $stmt->bind_param("i", $order['product_id']);
    $stmt->execute();
    $product_purchase_data['total_quantity'] = $stmt->get_result()->fetch_assoc()['total_quantity'] ?: 0;
    $stmt->close();

    // Fetch customer purchase data
    $stmt = $conn->prepare("SELECT COUNT(*) AS total_orders, SUM(total) AS total_spent FROM product_orders WHERE customer_id = ?");
    $stmt->bind_param("i", $order['customer_id']);
    $stmt->execute();
    $customer_purchase_data = $stmt->get_result()->fetch_assoc();
    $customer_purchase_data['total_spent'] = $customer_purchase_data['total_spent'] ?: 0;
    $stmt->close();
}

// Handle Order Update Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $order) {
    $order_number = trim($_POST['order_number'] ?? '');
    $customer_id = trim($_POST['customer_id'] ?? '');
    $product_id = trim($_POST['product_id'] ?? '');
    $quantity = trim($_POST['quantity'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $discount = trim($_POST['discount'] ?? '');
    $total = trim($_POST['total'] ?? '');
    $payment_method = trim($_POST['payment_method'] ?? '');
    $payment_status = trim($_POST['payment_status'] ?? '');
    $order_status = trim($_POST['order_status'] ?? '');
    $shipping_address = trim($_POST['shipping_address'] ?? '');

    // Validation
    if (empty($order_number)) $errors[] = "Order Number is required.";
    if (empty($customer_id) || !is_numeric($customer_id)) $errors[] = "Customer ID is required.";
    if (empty($product_id) || !is_numeric($product_id)) $errors[] = "Product ID is required.";
    if (empty($quantity) || !is_numeric($quantity) || $quantity < 1) $errors[] = "Quantity must be a positive number.";
    if (empty($price) || !is_numeric($price) || $price < 0) $errors[] = "Price must be a non-negative number.";
    if ($discount === '' || !is_numeric($discount) || $discount < 0 || $discount > 100) $errors[] = "Discount must be between 0 and 100.";
    if (empty($payment_method)) $errors[] = "Payment Method is required.";
    if (empty($payment_status)) $errors[] = "Payment Status is required.";
    if (empty($order_status)) $errors[] = "Order Status is required.";
    if (empty($shipping_address)) $errors[] = "Shipping Address is required.";

    // Verify customer and product exist
    $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->bind_param("i", $customer_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows === 0) $errors[] = "Invalid Customer ID.";
    $stmt->close();

    $stmt = $conn->prepare("SELECT id FROM products WHERE id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows === 0) $errors[] = "Invalid Product ID.";
    $stmt->close();

    // If no errors, update the order
    if (empty($errors)) {
        $stmt = $conn->prepare("UPDATE product_orders SET order_number = ?, customer_id = ?, product_id = ?, quantity = ?, price = ?, discount = ?, total = ?, payment_method = ?, payment_status = ?, order_status = ?, shipping_address = ? WHERE id = ?");
        $stmt->bind_param("siiiddsssssi", $order_number, $customer_id, $product_id, $quantity, $price, $discount, $total, $payment_method, $payment_status, $order_status, $shipping_address, $order['id']);
        if ($stmt->execute()) {
            $success = "Order updated successfully!";
            // Refresh order data
            $stmt = $conn->prepare("SELECT id, order_number, customer_id, product_id, quantity, price, discount, total, payment_method, payment_status, order_status, shipping_address FROM product_orders WHERE id = ?");
            $stmt->bind_param("i", $order['id']);
            $stmt->execute();
            $order = $stmt->get_result()->fetch_assoc();
            // Refresh purchase data
            $stmt = $conn->prepare("SELECT SUM(quantity) AS total_quantity FROM product_orders WHERE product_id = ?");
            $stmt->bind_param("i", $order['product_id']);
            $stmt->execute();
            $product_purchase_data['total_quantity'] = $stmt->get_result()->fetch_assoc()['total_quantity'] ?: 0;
            $stmt->close();
            $stmt = $conn->prepare("SELECT COUNT(*) AS total_orders, SUM(total) AS total_spent FROM product_orders WHERE customer_id = ?");
            $stmt->bind_param("i", $order['customer_id']);
            $stmt->execute();
            $customer_purchase_data = $stmt->get_result()->fetch_assoc();
            $customer_purchase_data['total_spent'] = $customer_purchase_data['total_spent'] ?: 0;
            $_POST = []; // Reset form fields
        } else {
            $errors[] = "Failed to update order: " . $conn->error;
        }
        $stmt->close();
    }
}
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        /* Tailwind CSS CDN (embedded for top-class design) */
        @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; }
        .form-section, .sidebar-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .form-section:hover, .sidebar-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, textarea, select { transition: all 0.2s ease; }
        input:focus, textarea:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; font-size: 1.25rem; font-weight: bold; }
        .sidebar-section { background: #F9FAFB; border-left: 4px solid #F59E0B; }
        .sidebar-section h3 { color: #1F2937; }
        .sidebar-section p { color: #4B5563; }
        .status-paid { color: #10B981; }
        .status-pending { color: #F59E0B; }
        .status-failed { color: #DC2626; }
        @media (max-width: 1024px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
            .sidebar-section { margin-top: 1rem; }
        }
        @media (min-width: 1025px) {
            .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>

    <!-- Main Content with Sidebar -->
    <div class="flex flex-col lg:flex-row gap-6 my-6 mx-auto max-w-7xl">
        <!-- Edit Order Form -->
        <div class="form-section bg-white p-6 rounded-lg shadow-md w-full lg:w-2/3">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Edit Order</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; ?>

            <?php if ($order): ?>
                <!-- Order Form -->
                <form method="POST" class="space-y-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 isset($_POST['order_number']) ? htmlspecialchars($_POST['order_number']) : htmlspecialchars($order['order_number']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                    </div>
                    <div>
                        <label for="customer_id" class="block text-sm font-medium text-gray-700">Customer</label>
                        <select id="customer_id" name="customer_id" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                            <option value="">Select customer</option>
                            <?php foreach ($customers as $customer): ?>
                                <option value="<?php echo htmlspecialchars($customer['id']); ?>" <?php echo (isset($_POST['customer_id']) && $_POST['customer_id'] == $customer['id']) || (!isset($_POST['customer_id']) && $order['customer_id'] == $customer['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($customer['name'] . ' (ID: ' . $customer['id'] . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="product_id" class="block text-sm font-medium text-gray-700">Product</label>
                        <select id="product_id" name="product_id" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                            <option value="">Select product</option>
                            <?php foreach ($products as $product): ?>
                                <option value="<?php echo htmlspecialchars($product['id']); ?>" <?php echo (isset($_POST['product_id']) && $_POST['product_id'] == $product['id']) || (!isset($_POST['product_id']) && $order['product_id'] == $product['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($product['name'] . ' (ID: ' . $product['id'] . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="quantity" class="block text-sm font-medium text-gray-700">Quantity</label>
                        <input type="number" id="quantity" name="quantity" value="<?php echo isset($_POST['quantity']) ? htmlspecialchars($_POST['quantity']) : htmlspecialchars($order['quantity']); ?>" min="1" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                    </div>
                    <div>
                        <label for="price" class="block text-sm font-medium text-gray-700">Price</label>
                        <input type="number" id="price" name="price" step="0.01" value="<?php echo isset($_POST['price']) ? htmlspecialchars($_POST['price']) : htmlspecialchars($order['price']); ?>" min="0" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                    </div>
                    <div>
                        <label for="discount" class="block text-sm font-medium text-gray-700">Discount (%)</label>
                        <input type="number" id="discount" name="discount" step="0.01" value="<?php echo isset($_POST['discount']) ? htmlspecialchars($_POST['discount']) : htmlspecialchars($order['discount']); ?>" min="0" max="100" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                    </div>
                    <div>
                        <label for="total" class="block text-sm font-medium text-gray-700">Total</label>
                        <input type="number" id="total" name="total" step="0.01" value="<?php echo isset($_POST['total']) ? htmlspecialchars($_POST['total']) : htmlspecialchars($order['total']); ?>" class="w-full p-2 border border-gray-300 rounded-md bg-gray-100 cursor-not-allowed" readonly>
                    </div>
                    <div>
                        <label for="payment_method" class="block text-sm font-medium text-gray-700">Payment Method</label>
                        <select id="payment_method" name="payment_method" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                            <option value="">Select payment method</option>
                            <option value="bKash" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] == 'bKash') || (!isset($_POST['payment_method']) && $order['payment_method'] == 'bKash') ? 'selected' : ''; ?>>bKash</option>
                            <option value="Nagad" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] == 'Nagad') || (!isset($_POST['payment_method']) && $order['payment_method'] == 'Nagad') ? 'selected' : ''; ?>>Nagad</option>
                            <option value="Card" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] == 'Card') || (!isset($_POST['payment_method']) && $order['payment_method'] == 'Card') ? 'selected' : ''; ?>>Card</option>
                            <option value="COD" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] == 'COD') || (!isset($_POST['payment_method']) && $order['payment_method'] == 'COD') ? 'selected' : ''; ?>>Cash on Delivery</option>
                        </select>
                    </div>
                    <div>
                        <label for="payment_status" class="block text-sm font-medium text-gray-700">Payment Status</label>
                        <select id="payment_status" name="payment_status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                            <option value="">Select payment status</option>
                            <option value="paid" <?php echo (isset($_POST['payment_status']) && $_POST['payment_status'] == 'paid') || (!isset($_POST['payment_status']) && $order['payment_status'] == 'paid') ? 'selected' : ''; ?>>Paid</option>
                            <option value="pending" <?php echo (isset($_POST['payment_status']) && $_POST['payment_status'] == 'pending') || (!isset($_POST['payment_status']) && $order['payment_status'] == 'pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="failed" <?php echo (isset($_POST['payment_status']) && $_POST['payment_status'] == 'failed') || (!isset($_POST['payment_status']) && $order['payment_status'] == 'failed') ? 'selected' : ''; ?>>Failed</option>
                        </select>
                    </div>
                    <div>
                        <label for="order_status" class="block text-sm font-medium text-gray-700">Order Status</label>
                        <select id="order_status" name="order_status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                            <option value="">Select order status</option>
                            <option value="pending" <?php echo (isset($_POST['order_status']) && $_POST['order_status'] == 'pending') || (!isset($_POST['order_status']) && $order['order_status'] == 'pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?php echo (isset($_POST['order_status']) && $_POST['order_status'] == 'processing') || (!isset($_POST['order_status']) && $order['order_status'] == 'processing') ? 'selected' : ''; ?>>Processing</option>
                            <option value="delivered" <?php echo (isset($_POST['order_status']) && $_POST['order_status'] == 'delivered') || (!isset($_POST['order_status']) && $order['order_status'] == 'delivered') ? 'selected' : ''; ?>>Delivered</option>
                            <option value="cancelled" <?php echo (isset($_POST['order_status']) && $_POST['order_status'] == 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <div>
                        <label for="shipping_address" class="block text-sm font-medium text-gray-700">Shipping Address</label>
                        <textarea id="shipping_address" name="shipping_address" rows="4" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required><?php echo isset($_POST['shipping_address']) ? htmlspecialchars($_POST['shipping_address']) : htmlspecialchars($order['shipping_address']); ?></textarea>
                    </div>
                    <div class="flex gap-4">
                        <button type="submit" class="flex-1 bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Update Order</button>
                        <a href="product_order.php" class="flex-1 bg-gray-500 text-white p-2 rounded-md hover:bg-gray-600 transition-colors text-center">Cancel</a>
                    </div>
                </form>

                <!-- JavaScript for Total Calculation -->
                <script>
                    function calculateTotal() {
                        const quantity = parseFloat(document.getElementById('quantity').value) || 0;
                        const price = parseFloat(document.getElementById('price').value) || 0;
                        const discount = parseFloat(document.getElementById('discount').value) || 0;
                        const total = quantity * price * (1 - discount / 100);
                        document.getElementById('total').value = total.toFixed(2);
                    }
                    document.getElementById('quantity').addEventListener('input', calculateTotal);
                    document.getElementById('price').addEventListener('input', calculateTotal);
                    document.getElementById('discount').addEventListener('input', calculateTotal);
                    calculateTotal(); // Initial calculation
                </script>
            <?php else: ?>
                <p class="text-center text-gray-700">No order found to edit.</p>
            <?php endif; ?>
        </div>

        <!-- Right Sidebar -->
        <?php if ($order): ?>
            <div class="sidebar-section bg-white p-6 rounded-lg shadow-md w-full lg:w-1/3">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Order Insights</h3>
                <div class="space-y-4">
                    <!-- Payment Summary -->
                    <div>
                        <h4 class="text-md font-medium text-gray-700">Payment Summary</h4>
                        <p class="status-paid">Total Paid: $<?php echo number_format($payment_summary['paid'], 2); ?></p>
                        <p class="status-pending">Total Pending: $<?php echo number_format($payment_summary['pending'], 2); ?></p>
                        <p class="status-failed">Total Failed: $<?php echo number_format($payment_summary['failed'], 2); ?></p>
                    </div>
                    <!-- Product Purchase Data -->
                    <div>
                        <h4 class="text-md font-medium text-gray-700">Product Purchase Data</h4>
                        <p>Total Quantity Ordered: <?php echo htmlspecialchars($product_purchase_data['total_quantity']); ?> units</p>
                    </div>
                    <!-- Customer Purchase Data -->
                    <div>
                        <h4 class="text-md font-medium text-gray-700">Customer Purchase Data</h4>
                        <p>Total Orders: <?php echo htmlspecialchars($customer_purchase_data['total_orders']); ?></p>
                        <p>Total Spent: $<?php echo number_format($customer_purchase_data['total_spent'], 2); ?></p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

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