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


// Get the vendor transaction to be deleted
$transaction_id = $_POST['transaction_id'];
$sql = "SELECT vendor_id, amount_transacted, transaction_type FROM vendor_transactions WHERE id = $transaction_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$vendor_id = $row['vendor_id'];
$amount_transacted = $row['amount_transacted'];
$transaction_type = $row['transaction_type'];

// Delete the vendor transaction
$sql = "DELETE FROM vendor_transactions WHERE id = $transaction_id";
if ($conn->query($sql) === FALSE) {
  echo "Error deleting transaction: " . $conn->error;
  exit();
}

// Update the vendor debt balance
$sql = "SELECT amount_owed FROM vendor_debts WHERE vendor_id = $vendor_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = $row['amount_owed'];
if ($transaction_type == "Credit") {
  $new_balance = $balance - $amount_transacted;
} elseif ($transaction_type == "Debit") {
  $new_balance = $balance + $amount_transacted;
} else {
  echo "Invalid transaction type: " . $transaction_type;
  exit();
}

$sql = "UPDATE vendor_debts SET amount_owed = $new_balance WHERE vendor_id = $vendor_id";
if ($conn->query($sql) === FALSE) {
  echo "Error updating vendor debt balance: " . $conn->error;
  exit();
}

$conn->close();
?>
