<?php
session_start();
require 'shikanisha.kts.php';

function generateRandomInvoiceId() {
    return rand(100000, 999999);
}

if (isset($_SESSION['purchaseCart']) && !empty($_SESSION['purchaseCart'])) {
    $cart = $_SESSION['purchaseCart'];
    $conn->begin_transaction();

    try {
        $totalSubtotal = 0;
        
        foreach ($cart as $item) {
            $buyingPrice = $item['buyingPrice'];
            $quantity = $item['quantity'];
            $totalSubtotal += $buyingPrice * $quantity;
        }

        // Insert into the purchase table
            $invoiceId = isset($_POST['invoice_id']) ? $_POST['invoice_id'] : generateRandomInvoiceId();
    $vendorId = isset($_POST['vendor_id']) ? $_POST['vendor_id'] : 1;
        
        $purchaseInsertQuery = $conn->prepare(
            "INSERT INTO purchase (vendor_id, payment_method, purchase_date, total_amount) VALUES (?, ?, NOW(), ?)"
        );
        $purchaseInsertQuery->bind_param('isd', $vendorId, $paymentMethod, $totalSubtotal);

        if (!$purchaseInsertQuery->execute()) {
            throw new Exception('Error inserting into purchase: ' . $purchaseInsertQuery->error);
        }
        
        $invoiceId = $conn->insert_id;

        foreach ($cart as $item) {
            $id = $item['id'];
            $name = $item['name'];
            $category = $item['category'];
            $buyingPrice = $item['buyingPrice'];
            $quantity = $item['quantity'];
            $availability = $item['availability'];

            if ($category === 'Beverage') {
                $updateBeverages = $conn->prepare(
                    "UPDATE beverages SET buying_price = ?, quantity = quantity + ? WHERE beverage_id = ? "
                );
                $updateBeverages->bind_param('dii', $buyingPrice, $quantity, $id);

                if (!$updateBeverages->execute()) {
                    throw new Exception('Error updating beverages: ' . $updateBeverages->error);
                }

                $purchaseOrderQuery = $conn->prepare(
                    "INSERT INTO purchase_orders (purchase_date, productname, price, quantity, subtotal, invo_id, category, product_id) 
                    VALUES (NOW(), ?, ?, ?, ?, ?, 'Beverages', ?)"
                );
                $subtotal = $buyingPrice * $quantity;
                $purchaseOrderQuery->bind_param('sdiisi', $name, $buyingPrice, $quantity, $subtotal, $invoiceId, $id);

                if (!$purchaseOrderQuery->execute()) {
                    throw new Exception('Error inserting into purchase_orders (Beverages): ' . $purchaseOrderQuery->error);
                }
            } elseif ($category === 'Ingredient') {
                $updateIngredients = $conn->prepare(
                    "UPDATE ingredients SET quantity = quantity + ?, buying_price = ? WHERE id = ?"
                );
                $updateIngredients->bind_param('idi', $quantity, $buyingPrice, $id);

                if (!$updateIngredients->execute()) {
                    throw new Exception('Error updating ingredients: ' . $updateIngredients->error);
                }

                $purchaseOrderQuery = $conn->prepare(
                    "INSERT INTO purchase_orders (purchase_date, productname, price, quantity, subtotal, invo_id, category, product_id) 
                    VALUES (NOW(), ?, ?, ?, ?, ?, 'Ingredients', ?)"
                );
                $subtotal = $buyingPrice * $quantity;
                $purchaseOrderQuery->bind_param('sdiisi', $name, $buyingPrice, $quantity, $subtotal, $invoiceId, $id);

                if (!$purchaseOrderQuery->execute()) {
                    throw new Exception('Error inserting into purchase_orders (Ingredients): ' . $purchaseOrderQuery->error);
                }
            }
        }

        // Update vendor's amount_owed
        $updateVendorDebts = $conn->prepare(
            "UPDATE vendor_debts SET amount_owed = amount_owed + ? WHERE vendor_id = ?"
        );
        $updateVendorDebts->bind_param('di', $totalSubtotal, $vendorId);

        if (!$updateVendorDebts->execute()) {
            throw new Exception('Error updating vendor_debts: ' . $updateVendorDebts->error);
        }

        // Insert into vendor_transactions
        $vendorTransactionQuery = $conn->prepare(
            "INSERT INTO vendor_transactions (amount_transacted, transaction_type, vendor_id, date) 
            VALUES (?, 'Invoice', ?, NOW())"
        );
        $vendorTransactionQuery->bind_param('di', $totalSubtotal, $vendorId);

        if (!$vendorTransactionQuery->execute()) {
            throw new Exception('Error inserting into vendor_transactions: ' . $vendorTransactionQuery->error);
        }

        $conn->commit();
        unset($_SESSION['purchaseCart']);
        echo json_encode(['status' => 'success', 'message' => 'Products received and processed successfully']);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Error processing the cart: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'No items in the cart to receive']);
}

$conn->close();
?>
