<?php
    // *** This cron job should be run just before midnight.  the logic is assuming this is the case. ***

    include dirname(__FILE__) . '/../php_only_scripts/global_after_session.php';
    include dirname(__FILE__) . '/../php_only_scripts/database.php';
    
    // Function to check tool stock and then notify appropriate users
    function resetAllRunningTaskRouteNodes($db, $userRow){
        // create a query to get the super company (EES)
        $sql = 'SELECT * FROM companies WHERE SuperCompany=1;';

        // Query the database
        $companyRow = $db->queryDB($sql, $userRow, "stopstarttasksonbiztime occurance 1");

        // Determine if we have ONE row to parse.  Should be only one super company. 
        // I do not know what to do for multiple.
        if ($companyRow!=null){
            // Attempt to get the user row
            $companyAssocRow = $companyRow->fetch_assoc();
            
            // Create the dates for analysis
            $todayDate = new DateTime();
            $tomorrowDate = (new DateTime())->modify('+1 day');
            
            // Get the current date string
            $currentDate = new DateTime();
            $currentDate->modify('-1 hour');
            $currentDateString = $currentDate->format('Y-m-d H:i:s');

            // Put values for the real end time and real start time of nothing for now
            $realEndDate=null;
            $realStartDate=null;
            
            // Determine if this is a weekend, there is a date in the biz database for ending and that the shop is NOT a 24 hr shop
            if (($todayDate->format('N'))>=6 && 
                $companyAssocRow["WeekendEndWorkingTime"]!=null &&
                $companyAssocRow["WeekendEndWorkingTime"]!=$companyAssocRow["WeekendStartWorkingTime"]) {
                // Set the real ending date as the weekend end date
                $realEndDate=$todayDate->format('Y-m-d ') . $companyAssocRow["WeekendEndWorkingTime"];
            }
            else if (($todayDate->format('N'))<6 && 
                $companyAssocRow["WeekdayEndWorkingTime"]!=null &&
                $companyAssocRow["WeekdayEndWorkingTime"]!=$companyAssocRow["WeekdayStartWorkingTime"]) {
                // Set the real ending date as the weekday end date
                $realEndDate=$todayDate->format('Y-m-d ') . $companyAssocRow["WeekdayEndWorkingTime"];
            }
            
            // Determine if tomorrow is a weekend, there is a date in the biz database for starting and that the shop is NOT a 24 hr shop
            if (($tomorrowDate->format('N'))>=6 && 
                $companyAssocRow["WeekendStartWorkingTime"]!=null &&
                $companyAssocRow["WeekendStartWorkingTime"]!=$companyAssocRow["WeekendEndWorkingTime"]) {
                // Set the real starting date as the weekend start date
                $realStartDate=$tomorrowDate->format('Y-m-d ') . $companyAssocRow["WeekendStartWorkingTime"];
            }
            else if (($tomorrowDate->format('N'))<6 && 
                $companyAssocRow["WeekdayStartWorkingTime"]!=null &&
                $companyAssocRow["WeekdayStartWorkingTime"]!=$companyAssocRow["WeekdayEndWorkingTime"]) {
                // Set the real starting date as the weekday start date
                $realStartDate=$tomorrowDate->format('Y-m-d ') . $companyAssocRow["WeekdayStartWorkingTime"];
            }
            else {
                // Determine if there is a weekday date but no weekend
                if ($companyAssocRow["WeekendStartWorkingTime"]==null && 
                    $companyAssocRow["WeekdayStartWorkingTime"]!=null){
                    // Just get the next monday date
                    $nextMondayDate = ((new DateTime())->modify('+' . (8-$todayDate->format('N')) . ' day'));
                    
                    // Set that as the start of the task at the start time
                    $realStartDate=$nextMondayDate->format('Y-m-d ') . $companyAssocRow["WeekdayStartWorkingTime"];
                }
            }

            // Now determine if we have dates to work with
            if ($realEndDate!=null){
                // Make a query to close the current routing node with an auto appended note
                $sql='UPDATE taskstatusinfo_current ' .
                      'SET ActualTime=ActualTime+(IF(TimerStartDate IS NULL, 0, time_to_sec(timediff("' . $realEndDate . '", TimerStartDate))/3600)), ' .
                          'AutoAppendedNotes=CONCAT(AutoAppendedNotes, "\n\n' . $currentDateString . ': Actual time updated due to end of day event.") ' .
//                          'AutoAppendedNotes=CONCAT(AutoAppendedNotes, "\n\n-' . ($tomorrowDate->format('N')) . '- : ' . $realStartDate . ' : ' . $tomorrowDate->format('Y-m-d ') . '") ' .
                      'WHERE TimerStartDate IS NOT NULL ' .
                      'AND timediff("' . $realEndDate . '", TimerStartDate)>0;';

            }

            // Update the rows that need to have time calculated
            $db->queryDB($sql, $userRow, "startstoptasksonbiztime occurance 2");
            
            // Run the update query and check result
            if ($realStartDate!=null){
                // Make a query to update the actual time to the next day's start time
                $sql='UPDATE taskstatusinfo_current ' .
                     'SET TimerStartDate="' . $realStartDate . '" ' .
                     'WHERE TimerStartDate IS NOT NULL ' .
                     'AND timediff("' . $realEndDate . '",TimerStartDate)>0;';

                // Run the update query
                $db->queryDB($sql, $userRow, "startstoptasksonbiztime occurance 3");
            }
        }
    }
    
    // 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 to get the SU company hours of operation and reset open route nodes
            resetAllRunningTaskRouteNodes ($db, $userRow);        
        }
    }

    // Exit this code
    exit;
?>       

