<?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'];
    $cashReceived = isset($_POST['cash_received']) ? (float)$_POST['cash_received'] : 0;
    
    // Get order level values
    $orderDiscount = isset($_POST['order_discount']) ? (float)$_POST['order_discount'] : 0;
    $installation = isset($_POST['installation']) ? (float)$_POST['installation'] : 0;
    $preAmount = isset($_POST['pre_amount']) ? (float)$_POST['pre_amount'] : 0;
    
    $grandTotal   = 0;
    $subtotal = 0;

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

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

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

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

        // Calculate discount percent
        $gross           = $qty * $price;
        $discountPercent = $gross > 0 ? ($dAmt / $gross) * 100 : 0;

        // Net amount for this line item
        $netAmount = $gross - $dAmt;
        $subtotal += $netAmount;

        // Update log_user_sales row (without order-level fields)
        mysqli_query(
            $connection,
            "UPDATE log_user_sales 
             SET product_quantity='$qty',
                 product_price='$price',
                 discount='$discountPercent',
                 disc_amount='$dAmt',
                 net_amount='$netAmount'
             WHERE id='$id' AND order_id='$orderId'"
        );
    }
    
    // Calculate order-level totals
    $totalAfterDiscount = $subtotal - $orderDiscount;
    $grandTotal = $totalAfterDiscount + $installation + $preAmount;
    $remainingAmount = $grandTotal - $cashReceived;

    // Update all rows for this order_id with the order-level values
    mysqli_query(
        $connection,
        "UPDATE log_user_sales 
         SET discounted='$orderDiscount',
             installation='$installation',
             pre_amount='$preAmount',
             cash_amount='$cashReceived',
             discount_amount='$totalAfterDiscount',
             grand_amount='$grandTotal',
             change_amount='$remainingAmount'
         WHERE order_id='$orderId'"
    );

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

// Fetch order rows
$result = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id='$orderId' AND status = '' AND r_order_id = '' ");
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: <?= 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><?= htmlspecialchars($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 mt-3">
    <p><strong>Total Products:</strong> Rs <span id="total_products">0</span></p>

    <div class="row mt-3">

        <div class="col-md-3">
            <label>Order Discount (Rs)</label>
            <input type="number" id="order_discount" name="order_discount" 
                   class="form-control"
                   value="<?= $orderRows[0]['discounted'] ?? 0; ?>" step="0.01">
        </div>

        <div class="col-md-3">
            <label>Installation (Rs)</label>
            <input type="number" id="installation" name="installation" 
                   class="form-control"
                   value="<?= $orderRows[0]['installation'] ?? 0; ?>" step="0.01">
        </div>

        <div class="col-md-3">
            <label>Pre Amount (Rs)</label>
            <input type="number" id="pre_amount" name="pre_amount" 
                   class="form-control"
                   value="<?= $orderRows[0]['pre_amount'] ?? 0; ?>" step="0.01">
        </div>

        <div class="col-md-3">
            <label>Cash Received (Rs)</label>
            <input type="number" id="cash_received" name="cash_received" 
                   class="form-control"
                   value="<?= $orderRows[0]['cash_amount'] ?? 0; ?>" step="0.01">
        </div>

    </div>

    <div class="row mt-3">
        <div class="col-md-3">
            <label><strong>Total After Discount</strong></label>
            <input type="text" id="total_after_discount" class="form-control" readonly>
        </div>

        <div class="col-md-3">
            <label><strong>Grand Total</strong></label>
            <input type="text" id="grandtotal" class="form-control" readonly>
        </div>

        <div class="col-md-3">
            <label><strong>Remaining Amount</strong></label>
            <input type="text" id="remaining_amount" class="form-control" readonly>
        </div>
    </div>
</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) {

        let qty = parseFloat(row.querySelector(".qty").value) || 0;
        let price = parseFloat(row.querySelector(".price").value) || 0;
        let dAmt = parseFloat(row.querySelector(".disc_amt").value) || 0;

        let rowTotal = qty * price - dAmt;
        row.querySelector(".total").innerText = rowTotal.toFixed(2);

        subtotal += rowTotal;
    });

    document.getElementById("total_products").innerText = subtotal.toFixed(2);

    // === ORDER LEVEL VALUES ===
    let orderDiscount = parseFloat(document.getElementById("order_discount").value) || 0;
    let installation = parseFloat(document.getElementById("installation").value) || 0;
    let preAmount = parseFloat(document.getElementById("pre_amount").value) || 0;
    let cashReceived = parseFloat(document.getElementById("cash_received").value) || 0;

    // === SAME CALCULATION AS PREVIOUS PAGE ===
    let totalAfterDiscount = subtotal - orderDiscount;
    let grandTotal = totalAfterDiscount + installation + preAmount;
    let remaining = grandTotal - cashReceived;

    // === SET VALUES ===
    document.getElementById("total_after_discount").value = totalAfterDiscount.toFixed(2);
    document.getElementById("grandtotal").value = grandTotal.toFixed(2);
    document.getElementById("remaining_amount").value = remaining.toFixed(2);
}


document.querySelectorAll(".qty, .price, .disc_amt, .disc_percent").forEach(el => {
    el.addEventListener("input", calculateTotals);
});

["order_discount", "installation", "pre_amount", "cash_received"].forEach(id => {
    document.getElementById(id).addEventListener("input", calculateTotals);
});

window.addEventListener("DOMContentLoaded", calculateTotals);

</script>

</body>
</html>