<?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 tool type ID to update has been sent via post
    if (isset($_GET['deleteToolTypeID']) && isset($userRow['CanModify']) && $userRow['CanModify']==1){
        // Get the tool type ID to work with
        $toolTypeID = $_GET['deleteToolTypeID'];
        
        // Get the tool type row we will update
        $sql = 'SELECT * FROM tooltype WHERE ToolTypeID=' . $toolTypeID . ';';

        // Get the tool type row that is being deleted
        $toolTypeRow = $db->queryDB($sql, $userRow, "delete_tooltype Form occurance 1");
        
        // Check to ensure there is a row to delete before anything
        if (mysqli_num_rows($toolTypeRow)==1){
            // Get a query to determine if there is any associations now
            $sql = 'SELECT COUNT(*) AS ToolCount FROM tools WHERE ToolTypeID = ' . 
                    $toolTypeID . ';';
            
            // Determine if there are any associations first
            $toolsAssociatedRow = $db->queryDB($sql, $userRow, "delete_tooltype Form occurance 2");
            
            // Get the amount of rows associated with this type
            $toolsAssociatedAssocRow = $toolsAssociatedRow->fetch_assoc();
            
            // Determine if there are rows using this ID
            if ($toolsAssociatedAssocRow["TotalCount"]==0){
                // Get the query to delete this tool type
                $sql="DELETE FROM tooltype where ToolTypeID=" . $toolTypeID . ";";

                // Run the delete query
                $db->queryDB($sql, $userRow, "delete_material Form occurance 3");
            }
            else {
                echo '<script>alert("This tool type was NOT deleted because it has ' . 
                     'associations with a tool. If you would still like to delete ' . 
                     'this tool type either remove the associations or speak with ' . 
                     'the tech team to find out where the association is");</script>';
            }
        }
    }

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