<?php 
    include dirname(__FILE__) . '/../php_only_scripts/global_after_session.php';
    include dirname(__FILE__) . '/../php_only_scripts/database.php';
    
    // Check for old attachments
    function checkOldAttachments ($db, $userRow){
        // Determine if this user has the appropriate level and run assigned tool update query
        if ($userRow["UserLevel"] == 'SU' || 
            $userRow["UserLevel"] == 'EXECUTIVE' ||
            $userRow["UserLevel"] == 'MANAGEMENT'){
            // Create timestamp for two months ago
            $twoMonthsAgoDate = (new Datetime())->modify('-2 months');
            $twoMonthsAgoTS = $twoMonthsAgoDate->format('U');

            // Define a query to remove the old attachments from the attachments table
            //$sql = 'DELETE FROM attachments WHERE TaskID IS NULL AND SubmitDate <= FROM_UNIXTIME(' . $twoMonthsAgoTS . ');';
            $sql = 'DELETE ' .
                   'FROM attachments ' .
                   'WHERE NoteID IS NULL ' . 
                   'AND TaskID IN ' .
                   '(SELECT t.TaskID FROM tasks t ' .
                   'INNER JOIN companies c ' .
                   'ON t.CompanyID = c.CompanyID ' .
                   'WHERE c.Store = 0 AND c.MainSubCompany = 0 AND CleanUp = 1) ' .
                   'AND SubmitDate <= FROM_UNIXTIME(' . $twoMonthsAgoTS . ');';

            // Attempt to Remove old attachments and evaluate response
            if (!$db->queryDB($sql, $userRow, "log_check Form occurance 2")){
                // Log the error to the error file
                error_log("Unable to check and update the tasks for old attachments " . 
                          "Query Ran: " . $sql, 0);                

                // Send the error to the main SU of this database
                error_log("Unable to check and update the tasks for old attachments " . 
                          "Query Ran: " . $sql, 1, "sdunn@evolveeng.com");    
            }
        }
    }

    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to get the username and password
    $userName = 'cuser';
    $password = '1Crono2User3!';

    // Attempt to log in with this user
    $currentUser = $db->loginUser($userName, $password, 7777777);

    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser != null and mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

        // Determine if they are the SU company
        if ($userRow["CompanyID"]==1){
            // Check for old attachments and delete thm
            checkOldAttachments ($db, $userRow);        
        }
    }

    // Exit this code
    exit;
?>