<?php 
    // continue the session
    session_start();
    
    include '../php_only_scripts/database.php';
    
    // Init 
    $userRow=null;

    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser(session_id());

    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser == null){
        exit;
    }
    elseif (mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
    }

    // Determine if the task ID to update has been sent via post
    if (isset($_GET['deleteVendorID']) && $userRow['CanModify']==1){
        // Get the task ID to work with
        $vendorID = $_GET['deleteVendorID'];
        
        // Get the task row we will update
        $sql = 'SELECT * FROM vendors WHERE VendorID=' . $vendorID . ';';

        // Get the vendor row that is being deleted
        $vendorRow = $db->queryDB($sql, $userRow, "delete_vendor Form occurance 1");
        
        // Check to ensure there is a row to delete
        if (mysqli_num_rows($vendorRow)==1){
            // Get the query to delete this vendor
            $sql="DELETE FROM vendors where VendorID=" . $vendorID . ";";

            // Run the delete query
            $db->queryDB($sql, $userRow, "delete_vendor Form occurance 2");
            
            // Delete from the addresses table all that are associated with this vendor
            $sql="DELETE FROM addresses where AddressID IN " .
                    "(" .
                        "SELECT AddressID FROM addresslinker WHERE VendorID=" . $vendorID . 
                    ");";

            // Run the delete query for the vendor table
            $db->queryDB($sql, $userRow, "delete_vendor Form occurance 3");

            // Get the query to delete this vendor from the linker table
            $sql="DELETE FROM addresslinker where VendorID=" . $vendorID . ";";

            // Run the delete query
            $db->queryDB($sql, $userRow, "delete_vendor Form occurance 4");

            // Get the query to update the tool table with this vendor to be nobody now
            $sql="UPDATE tools SET VendorID=-1 WHERE VendorID=" . $vendorID . ";";

            // Run the update query
            $db->queryDB($sql, $userRow, "delete_vendor Form occurance 5");

            // Get the query to update the stock table with this vendor to be nobody now
            $sql="UPDATE materialstock SET VendorID=-1 WHERE VendorID=" . $vendorID . ";";

            // Run the update query
            $db->queryDB($sql, $userRow, "delete_vendor Form occurance 6");
        }
    }

    // Go to the task that is in memory to update
    echo ('<script>window.location = "../vendors.php";</script>');
?>