<?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['deleteCompanyID']) && $userRow['CanModify']==1){
        // Get the task ID to work with
        $companyID = $_GET['deleteCompanyID'];
        
        // Get the task row we will update
        $sql = 'SELECT * FROM companies WHERE CompanyID=' . $companyID . ';';

        // Get the task row that is being deleted
        $companyRow = $db->queryDB($sql, $userRow, "delete_company Form occurance 1");
        
        // Check to ensure there is a row to delete
        if (mysqli_num_rows($companyRow)==1){
            // Get the query to delete this company
            $sql="DELETE FROM companies where CompanyID=" . $companyID . ";";

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

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

            // Get the query to delete this company from the linker table
            $sql="DELETE FROM addresslinker where CompanyID=" . $companyID . ";";

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

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