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

        // Get the material row that is being deleted
        $materialRow = $db->queryDB($sql, $userRow, "delete_material Form occurance 1");
        
        // Check to ensure there is a row to delete before anything
        if (mysqli_num_rows($materialRow)==1){
            // Get a query to determine if there is any associations now
            $sql = 'SELECT (' . 
                    '(SELECT COUNT(*) AS BlankCount FROM jobblanks WHERE MaterialID = ' . $materialID . ') + ' . 
                    '(SELECT COUNT(*) AS StockCount FROM materialstock WHERE MaterialID = ' . $materialID . ')' . 
                    ') as TotalCount';
            
            // Determine if there are any associations first
            $materialAssociatedRow = $db->queryDB($sql, $userRow, "delete_material Form occurance 2");
            
            // Get the current task row to work with as the assoc style
            $materialAssociatedAssocRow = $materialAssociatedRow->fetch_assoc();
            
            // Determine ig there re rows using this ID
            if ($materialAssociatedAssocRow["TotalCount"]==0){
                // Get the query to delete this material
                $sql="DELETE FROM material where MaterialID=" . $materialID . ";";

                // Run the delete query
                $db->queryDB($sql, $userRow, "delete_material Form occurance 3");
            }
            else {
                echo '<script>alert("This material was NOT deleted because it has associations ' . 
                     'either with blanks used for jobs or materials in-house. If ' .
                     'you would still like to delete this material 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 = "../materialTypes.php";</script>');
?>