<?php
include("../db/cn.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (!isset($_GET['order_id'])) {
    die("Order ID not provided.");
}

$orderId = $_GET['order_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $quantities = $_POST['quantities'];
    $prices = $_POST['prices'];
    $discounts = $_POST['discounts'];

    $grandTotal = 0;

    foreach ($quantities as $id => $qty) {
        $price = $prices[$id];
        $discountPercent = $discounts[$id];
        
        $gross = (float)$price * (int)$qty;
        $discountAmount = ($gross * (float)$discountPercent) / 100;
        $netAmount = $gross - $discountAmount;
        $grandTotal += $netAmount;
        
        $updateItem = "UPDATE log_user_sales 
            SET product_quantity = '$qty', 
                product_price = '$price', 
                discount = '$discountPercent',
                net_amount = '$netAmount'
            WHERE order_id = '$orderId' AND id = '$id'";

        if (!mysqli_query($connection, $updateItem)) {
            die("Update failed: " . mysqli_error($connection));
        }
    }

    $updateDiscountAmount = "UPDATE log_user_sales 
        SET discount_amount = '$grandTotal'
        WHERE order_id = '$orderId'";

    if (!mysqli_query($connection, $updateDiscountAmount)) {
        die("Failed to update discount_amount: " . mysqli_error($connection));
    }

    echo "<script>alert('Order updated successfully!'); window.location.href='order_detail_v.php';</script>";
    exit();
}

$result = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$orderId'");
if (mysqli_num_rows($result) == 0) {
    die("Order not found.");
}
$orderRows = [];
while ($row = mysqli_fetch_assoc($result)) {
    $orderRows[] = $row;
}
ob_end_flush();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Wholesale Software</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-5">
    <h3>Edit Order: <?php echo htmlspecialchars($orderId); ?></h3>
    <form method="POST" id="editForm">
        <table class="table text-center table-sm" style="font-size:14px;">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price(Rs)</th>
                    <th>Discount(%)</th>
                    <th>Total(Rs)</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orderRows as $row): ?>
                    <tr>
                        <td><?php echo $row['product_name']; ?></td>
                        <td>
                            <input type="number" name="quantities[<?php echo $row['id']; ?>]" class="form-control qty" value="<?php echo $row['product_quantity']; ?>" min="1">
                        </td>
                        <td>
                            <input type="number" name="prices[<?php echo $row['id']; ?>]" class="form-control price" value="<?php echo $row['product_price']; ?>" step="0.01">
                        </td>
                        <td>
                            <input type="number" name="discounts[<?php echo $row['id']; ?>]" class="form-control discount" value="<?php echo $row['discount']; ?>" step="0.01">
                        </td>
                        <td class="total">0</td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="text-end">
            <p><strong>Sub:</strong> Rs <span id="subtotal">0</span></p>
            <p><strong>Total:</strong> Rs <span id="grandtotal">0</span></p>
        </div>

        <button type="submit" class="btn btn-success">Update Order</button>
        <a href="order_detail_v.php" class="btn btn-secondary">Cancel</a>
    </form>

    <script>
        function calculateTotals() {
            let subtotal = 0;
            document.querySelectorAll('tbody tr').forEach(function(row) {
                const qty = parseFloat(row.querySelector('.qty').value) || 0;
                const price = parseFloat(row.querySelector('.price').value) || 0;
                const discountPercent = parseFloat(row.querySelector('.discount').value) || 0;
                
                const gross = qty * price;
                const discountAmount = (gross * discountPercent) / 100;
                const total = gross - discountAmount;

                row.querySelector('.total').innerText = total.toFixed(2);
                subtotal += total;
            });
            document.getElementById('subtotal').innerText = subtotal.toFixed(2);
            document.getElementById('grandtotal').innerText = subtotal.toFixed(2);
        }

        document.querySelectorAll('.qty, .price, .discount').forEach(el => {
            el.addEventListener('input', calculateTotals);
        });

        window.addEventListener('DOMContentLoaded', calculateTotals);
    </script>
</body>
</html>
