<?php
include("../db/cn.php");

if (isset($_GET['inv_id'])) {
    $orderId = $_GET['inv_id'];
    $sql = "SELECT * FROM purchase WHERE inv_id = '$orderId'";
    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
        $orderData = $result->fetch_all(MYSQLI_ASSOC);
    } else {
        echo "Purchase not found!";
        exit;
    }
} else {
    echo "Invalid request!";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $customerName   = $_POST['customer_name'];
    $customerPhone  = $_POST['customer_phone'];
    $paidBy         = $_POST['paid_by'];
    $productName    = $_POST['product_name'];
    $quantity       = $_POST['quantity'];
    $price          = $_POST['price'];
    $discount       = $_POST['discount'];

    $subtotal   = $quantity * $price;
    $finalTotal = $subtotal - $discount;
    if ($finalTotal < 0) $finalTotal = 0;

    $updateSql = "UPDATE purchase 
                  SET customer_name   = '$customerName', 
                      customer_phone  = '$customerPhone', 
                      paid_by         = '$paidBy',
                      product_name    = '$productName',
                      product_quantity= '$quantity',
                      product_price   = '$price',
                      discount_amount = '$discount',
                      product_total   = '$subtotal',
                      net_amount      = '$finalTotal'
                  WHERE inv_id = '$orderId'";

    if ($connection->query($updateSql) === TRUE) {
        echo "<script>alert('Purchase updated successfully!'); window.location.href='purchase_detail_v.php';</script>";
        exit;
    } else {
        echo "Error updating order: " . $connection->error;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Purchase</title>
    <!-- Bootstrap 5 CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body class="bg-light py-4">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">Edit Purhcase - <?php echo $orderId; ?></h4>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Customer Name</label>
                                    <input type="text" name="customer_name" class="form-control" value="<?php echo $orderData[0]['customer_name']; ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Customer Phone</label>
                                    <input type="text" name="customer_phone" class="form-control" value="<?php echo $orderData[0]['customer_phone']; ?>">
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Paid By</label>
                                <select name="paid_by" class="form-select">
                                    <option value="cash" <?php if ($orderData[0]['paid_by'] == 'cash') echo 'selected'; ?>>Cash</option>
                                    <option value="card" <?php if ($orderData[0]['paid_by'] == 'card') echo 'selected'; ?>>Credit</option>
                                </select>
                            </div>

                            <hr>
                            <h5 class="mb-3">Product Details</h5>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Product Name</label>
                                    <input type="text" name="product_name" class="form-control" value="<?php echo $orderData[0]['product_name']; ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Quantity</label>
                                    <input type="number" id="quantity" name="quantity" class="form-control" value="<?php echo $orderData[0]['product_quantity']; ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Price (Rs)</label>
                                    <input type="number" step="0.01" id="price" name="price" class="form-control" value="<?php echo $orderData[0]['product_price']; ?>" required>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-8"></div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Amount</label>
                                    <input type="number" step="0.01" id="discount" name="discount" class="form-control" value="<?php echo $orderData[0]['discount_amount']; ?>">
                                </div>
                            </div>

                            <div class="mt-4 text-end">
                                <button type="submit" class="btn btn-success">Update Purchase</button>
                                <a href="purchase_detail_v.php" class="btn btn-secondary">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const quantityInput = document.getElementById('quantity');
        const priceInput = document.getElementById('price');
        const discountInput = document.getElementById('discount');

        function recalc() {
            const qty = parseFloat(quantityInput.value) || 0;
            const price = parseFloat(priceInput.value) || 0;
            const discount = parseFloat(discountInput.value) || 0;
            const total = qty * price;
            discountInput.value = total >= 0 ? total.toFixed(2) : 0;
        }

        quantityInput.addEventListener('input', recalc);
        priceInput.addEventListener('input', recalc);
        discountInput.addEventListener('input', recalc);
    </script>
</body>
</html>