<?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'];
    $discountAmounts = $_POST['discount_amounts'];
    $orderDiscount = isset($_POST['order_discount']) ? (float)$_POST['order_discount'] : 0;
    $preAmount = isset($_POST['pre_amount']) ? (float)$_POST['pre_amount'] : 0;
    $cashPaid = isset($_POST['cash_paid']) ? (float)$_POST['cash_paid'] : 0;
    
    $grandTotal = 0;
    $subtotal = 0;
    $totalProductDiscount = 0;

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

        // Fetch original row
        $originalQuery = mysqli_query(
            $connection,
            "SELECT * 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'];
        $oldPrice       = (float)$originalData['product_price'];
        $tradePrice     = (float)$originalData['trade_price'];
        
        // Get discount values
        $oldDiscount = isset($originalData['discount']) ? (float)$originalData['discount'] : 0;
        $oldDiscAmount = isset($originalData['dis_amount']) ? (float)$originalData['dis_amount'] : 0;

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

        // Update products table (quantity adjustment based on trade price)
        $amountDiff = $qtyDiff * $tradePrice;
        $stockUpdate = "
            UPDATE products 
            SET quantity = quantity - ($qtyDiff),
                total_amount = total_amount - ($amountDiff)
            WHERE product_id = '$productId'";
        mysqli_query($connection, $stockUpdate);

        // Get sale cost
        $saleCost = 0;
        if (isset($_POST['sale_costs'][$id])) {
            $saleCost = (float)$_POST['sale_costs'][$id];
        } elseif (isset($originalData['sale_cost'])) {
            $saleCost = (float)$originalData['sale_cost'];
        }

        // Calculate totals for this product
        $gross = $qty * $price;
        $productTotal = $gross;
        
        // Use the discount amount directly from form
        $discountAmount = $dAmt;
        
        // Calculate discount percentage for consistency
        $discountPercent = $gross > 0 ? ($discountAmount / $gross) * 100 : 0;
        
        $netAmount = $gross - $discountAmount;
        
        // Add to totals
        $subtotal += $gross;
        $totalProductDiscount += $discountAmount;
        $grandTotal += $netAmount;

        // Update purchase row with correct field names
        $updateQuery = "
            UPDATE purchase 
            SET product_quantity = '$qty', 
                product_price    = '$price', 
                discount         = '$discountPercent',
                dis_amount       = '$discountAmount',
                net_amount       = '$netAmount',
                sale_cost        = '$saleCost',
                product_total    = '$productTotal'
            WHERE inv_id = '$orderId' AND id = '$id'";

        if (!mysqli_query($connection, $updateQuery)) {
            die("Update failed: " . mysqli_error($connection));
        }
    }
    
    // Calculate order-level totals
    $totalAfterProductDiscount = $grandTotal;
    $totalAfterOrderDiscount = $totalAfterProductDiscount - $orderDiscount;
    $finalGrandTotal = $totalAfterOrderDiscount + $preAmount;
    $remaining = $finalGrandTotal - $cashPaid;
    
    // Calculate change (if cash paid > grand total)
    $changeAmount = max($cashPaid - $finalGrandTotal, 0);
    
    // Update all order-level fields
    $updateOrderQuery = "
        UPDATE purchase 
        SET discounted     = '$orderDiscount',
            pre_amount     = '$preAmount',
            cash_amount    = '$cashPaid',
            change_amount  = '$changeAmount',
            grand_amount   = '$finalGrandTotal',
            total_amount   = '$finalGrandTotal',
            discount_amount = '$finalGrandTotal'
        WHERE inv_id = '$orderId'";
    
    if (!mysqli_query($connection, $updateOrderQuery)) {
        die("Failed to update order totals: " . mysqli_error($connection));
    }

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

// Fetch invoice details
$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;
}

// Calculate initial totals
$initialSubtotal = 0;
$initialProductDiscounts = 0;
$initialGrandTotal = 0;
foreach ($orderRows as $row) {
    $gross = $row['product_quantity'] * $row['product_price'];
    
    // Get discount amount from dis_amount field
    $discountAmount = isset($row['dis_amount']) ? (float)$row['dis_amount'] : 0;
    
    $netAmount = $gross - $discountAmount;
    
    $initialSubtotal += $gross;
    $initialProductDiscounts += $discountAmount;
    $initialGrandTotal += $netAmount;
}

ob_end_flush();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Purchase Invoice</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body class="container mt-5">
    <h3>Edit Purchase 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>Qty</th>
                    <th>Price</th>
                    <th>Discount(%)</th>
                    <th>Discount(Rs)</th>
                    <th>Sale Cost</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orderRows as $row): 
                    $gross = $row['product_quantity'] * $row['product_price'];
                    
                    // Get discount values
                    $discountPercent = isset($row['discount']) ? (float)$row['discount'] : 0;
                    $discountAmount = isset($row['dis_amount']) ? (float)$row['dis_amount'] : 0;
                    $netAmount = $gross - $discountAmount;
                ?>
                    <tr>
                        <td><?php echo htmlspecialchars($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_percent"
                                   value="<?php echo $discountPercent; ?>"
                                   step="any">
                        </td>
                        <td>
                            <input type="number"
                                   name="discount_amounts[<?php echo $row['id']; ?>]"
                                   class="form-control discount_amount"
                                   value="<?php echo $discountAmount; ?>"
                                   step="any">
                        </td>
                        <td>
                            <input type="number"
                                   name="sale_costs[<?php echo $row['id']; ?>]"
                                   class="form-control sale_cost"
                                   value="<?php echo isset($row['sale_cost']) ? $row['sale_cost'] : 0; ?>"
                                   step="0.01">
                        </td>
                        <td class="total"><?php echo number_format($netAmount, 2); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <div class="text-end mt-3">
            <p><strong>Total Products:</strong> Rs <span id="total_products"><?php echo number_format($initialGrandTotal, 2); ?></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 
                           value="<?php echo number_format($initialGrandTotal, 2); ?>">
                </div>
                <div class="col-md-3">
                    <label>Order Discount (Rs)</label>
                    <input type="number" id="order_discount" name="order_discount" 
                           class="form-control"
                           value="<?php echo isset($orderRows[0]['discounted']) ? $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="<?php echo isset($orderRows[0]['pre_amount']) ? $orderRows[0]['pre_amount'] : 0; ?>" step="0.01">
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-3">
                    <label>Cash Paid (Rs)</label>
                    <input type="number" id="cash_paid" name="cash_paid" 
                           class="form-control"
                           value="<?php echo isset($orderRows[0]['cash_amount']) ? $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 
                           value="<?php echo number_format($initialGrandTotal, 2); ?>">
                </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>

        <button type="submit" class="btn btn-success mt-3">Update Invoice</button>
        <a href="purchase_detail_v.php" class="btn btn-secondary mt-3">Cancel</a>
    </form>

<script>
function calculateTotals() {
    let subtotal = 0;
    let productDiscounts = 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;

        // Calculate gross
        let gross = qty * price;

        // Sync discount percentage and amount
        if (document.activeElement === percentInput) {
            // User edited percentage - calculate amount
            discountAmount = (gross * discountPercent) / 100;
            amountInput.value = discountAmount.toFixed(2);
        } else if (document.activeElement === amountInput) {
            // User edited amount - calculate percentage
            discountPercent = gross > 0 ? (discountAmount / gross) * 100 : 0;
            percentInput.value = discountPercent.toFixed(2);
        } else {
            // Initial load or other changes
            discountAmount = (gross * discountPercent) / 100;
            amountInput.value = discountAmount.toFixed(2);
        }

        // Calculate net amount
        let netAmount = gross - discountAmount;
        row.querySelector(".total").innerText = netAmount.toFixed(2);

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

    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 calculations
    let orderDiscount = parseFloat(document.getElementById("order_discount").value) || 0;
    let preAmount = parseFloat(document.getElementById("pre_amount").value) || 0;
    let cashPaid = parseFloat(document.getElementById("cash_paid").value) || 0;

    let totalAfterOrderDiscount = totalAfterProductDiscount - orderDiscount;
    let grandTotal = totalAfterOrderDiscount + preAmount;
    let remaining = grandTotal - cashPaid;
    let changeAmount = Math.max(cashPaid - grandTotal, 0);
    
    // If cash paid is more than grand total, remaining is 0
    if (cashPaid > grandTotal) {
        remaining = 0;
    }

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

// Event listeners
document.querySelectorAll(".qty, .price, .discount_percent, .discount_amount, .sale_cost").forEach(el => {
    el.addEventListener("input", calculateTotals);
});

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

// Calculate on page load
window.addEventListener("DOMContentLoaded", calculateTotals);
</script>


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