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

        // Get the machine row we will update
        $sql = 'SELECT * FROM machines WHERE MachineID=' . $machineID . ';';

        // Get the machine row that is being deleted
        $machineRow = $db->queryDB($sql, $userRow, "delete_machine Form occurance 1");
        
        // Check to ensure there is a row to delete
        if (mysqli_num_rows($machineRow)==1){
            // Update the tools table to remove any tools that are labeled with this piece of machine
            $sql="UPDATE tools SET MachineID=NULL where MachineID=" . $machineID . ";";

            // Run the update query for the tool table table
            $db->queryDB($sql, $userRow, "delete_machine Form occurance 2");

            // Create a query to remove all rows associated with that machine
            $sql="DELETE FROM assignedtools " . 
                 "WHERE MachineID = " . $machineID . ";";

            // Attempt to delete them
            $db->queryDB($sql, $userRow, "delete_machine Form occurance 3");
                        
            // Get the query to delete this machine
            $sql="DELETE FROM machines where MachineID=" . $machineID . ";";

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

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