function ApproveMainVacationRequest($requestID, $useFirst)
{
    $statusMessage = "";
    $succeeded = true;
    $absenceType = GetAnnualLeaveAbsenceTypeID();
    $request = RetrieveMainVacationRequestByID($requestID);
    if ($request != NULL) {
        $start = $request[MAIN_VACATION_1ST_START];
        $end = $request[MAIN_VACATION_1ST_END];
        if (!$useFirst) {
            $start = $request[MAIN_VACATION_2ND_START];
            $end = $request[MAIN_VACATION_2ND_END];
        }
        $succeeded = ProcessAbsenceRequest($request[MAIN_VACATION_EMP_ID], $start, $end, $absenceType, $statusMessage);
        if ($succeeded) {
            DeleteMainVacationRequest($requestID);
        }
    } else {
        $statusMessage .= "Error: Unable to process your request." . "The MainVacationRequest ID of {$requestID} " . "could not be found in the database. Please " . "contact your system administrator.</br>";
        $succeeded = false;
    }
    GenerateStatus($succeeded, $statusMessage);
}
function CreateMainVactionRequest($employeeID, $firstChoiceStartDate, $firstChoiceEndDate, $secondChoiceStartDate, $secondChoiceEndDate)
{
    $statusMessage = "";
    $request = NULL;
    //-------------------------------------------------------------------------
    // Validate Input parameters
    //-------------------------------------------------------------------------
    $inputIsValid = TRUE;
    $employee = RetrieveEmployeeByID($employeeID);
    if ($employee == NULL) {
        $statusMessage .= "Unrecognised Employee ID.</br>";
        error_log("Invalid employeeID passed to CreateMainVacationRequest." . " value=" . $employeeID);
        $inputIsValid = FALSE;
    }
    if (!isValidDate($firstChoiceStartDate)) {
        $statusMessage .= "1st Choice Start Date is not a valid Date.</br>";
        error_log("Invalid firstChoiceStartDate passed to CreateMainVacationRequest." . " value=" . $firstChoiceStartDate);
        $inputIsValid = FALSE;
    }
    if (!isValidDate($firstChoiceEndDate)) {
        $statusMessage .= "1st Choice Finish Date is not a valid Date.</br>";
        error_log("Invalid firstChoiceEndDate passed to CreateMainVacationRequest." . " value=" . $firstChoiceEndDate);
        $inputIsValid = FALSE;
    }
    if (!isValidDate($secondChoiceStartDate)) {
        $statusMessage .= "2nd Choice Start Date is not a valid Date.</br>";
        error_log("Invalid secondChoiceStartDate passed to CreateMainVacationRequest." . " value=" . $secondChoiceStartDate);
        $inputIsValid = FALSE;
    }
    if (!isValidDate($secondChoiceEndDate)) {
        $statusMessage .= "2nd Choice Finish Date is not a valid Date.</br>";
        error_log("Invalid secondChoiceEndDate passed to CreateMainVacationRequest." . " value=" . $secondChoiceEndDate);
        $inputIsValid = FALSE;
    }
    if (strtotime($firstChoiceEndDate) < strtotime($firstChoiceStartDate)) {
        $statusMessage .= "1st Choice End Date is before 1st Choice Start Date.</br>";
        error_log("First Choice End Date is before First Choice Start Date.");
        $inputIsValid = FALSE;
    }
    if (strtotime($secondChoiceEndDate) < strtotime($secondChoiceStartDate)) {
        $statusMessage .= "2nd Choice End Date is before 2nd Choice Start Date.</br>";
        error_log("Second Choice End Date is before Second Choice Start Date.");
        $inputIsValid = FALSE;
    }
    //------------------------------------------------------------------------
    // Need to check for booking range. Ensure than no booking period is more
    // than 30 days duration.
    //------------------------------------------------------------------------
    if (isValidDate($firstChoiceStartDate) && isValidDate($firstChoiceEndDate)) {
        $start_date = strtotime($firstChoiceStartDate);
        $end_date = strtotime($firstChoiceEndDate);
        $diff_date = $end_date - $start_date;
        $days = floor($diff_date / (60 * 60 * 24));
        if ($days > 30) {
            $statusMessage .= "First choice end date is more than 30 days from " . "start date <br/>";
            error_log("Invalid first choice passed to CreateMainVacationRequest.");
            $inputIsValid = FALSE;
        }
    }
    //------------------------------------------------------------------------
    // Need to check for booking range. Ensure than no booking period is more
    // than 30 days duration.
    //------------------------------------------------------------------------
    if (isValidDate($secondChoiceStartDate) && isValidDate($secondChoiceEndDate)) {
        $start_date = strtotime($secondChoiceStartDate);
        $end_date = strtotime($secondChoiceEndDate);
        $diff_date = $end_date - $start_date;
        $days = floor($diff_date / (60 * 60 * 24));
        if ($days > 30) {
            $statusMessage .= "second choice end date is more than 30 days from " . "start date <br/>";
            error_log("Invalid second choice passed to CreateMainVacationRequest.");
            $inputIsValid = FALSE;
        }
    }
    //-------------------------------------------------------------------------
    // Only attempt to insert a record in the database if the input parameters
    // are ok.
    //-------------------------------------------------------------------------
    if ($inputIsValid) {
        $request[MAIN_VACATION_REQ_ID] = NULL;
        $request[MAIN_VACATION_EMP_ID] = $employeeID;
        $request[MAIN_VACATION_1ST_START] = $firstChoiceStartDate;
        $request[MAIN_VACATION_1ST_END] = $firstChoiceEndDate;
        $request[MAIN_VACATION_2ND_START] = $secondChoiceStartDate;
        $request[MAIN_VACATION_2ND_END] = $secondChoiceEndDate;
        $success = sqlInsertMainVacationRequest($request);
        if (!$success) {
            $inputIsValid = false;
            $statusMessage .= "Unexpected error encountered with database. " . "Contact your system administrator.</br>";
            error_log("Failed to create main vacation request. ");
            $request = NULL;
        } else {
            //-----------------------------------------------------------------
            // Now that Main Vacation Request has been created, we need to
            // update the employee record to reference it. First, chcek to see
            // if the employee already has a main vacation request (in which
            //  case we need to deltete it.
            //-----------------------------------------------------------------
            if ($employee[EMP_MAIN_VACATION_REQ_ID] != NULL) {
                $count = DeleteMainVacationRequest($employee[EMP_MAIN_VACATION_REQ_ID]);
                if ($count == 0) {
                    $inputIsValid = false;
                    $statusMessage .= "Unexpected error encountered when removing" . " Main Vacation Request from Database. " . "Contact your system administrator.</br>";
                    error_log("Failed to delete main vacation request. ID=" . $employee[EMP_MAIN_VACATION_REQ_ID]);
                }
            }
            //-----------------------------------------------------------------
            // Now update the employee record to reference the new
            // MainVacationRequest record.
            //-----------------------------------------------------------------
            $employee[EMP_MAIN_VACATION_REQ_ID] = $request[MAIN_VACATION_REQ_ID];
            $success = UpdateEmployee($employee);
            if (!$success) {
                $statusMessage .= "Failed to update employee to reference new " . "main vacation request.";
                error_log("Failed to update employee to reference new " . "main vacation request.");
                $inputIsValid = false;
            } else {
                $statusMessage .= "Main Vacation Request successfully created.";
            }
        }
    }
    GenerateStatus($inputIsValid, $statusMessage);
    return $request;
}
function ProcessMainVacationRequests(&$statusMessage)
{
    $stoppedAtEmployeeID = NULL;
    //--------------------------------------------------------------------------
    // Need to get all main vacation requests in an order based on the employees
    // length of service, so use the bespoke SQL query below.
    //--------------------------------------------------------------------------
    $conn = $GLOBALS["connection"];
    $sql = "SELECT * FROM mainVacationRequestTable JOIN EmployeeTable " . "WHERE mainVacationRequestTable.EmployeeID = EmployeeTable.EmployeeID " . "ORDER BY EmployeeTable.dateJoinedTheCompany;";
    $result = mysqli_query($conn, $sql);
    if (!$result) {
        $statusMessage .= "SQL Error when accessing database.</br>";
        error_log("PerformSQL failed. Sql = {$sql}");
    } else {
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        $lastRequestGranted = TRUE;
        //---------------------------------------------------------------------
        // Process each request in turn until either all have been processed,
        // or we reach a request that can't be granted.
        //---------------------------------------------------------------------
        while ($row and $lastRequestGranted) {
            $id = $row[MAIN_VACATION_REQ_ID];
            $employeeID = $row[MAIN_VACATION_EMP_ID];
            $firstChoiceStartDate = $row[MAIN_VACATION_1ST_START];
            $firstChoiceEndDate = $row[MAIN_VACATION_1ST_END];
            $secondChoiceStartDate = $row[MAIN_VACATION_2ND_START];
            $secondChoiceEndDate = $row[MAIN_VACATION_2ND_END];
            $absenceTypeID = GetAnnualLeaveAbsenceTypeID();
            $Employee = RetrieveEmployeeByID($employeeID);
            $statusMessage .= "<b>[Processing main vacation request for " . $Employee[EMP_NAME] . "]</b><br/>";
            $statusMessage .= "Attempting first choice from {$firstChoiceStartDate} " . "to {$firstChoiceEndDate}.</br>";
            //Try and approve first choice request.
            if (ProcessAbsenceRequest($employeeID, $firstChoiceStartDate, $firstChoiceEndDate, $absenceTypeID, $statusMessage) == FALSE) {
                //First choice denied. Try and approve second choice request.
                $statusMessage .= "Attempting second choice from " . "{$secondChoiceStartDate} to {$secondChoiceEndDate}.</br>";
                if (ProcessAbsenceRequest($employeeID, $secondChoiceStartDate, $secondChoiceEndDate, $absenceTypeID, $statusMessage) == FALSE) {
                    //second choice denied. Mail employee to instruct them to
                    //submit a new booking.
                    $statusMessage .= "Neither first nor second choice could be " . "granted. Employee has been emailed to ask " . "for new dates.</br>";
                    SendResubmitMainVacationRequest($employeeID);
                    //set the ID of the employee who needs to resubmit, to
                    //pass back to the calling function.
                    $lastRequestGranted = FALSE;
                    $stoppedAtEmployeeID = $employeeID;
                }
            }
            //Delete the main vacation request.
            DeleteMainVacationRequest($id);
            $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        }
    }
    return $stoppedAtEmployeeID;
}
if (!$isAdministrator) {
    header('Location: index.php');
    exit;
}
if (isset($_POST["submit"])) {
    ClearStatus();
    $request = CreateMainVactionRequest($_POST["employeeID"], $_POST["firstChoiceStart"], $_POST["firstChoiceEnd"], $_POST["secondChoiceStart"], $_POST["secondChoiceEnd"]);
}
if (isset($_POST["amend"])) {
    ClearStatus();
    $url = "Location:editMainRequest.php?ID=" . $_POST["amend"] . "&back=adminMainVacationRequests.php";
    header($url);
}
if (isset($_POST["delete"])) {
    ClearStatus();
    DeleteMainVacationRequest($_POST["delete"]);
}
function PopulateTableBody()
{
    $requests = RetrieveMainVacationRequests();
    if ($requests != NULL) {
        foreach ($requests as $request) {
            $employee = RetrieveEmployeeByID($request[MAIN_VACATION_EMP_ID]);
            echo "<tr>";
            echo "<td>" . $employee[EMP_NAME] . "</td>";
            echo "<td>" . $request[MAIN_VACATION_1ST_START] . "</td>";
            echo "<td>" . $request[MAIN_VACATION_1ST_END] . "</td>";
            echo "<td>" . $request[MAIN_VACATION_2ND_START] . "</td>";
            echo "<td>" . $request[MAIN_VACATION_2ND_END] . "</td>";
            echo '<td> <button class="btn btn-success" type="submit" ' . 'name="amend"  value="' . $request[MAIN_VACATION_REQ_ID] . '">Amend</button></td>';
            echo '<td> <button class="btn btn-danger" type="submit" name="delete"' . ' value="' . $request[MAIN_VACATION_REQ_ID] . '">Delete</button></td>';