<?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'];
    $discAmount = $_POST['discount_amt']; // user-entered discount in rupees

    $grandTotal = 0;
    $disAmounted = $_POST['discount_amount'];

    foreach ($quantities as $id => $qty) {
        $qty   = (float)$qty;
        $price = (float)$prices[$id];
        $dAmt  = (float)$discAmount[$id]; // discount in rupees

        // Fetch original row
        $q = mysqli_query(
            $connection,
            "SELECT * FROM log_user_sales WHERE id='$id' AND order_id='$orderId'"
        );
        if (!$q || mysqli_num_rows($q) === 0) continue;

        $r = mysqli_fetch_assoc($q);
        $oldQty = (float)$r['product_quantity'];
        $productId = $r['product_id'];

        // Stock adjust
        $qtyDiff = $qty - $oldQty;
        mysqli_query(
            $connection,
            "UPDATE products 
             SET quantity = quantity - ($qtyDiff)
             WHERE product_id='$productId'"
        );

        // NEW: discount percentage based on amount
        $gross = $qty * $price;
        $discountPercent = $gross > 0 ? ($dAmt / $gross) * 100 : 0;

        // Net
        $netAmount = $gross - $dAmt;
        $grandTotal += $netAmount;

        // Update row
        $update = "
            UPDATE log_user_sales 
            SET product_quantity='$qty',
                product_price='$price',
                discount='$discountPercent',
                disc_amount='$dAmt',
                net_amount='$netAmount',
                discount_amount='$disAmounted',
                grand_amount = '$disAmounted'
            WHERE id='$id' AND order_id='$orderId'
        ";

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

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

// Fetch rows
$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>Edit Order</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">
<table class="table text-center table-sm" style="font-size:14px;">
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Discount(%)</th>
<th>Discount(Rs)</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($orderRows as $row): ?>
<tr>
<td><?= $row['product_name']; ?></td>

<td><input type="number" name="quantities[<?= $row['id']; ?>]" class="form-control qty"
value="<?= $row['product_quantity']; ?>" min="1"></td>

<td><input type="number" name="prices[<?= $row['id']; ?>]" class="form-control price"
value="<?= $row['product_price']; ?>" step="0.01"></td>

<td><input type="number" class="form-control disc_percent" step="0.01"
value="<?= $row['discount']; ?>" ></td>

<td><input type="number" name="discount_amt[<?= $row['id']; ?>]" class="form-control disc_amt"
value="<?= $row['disc_amount']; ?>" step="0.01"></td>

<td class="total">0</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<div class="text-end">
    <p><strong>Total:</strong> Rs <span id="grandtotal">0</span></p>
    <input type="hidden" name="discount_amount" id="discount_amount_input" value="0">
</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 gtotal = 0;

    document.querySelectorAll("tbody tr").forEach(function(row) {
        let qty   = parseFloat(row.querySelector(".qty").value)   || 0;
        let price = parseFloat(row.querySelector(".price").value) || 0;
        let dAmtInput = row.querySelector(".disc_amt");
        let dPercentInput = row.querySelector(".disc_percent");

        let gross = qty * price;

        // Check which input is being changed last
        let lastChanged = row.dataset.lastChanged || 'amt'; // default to amount

        let dAmt = parseFloat(dAmtInput.value) || 0;
        let dPercent = parseFloat(dPercentInput.value) || 0;

        if (lastChanged === 'percent') {
            // Discount % entered, calculate amount
            dAmt = gross * (dPercent / 100);
            dAmtInput.value = dAmt.toFixed(2);
        } else {
            // Discount amount entered, calculate %
            dPercent = gross > 0 ? (dAmt / gross) * 100 : 0;
            dPercentInput.value = dPercent.toFixed(2);
        }

        let total = gross - dAmt;
        row.querySelector(".total").innerText = total.toFixed(2);

        gtotal += total;
    });

    document.getElementById("grandtotal").innerText = gtotal.toFixed(2);
    document.getElementById("discount_amount_input").value = gtotal.toFixed(2);
}

// Track last changed input
document.querySelectorAll(".qty, .price, .disc_amt, .disc_percent").forEach(el => {
    el.addEventListener("input", function() {
        let row = el.closest("tr");
        if (el.classList.contains("disc_percent")) {
            row.dataset.lastChanged = 'percent';
        } else if (el.classList.contains("disc_amt")) {
            row.dataset.lastChanged = 'amt';
        } else {
            row.dataset.lastChanged = 'amt'; // default for qty or price changes
        }
        calculateTotals();
    });
});

window.addEventListener("DOMContentLoaded", calculateTotals);
</script>

</body>
</html>
