<?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['inv_id'])) {
    die("Invoice ID not provided.");
}
$orderId = $_GET['inv_id'];

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

    $grandTotal = 0;

    foreach ($quantities as $id => $qty) {
        $price    = (float)$prices[$id];
        $discount = (float)$discounts[$id];
        $saleCost = (float)$saleCosts[$id];

        // ðŸŸ¢ Purani purchase entry nikalo
        $originalQuery = mysqli_query(
            $connection,
            "SELECT product_quantity, product_name, product_id, sale_cost 
             FROM purchase 
             WHERE id = '$id' AND inv_id = '$orderId'"
        );
        if (!$originalQuery || mysqli_num_rows($originalQuery) === 0) continue;

        $originalData   = mysqli_fetch_assoc($originalQuery);
        $originalQty    = (int)$originalData['product_quantity'];
        $productId      = $originalData['product_id'];
        $productName    = $originalData['product_name'];
        $oldSaleCost    = (float)$originalData['sale_cost'];

        $qty = (int)$qty;
        $qtyDiff = $qty - $originalQty;

        // ðŸŸ¢ Stock aur total_amount update karo
        $stockUpdate = "
            UPDATE products 
            SET quantity     = quantity - ($qtyDiff), 
                total_amount = total_amount - ($qtyDiff * $price) 
            WHERE product_id = '$productId'";
        mysqli_query($connection, $stockUpdate);

        // ðŸŸ¢ Per-unit sale cost calculate karo
        $perUnitSaleCost = ($originalQty > 0) ? ($oldSaleCost / $originalQty) : 0;

        // ðŸŸ¢ Sale cost proportional adjust
        $saleCost = $perUnitSaleCost * $qty;

        // ðŸŸ¢ Net amount (discount ke sath)
        $gross          = $qty * $price;
        $discountAmount = ($discount / 100) * $gross;
        $netAmount      = $gross - $discountAmount;

        $grandTotal += $netAmount;

        // ðŸŸ¢ Purchase row update karo
        $updateItem = "
            UPDATE purchase 
            SET product_quantity = '$qty', 
                product_price    = '$price', 
                discount         = '$discount',
                sale_cost        = '$saleCost',
                net_amount       = '$netAmount'
            WHERE inv_id = '$orderId' AND id = '$id'";

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

    // ðŸŸ¢ Grand total update karo
    $updateDiscountAmount = "
        UPDATE purchase 
        SET discount_amount = '$grandTotal'
        WHERE inv_id = '$orderId'";
    if (!mysqli_query($connection, $updateDiscountAmount)) {
        die("Failed to update discount_amount: " . mysqli_error($connection));
    }

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

// ðŸŸ¢ Invoice details fetch karo
$result = mysqli_query($connection, "SELECT * FROM purchase WHERE inv_id = '$orderId'");
if (mysqli_num_rows($result) == 0) {
    die("Invoice 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 Invoice: <?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>Discount(Rs)</th>
                    <th>Sale Cost(Rs)</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"
                                       data-per-unit-sale="<?php echo $row['product_quantity'] > 0 ? $row['sale_cost'] / $row['product_quantity'] : 0; ?>">
                            </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[<?= $row['id']; ?>]"
           class="form-control discount_percent"
           value="<?= $row['discount']; ?>"
           step="any"
           placeholder="%">
</td>
<td>
    
    <input type="number"
           class="form-control discount_amount mt-1"
           value=""
           step="any"
           placeholder="Rs">
</td>



                            <td>
                                <span class="sale_cost_cell">
                                    <?php echo number_format($row['sale_cost'], 2); ?>
                                </span>
                                <input type="hidden" 
                                       name="sale_costs[<?php echo $row['id']; ?>]" 
                                       class="sale_cost" 
                                       value="<?php echo $row['sale_cost']; ?>">
                            </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 Invoice</button>
        <a href="purchase_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 percentInput = row.querySelector(".discount_percent");
        const amountInput  = row.querySelector(".discount_amount");

        let discountPercent = parseFloat(percentInput.value) || 0;
        let discountAmount  = parseFloat(amountInput.value) || 0;

        // Gross
        let gross = qty * price;

        // ---- Sync Logic ----
        if (document.activeElement === percentInput) {
            // user edits percent → update Rs value
            discountAmount = (gross * discountPercent) / 100;
            amountInput.value = discountAmount.toFixed(2);
        }
        else if (document.activeElement === amountInput) {
            // user edits amount → update percent
            discountPercent = gross > 0 ? (discountAmount / gross) * 100 : 0;
            percentInput.value = discountPercent.toFixed(2);
        }
        else {
            // default load: calculate Rs from %
            discountAmount = (gross * discountPercent) / 100;
            amountInput.value = discountAmount.toFixed(2);
        }

        // Final total
        let total = gross - discountAmount;

        row.querySelector(".total").innerText = total.toFixed(2);

        subtotal += total;
    });

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

// Listeners
document.querySelectorAll(".qty, .price, .discount_percent, .discount_amount")
    .forEach(el => el.addEventListener("input", calculateTotals));

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


</body>
</html>
