<?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'];
    $orderDiscount = isset($_POST['order_discount']) ? (float)$_POST['order_discount'] : 0;
    $preAmount = isset($_POST['pre_amount']) ? (float)$_POST['pre_amount'] : 0;
    $cashReceived = isset($_POST['cash_received']) ? (float)$_POST['cash_received'] : 0;
    
    $grandTotal   = 0;
    $subtotal = 0;
    $totalProductDiscount = 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 product_quantity, trade_price, product_id, sale_cost 
             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'];
        $tradePrice = (float)$r['trade_price'];
        $productId = (int)$r['product_id'];
        $currentSaleCost = (float)$r['sale_cost'];

        // Calculate new sale_cost AS REQUESTED: quantity × sale_cost
        // But first we need to get the original per-unit sale cost
        // If original quantity was > 0, divide to get per-unit cost
        $perUnitSaleCost = $oldQty > 0 ? ($currentSaleCost / $oldQty) : $tradePrice;
        $newSaleCost = $qty * $perUnitSaleCost;

        // Quantity difference
        $qtyDiff = $qty - $oldQty;

        // Amount difference (qty diff × trade price)
        $amountDiff = $qtyDiff * $tradePrice;

        // Update products table (quantity + total_amount)
        mysqli_query(
            $connection,
            "UPDATE products 
             SET 
                quantity = GREATEST(quantity - ($qtyDiff), 0),
                total_amount = GREATEST(total_amount - ($amountDiff), 0)
             WHERE product_id='$productId'"
        );

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

        // Net amount
        $netAmount = $gross - $dAmt;
        $grandTotal += $netAmount;
        $subtotal += $gross;
        $totalProductDiscount += $dAmt;

        // Update log_user_sales row - SALE_COST UPDATE ADDED HERE
        mysqli_query(
            $connection,
            "UPDATE log_user_sales 
             SET product_quantity='$qty',
                 product_price='$price',
                 discount='$discountPercent',
                 disc_amount='$dAmt',
                 net_amount='$netAmount',
                 product_total='$gross',
                 sale_cost='$newSaleCost'  -- ADDED THIS LINE: product_quantity × sale_cost
             WHERE id='$id' AND order_id='$orderId'"
        );
    }
    
    // Calculate order-level totals
    $totalAfterProductDiscount = $grandTotal; // Already has product discounts applied
    $totalAfterOrderDiscount = $totalAfterProductDiscount - $orderDiscount;
    $finalGrandTotal = $totalAfterOrderDiscount + $preAmount;
    $remaining = $finalGrandTotal - $cashReceived;
    
    // Calculate change (if cash received > grand total)
    $changeAmount = max($cashReceived - $finalGrandTotal, 0);
    
    // Update all order-level fields for ALL rows with this order_id
    mysqli_query(
        $connection,
        "UPDATE log_user_sales 
         SET discounted = '$orderDiscount',
             pre_amount = '$preAmount',
             cash_amount = '$cashReceived',
             change_amount = '$changeAmount',
             grand_amount = '$finalGrandTotal',
             BillAmount = '$finalGrandTotal',
             total_amount = '$finalGrandTotal',
             discount_amount = '$finalGrandTotal'
         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'");
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">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<style>
    label, th{
        font-weight:700;
    }
</style>
<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>Sale Cost</th>
<th>Discount(%)</th>
<th>Discount(Rs)</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($orderRows as $row): 
    $rowTotal = ((int)$row['product_quantity'] * (int)$row['product_price']) - (int)$row['disc_amount'];
    // Calculate per unit sale cost for JavaScript
    $perUnitSaleCost = $row['product_quantity'] > 0 ? ($row['sale_cost'] / $row['product_quantity']) : $row['trade_price'];
?>
<tr data-perunit="<?= $perUnitSaleCost; ?>">
<td><?= htmlspecialchars($row['product_name']); ?></td>
<td><input type="number" name="quantities[<?= $row['id']; ?>]" class="form-control qty"
           value="<?= $row['product_quantity']; ?>" min="1" step="any"></td>
<td><input type="number" name="prices[<?= $row['id']; ?>]" class="form-control price"
           value="<?= $row['product_price']; ?>" step="0.01"></td>
<td>
    <!-- Show sale cost (will be calculated automatically) -->
    <input type="number" name="sale_cost[<?= $row['id']; ?>]" class="form-control sale_cost"
           value="<?= $row['sale_cost']; ?>" step="0.01" readonly>
    <input type="hidden" class="per_unit_cost" value="<?= $perUnitSaleCost; ?>">
</td>
<td>
  <input type="number"
         class="form-control disc_percent"
         value="<?= $row['discount']; ?>"
         step="0.01"
         min="0"
         max="100">
</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"><?= number_format($rowTotal, 2); ?></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><strong>Total</strong></label>
            <input type="text" id="total_after_discount" class="form-control" readonly>
        </div>
        <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>Sub Total</label>
            <input type="number" id="sub_total"  
                   class="form-control"
                    step="0.01" readonly>
        </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>

    <div class="row mt-3">
        <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 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 class="col-md-3">
            <label><strong>Change Amount</strong></label>
            <input type="text" id="change_amount" class="form-control" readonly>
        </div>
    </div>
</div>

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

<script>
function calculateTotals() {
    let subtotal = 0;
    let productDiscounts = 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 perUnitCost = parseFloat(row.querySelector(".per_unit_cost").value) || 0;

        // Calculate new sale cost: product_quantity × per_unit_sale_cost
        let newSaleCost = qty * perUnitCost;
        row.querySelector(".sale_cost").value = newSaleCost.toFixed(2);

        // Calculate discount percentage
        let gross = qty * price;
        let discPercent = gross > 0 ? (dAmt / gross) * 100 : 0;
        row.querySelector(".disc_percent").value = discPercent.toFixed(2);
        
        let rowTotal = gross - dAmt;
        row.querySelector(".total").innerText = rowTotal.toFixed(2);

        subtotal += gross;
        productDiscounts += dAmt;
    });

    let totalAfterProductDiscount = subtotal - productDiscounts;
    
    // Update display
    document.getElementById("total_products").innerText = totalAfterProductDiscount.toFixed(2);
    document.getElementById("total_after_discount").value = totalAfterProductDiscount.toFixed(2);

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

    // === CALCULATIONS ===
    let totalAfterOrderDiscount = totalAfterProductDiscount - orderDiscount;
    let grandTotal = totalAfterOrderDiscount + preAmount;
    let remaining = grandTotal - cashReceived;
    let changeAmount = Math.max(cashReceived - grandTotal, 0);
    
    // If cash received is more than grand total, remaining is negative (change given)
    if (cashReceived > grandTotal) {
        remaining = 0;
    }

    document.getElementById("sub_total").value = totalAfterOrderDiscount.toFixed(2);
    document.getElementById("grandtotal").value = grandTotal.toFixed(2);
    document.getElementById("remaining_amount").value = remaining.toFixed(2);
    document.getElementById("change_amount").value = changeAmount.toFixed(2);
}

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

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

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


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>