<?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 ID to update has been sent via post
    if (isset($_GET['deleteToolID']) && isset($userRow['CanModify']) && $userRow['CanModify']==1){
        // Get the tool ID to work with
        $toolID = $_GET['deleteToolID'];

        // Create query to determine if this tool is tied to anything
        $sql='SELECT at.CurrentToolID AS CurrentToolID, m.Name, at.Position ' .
             'FROM assignedtools at, ' .
                  'machines m ' .
             'WHERE m.MachineID=at.MachineID ' . 
                  'AND at.CurrentToolID=' . $toolID . ';';

        // Determine if this tool is tied to anything
        $rows = $db->queryDB($sql, $userRow, "delete_tool Form occurance 1");
        
        // Check to see if there are any
        if ($rows != null && 
            mysqli_num_rows($rows)>0){
                // Init a message
                $message='';
                
                // Loop through the returned results
                $amount=0;
                $lastOneUpdated = '';
                while ($row=mysqli_fetch_array($rows)){
                    // Add to the message this machine and at which slot it is at
                    $message = $message . '"'. $row["Name"] . '" at position ' . $row["Position"] . ', ';
                }
                
                // Remove the last comma and space
                $message = substr($message, 0, -2);

                // Let the user know it will NOT be deleted.
                echo "<script type='text/javascript'>alert('This tool is assigned to machine(s) and slot ($message). It will not be deleted until those are cleared');</script>";
        }
        else {
            // Get the query to delete this tool
            $sql="DELETE FROM tools where ToolID=" . $toolID . ";";

            // Run the delete query
            $db->queryDB($sql, $userRow, "delete_tool Form occurance 2");
        }
    }

    // Go to the tools list
   echo ('<script>window.location = "../tools.php";</script>');
?>