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

$response = array(); // Response array to hold success/failure messages

if (!empty($_SESSION['cart'])) {
    $company = $_POST['company'];
    $invoice = $_POST['invoice'];
    $id = $_POST['id'];
    $totalCost = $_POST['totalcost'];
    $date = date('Y-m-d');

    $totalCost = 0; // Initialize total cost

    // Start a transaction
    $conn->begin_transaction();

    try {
        foreach ($_SESSION['cart'] as $item) {
            $product_name = $item['product_name'];
            $buying_price = $item['buying_price'];
            $shop_qty = $item['quantity'];
            $product_id = $item['product_id'];

            // Calculate quantity and subtotal
            $subtotal = $shop_qty * $buying_price;

            // Update the product
            $update_sql = "UPDATE products SET shop_quantity=shop_quantity+? WHERE product_id=?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("ii", $shop_qty, $product_id);
            $update_result = $update_stmt->execute();

            if (!$update_result) {
                throw new Exception("Product update failed");
            }

            // Add subtotal to total cost
            $totalCost += $subtotal;
        }

        // Insert into the invoice table
        $purchase_sql = "INSERT INTO invoice (invoice_number, date, total, supplier_name) VALUES (?, ?, ?, ?)";
        $purchase_stmt = $conn->prepare($purchase_sql);
        $purchase_stmt->bind_param("ssds", $invoice, $date, $totalCost, $company);
        $purchase_result = $purchase_stmt->execute();

        if (!$purchase_result) {
            throw new Exception("Invoice insertion failed");
        }

        // Get the last inserted invoice ID
        $invoice_id = $conn->insert_id;

        // Insert into the purchase_orders table for each product in the cart with the associated invoice ID
      foreach ($_SESSION['cart'] as $item) {
    $product_name = $item['product_name'];
    $buying_price = $item['buying_price'];
    $quantity = $item['quantity'];
    $subtotal = $quantity * $buying_price;

    $purchase_sql = "INSERT INTO purchase_orders (productname, purchase_date, price, quantity, subtotal, invo_id) VALUES (?, ?, ?, ?, ?, ?)";
    
    // Assuming $date and $invoice_id are defined elsewhere in your code
    $date = date('Y-m-d'); // Replace this with your actual date format

    $purchase_stmt = $conn->prepare($purchase_sql);

    // The 's' stands for string, 'd' for double, and 'i' for integer
    $purchase_stmt->bind_param("ssdidi", $product_name, $date, $buying_price, $quantity, $subtotal, $invoice_id);

    $purchase_result = $purchase_stmt->execute();

    if (!$purchase_result) {
        throw new Exception("Record not added to purchases successfully");
    }
}

// Close the prepared statement after the loop
$purchase_stmt->close();


        // Update vendor debts and add vendor transaction
        $transaction_type = "Purchase";
        $date = date('Y-m-d');
        $sql = "SELECT amount_owed FROM vendor_debts WHERE vendor_id = '$id'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $current_amount_owed = $row['amount_owed'];
            $new_amount_owed = $current_amount_owed + $totalCost;
            $sql = "UPDATE vendor_debts SET amount_owed = '$new_amount_owed' WHERE vendor_id = '$id'";

            if ($conn->query($sql) === TRUE) {
                $sql = "INSERT INTO vendor_transactions (vendor_id, amount_transacted, transaction_type, date) VALUES ('$id', '$totalCost', '$transaction_type', '$date')";

                if ($conn->query($sql) === TRUE) {
                    // If everything is successful, commit the transaction
                    $conn->commit();
                    $response['success'] = true;
                    $response['message'] = "Invoice received Successfully";
                } else {
                    throw new Exception("Vendor transaction not added successfully");
                }
            } else {
                throw new Exception("Vendor debt not updated successfully");
            }
        } else {
            throw new Exception("No vendor debt found");
        }
    } catch (Exception $e) {
        // If any query fails, roll back the transaction
        $conn->rollback();
        $response['success'] = false;
        $response['message'] = $e->getMessage();
    }

    $update_stmt->close();
} else {
    $response['success'] = false;
    $response['message'] = "Cart is empty.";
}

// Provide JSON response
header('Content-Type: application/json');
echo json_encode($response);

$conn->close();
?>
