<?php
include 'auth_check.php';
header('Content-Type: application/json; charset=UTF-8');

try {
    $rawInput = file_get_contents('php://input');
    $data = json_decode($rawInput, true);

    if (!$data || empty($data['cart']) || !is_array($data['cart'])) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid bill payload.']);
        exit();
    }

    $bill_number = 'BILL' . time();
    $date = date('Y-m-d');
    $time = date('H:i:s');
    $user = $_SESSION['name'];
    $total_discount = 0;

    $conn->begin_transaction();

    foreach ($data['cart'] as $item) {
        $product = trim($item['product_name'] ?? '');
        $unit = trim($item['unit'] ?? '');
        $price = (float)($item['selling_price'] ?? 0);
        $qty = (float)($item['qty'] ?? 0);
        $discount = (float)($item['discount'] ?? 0);
        $itemStatus = trim($item['status'] ?? '');
        $sellingMode = trim($item['selling_mode'] ?? 'standard');
        $stockDeductQtyPerUnit = (float)($item['stock_deduct_qty_per_unit'] ?? 1);

        if ($product === '' || $qty <= 0) {
            throw new Exception('Invalid product row detected.');
        }

        if ($stockDeductQtyPerUnit <= 0) {
            $stockDeductQtyPerUnit = 1;
        }

        $stockDeductQty = $qty * $stockDeductQtyPerUnit;
        $sellAmount = ($price * $qty) - $discount;
        $lineTotal = $sellAmount;
        $total_discount += $discount;

        $stmt = $conn->prepare("INSERT INTO billing_data (bill_number, product_name, unit, selling_price, qty, discount, line_total, entered_date, entered_time, entered_user, selling_mode, stock_deduct_qty) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->bind_param("sssddddssssd", $bill_number, $product, $unit, $price, $qty, $discount, $lineTotal, $date, $time, $user, $sellingMode, $stockDeductQty);
        $stmt->execute();

        $stockRow = null;
        $stockLookup = $conn->prepare("SELECT id, purchased_qty, purchasing_price, base_unit_cost FROM stock WHERE product_name = ? LIMIT 1");
        $stockLookup->bind_param("s", $product);
        $stockLookup->execute();
        $stockRes = $stockLookup->get_result();

        if ($stockRes && $stockRes->num_rows > 0) {
            $stockRow = $stockRes->fetch_assoc();
        }

        if ($stockRow) {
            $newQty = (float)$stockRow['purchased_qty'] - $stockDeductQty;

            // Prevent negative stock from accidental oversell crash path
            if ($newQty < 0) {
                $newQty = 0;
            }

            $stockUpdate = $conn->prepare("UPDATE stock SET purchased_qty = ? WHERE id = ?");
            $stockUpdate->bind_param("di", $newQty, $stockRow['id']);
            $stockUpdate->execute();
        }

        if (strcasecmp($product, 'Other') === 0 || strcasecmp($itemStatus, 'Returned') === 0) {
            continue;
        }

        $purchaseUnitCost = 0;
        if ($stockRow) {
            $purchaseUnitCost = (float)($stockRow['base_unit_cost'] ?? 0);
            if ($purchaseUnitCost <= 0) {
                $purchaseUnitCost = (float)($stockRow['purchasing_price'] ?? 0);
            }
        }

        $purchasingAmount = $purchaseUnitCost * $stockDeductQty;
        $profit = $sellAmount - $purchasingAmount;

        $incomeStmt = $conn->prepare("INSERT INTO income_profit_data (bill_number, item, sell_amount, purchaing_amount, profit, entered_date, entered_time, entered_user) VALUES (?,?,?,?,?,?,?,?)");
        $incomeStmt->bind_param("ssdddsss", $bill_number, $product, $sellAmount, $purchasingAmount, $profit, $date, $time, $user);
        $incomeStmt->execute();
    }

    $netTotal = (float)($data['total_amount'] ?? 0);
    $receivedAmount = (float)($data['received_amount'] ?? 0);
    $balanceAmount = (float)($data['balance_amount'] ?? 0);

    $stmt2 = $conn->prepare("INSERT INTO selling_data (bill_number, total_amount, received_amount, balance_amount, total_discount, entered_date, entered_time, entered_user) VALUES (?,?,?,?,?,?,?,?)");
    $stmt2->bind_param("sdddssss", $bill_number, $netTotal, $receivedAmount, $balanceAmount, $total_discount, $date, $time, $user);
    $stmt2->execute();

    $conn->commit();

    $_SESSION['last_bill_number'] = $bill_number;

    echo json_encode([
        'status' => 'success',
        'bill_number' => $bill_number
    ]);
} catch (Throwable $e) {
    if (isset($conn) && $conn instanceof mysqli) {
        try {
            $conn->rollback();
        } catch (Throwable $rollbackError) {
        }
    }

    app_log_error('save_bill.php error: ' . $e->getMessage());

    http_response_code(503);
    echo json_encode([
        'status' => 'error',
        'message' => 'Bill could not be completed due to a connection or server issue. Please try again.'
    ]);
}
?>