<?php
// establish database connection
include_once 'shikanisha.kts.php';
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// process form data
if(isset($_POST['vendorId']) && isset($_POST['paymentAmount']) && isset($_POST['paymentType'])) {
    $vendor_id = $_POST['vendorId'];
    $payment_amount = $_POST['paymentAmount'];
    $payment_type = $_POST['paymentType'];

    // retrieve current amount owed for vendor
    $sql = "SELECT amount_owed FROM vendor_debts WHERE vendor_id = '$vendor_id'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $current_amount_owed = $row['amount_owed'];
    } else {
        echo "Vendor debt not found";
        exit();
    }

    // calculate new amount owed based on payment type
    if($payment_type == "credit") {
        $new_amount_owed = $current_amount_owed + $payment_amount;
        $transaction_type = "Credit";
    } elseif($payment_type == "debit") {
        $new_amount_owed = $current_amount_owed - $payment_amount;
        $transaction_type = "Debit";
    } else {
        echo "Invalid payment type";
        exit();
    }

    // update vendor_debts table with new amount owed
    $sql = "UPDATE vendor_debts SET amount_owed = '$new_amount_owed' WHERE vendor_id = '$vendor_id'";
    if ($conn->query($sql) === TRUE) {
        $date=date('Y-m-d');
        // insert transaction record into vendor_transactions table
        $sql = "INSERT INTO vendor_transactions (vendor_id, amount_transacted, transaction_type, date) VALUES ('$vendor_id', '$payment_amount', '$transaction_type', '$date')";
        if ($conn->query($sql) === TRUE) {
            echo "Payment processed successfully";
        } else {
            echo "Error inserting transaction record: " . $conn->error;
        }
    } else {
        echo "Error updating record: " . $conn->error;
    }
} else {
    echo "Invalid form data";
}
$conn->close();
?>
