<?php
include_once("includes/config.php");
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $conn->beginTransaction();

        $invoice = $_POST['invoice'];
        $customer_id = $_POST['customer_id'];
        $date_sale = $_POST['date_sale'];
        $receive_amount = $_POST['receive_amount'];

        // Update main sale
        $update_sale = $conn->prepare("UPDATE stock_sale 
            SET customer_id = ?, date_sale = ?
            WHERE invoice = ?");
        $update_sale->execute([$customer_id, $date_sale, $invoice]);

        // Update payment
        $update_payment = $conn->prepare("UPDATE cash_deposit 
            SET amount = ?
            WHERE invoice = ?");
        $update_payment->execute([$receive_amount, $invoice]);

        // Process products
        foreach ($_POST['product_id'] as $index => $product_id) {
            $sale_item_id = $_POST['sale_item_id'][$index];
            $quantity = $_POST['quantity'][$index];
            $price = $_POST['price'][$index];

            if ($sale_item_id) {
                // Update existing item
                $update_item = $conn->prepare("UPDATE stock_sale 
                    SET sale_qty = ?, price = ?
                    WHERE sale_id = ?");
                $update_item->execute([$quantity, $price, $sale_item_id]);
            } else {
                // Insert new item
                $insert_item = $conn->prepare("INSERT INTO stock_sale 
                    (invoice, product_id, sale_qty, price)
                    VALUES (?, ?, ?, ?)");
                $insert_item->execute([$invoice, $product_id, $quantity, $price]);
            }
        }

        $conn->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>