function CreateEmployeeSelect()
{
    echo '<select class="form-control" name="employeeID" id="employeeID" >';
    $employees = RetrieveEmployees();
    if ($employees != NULL) {
        foreach ($employees as $employee) {
            echo '<option value="' . $employee[EMP_ID] . '">' . $employee[EMP_NAME] . '</option>';
        }
    }
    echo '</select>';
}
function GenerateEmployeeSelect($request)
{
    $employees = RetrieveEmployees();
    if ($employees != NULL) {
        echo '<select class="form-control" name="employeeID">';
        foreach ($employees as $Employee) {
            if ($Employee[EMP_ID] == $request[APPR_ABS_EMPLOYEE_ID]) {
                echo '<option selected="selected" ' . 'value="' . $Employee[EMP_ID] . '">' . $Employee[EMP_NAME] . '</option>';
            } else {
                echo '<option value="' . $Employee[EMP_ID] . '">' . $Employee[EMP_NAME] . '</option>';
            }
        }
        echo '</select>';
    }
}
function DisplayEmployeeTableBody()
{
    $employees = RetrieveEmployees();
    if ($employees != NULL) {
        foreach ($employees as $employee) {
            $role = RetrieveCompanyRoleByID($employee[EMP_COMPANY_ROLE]);
            echo "<tr>";
            echo "<td>" . $employee[EMP_ID] . "</td>";
            echo "<td>" . $employee[EMP_NAME] . "</td>";
            echo "<td>" . $employee[EMP_EMAIL] . "</td>";
            echo "<td>" . $employee[EMP_DATEJOINED] . "</td>";
            echo "<td>" . $employee[EMP_LEAVE_ENTITLEMENT] . "</td>";
            echo "<td>" . $role[COMP_ROLE_NAME] . "</td>";
            echo "<td>" . $employee[EMP_MAIN_VACATION_REQ_ID] . "</td>";
            echo "<td>" . $employee[EMP_ADMIN_PERM] . "</td>";
            echo "<td>" . $employee[EMP_MANAGER_PERM] . "</td>";
            echo '<td> <button type="submit" class="btn btn-success" ' . 'name="amend" id="amend"  value="' . $employee[EMP_ID] . '">Amend</button></td>';
            echo '<td> <button type="submit" class="btn btn-danger" ' . 'name="delete" id="delete" value="' . $employee[EMP_ID] . '">Delete</button></td>';
            echo "</tr>";
        }
    }
}
function SendShortfallAlertToOfficeManager($employeeID, $startDate, $endDate, $absenceTypeID)
{
    $employee = RetrieveEmployeeByID($employeeID);
    $employeeName = $employee[EMP_NAME];
    $absenceType = RetrieveAbsenceTypeByID($absenceTypeID);
    $absenceName = $absenceType[ABS_TYPE_NAME];
    $role = RetrieveCompanyRoleByID($employee[EMP_COMPANY_ROLE]);
    $roleName = $role[COMP_ROLE_NAME];
    $minimumStaff = $role[COMP_ROLE_MIN_STAFF];
    $from = "*****@*****.**";
    $subject = "URGENT: STAFF SHORTFALL";
    $message = "Between {$startDate} and {$endDate} the number of staff performing the " . "role of {$roleName} will be below {$minimumStaff}." . "This is due to {$employeeName} being absent with {$absenceName}.";
    $filter[EMP_MANAGER_PERM] = 1;
    $managers = RetrieveEmployees($filter);
    $success = TRUE;
    foreach ($managers as $manager) {
        if (!mail($manager[EMP_EMAIL], $subject, $message)) {
            $success = FALSE;
        }
    }
    return $success;
}
function SufficentStaffInRoleToGrantRequest($employeeID, $startDate, $endDate)
{
    $sufficentStaffInRole = TRUE;
    // Get the employee record from the database.
    $Employee = RetrieveEmployeeByID($employeeID);
    if ($Employee != NULL) {
        // Get the associated Company Role record from the database.
        $employeeRole = RetrieveCompanyRoleByID($Employee[EMP_COMPANY_ROLE]);
        if ($employeeRole != NULL) {
            $minimumStaffingLevel = $employeeRole[COMP_ROLE_MIN_STAFF];
            //Calculate the total number of employees in this role.
            $filter[EMP_COMPANY_ROLE] = $Employee[EMP_COMPANY_ROLE];
            $employeesInRole = RetrieveEmployees($filter);
            $numEmployeesInRole = count($employeesInRole);
            //Check staffing levels for each day in the period requested.
            $tempDate = strtotime($startDate);
            $endTime = strtotime($endDate);
            $underMinimumStaffing = FALSE;
            while ($tempDate <= $endTime and $underMinimumStaffing == FALSE) {
                // 2010-05-01, 2010-05-02, etc
                $strDate = date('Y-m-d', $tempDate);
                //Calculate the number of staff in this role that are on leave
                //on this date.
                $staffOnLeave = CountStaffOnLeave($Employee[EMP_COMPANY_ROLE], $strDate);
                //Q.Would granting this leave would take us below the minimum
                //staffing level for the role.
                $availableStaff = $numEmployeesInRole - $staffOnLeave;
                if ($availableStaff <= $minimumStaffingLevel) {
                    //Y.Granting the request would take us below the minimum
                    //staffing level for the role.
                    $underMinimumStaffing = TRUE;
                    $sufficentStaffInRole = FALSE;
                }
                //move temp date onto the next day. Note tempdate is in seconds.
                //86400 = 60 seconds * 60 minutes * 24 hours.
                $tempDate = $tempDate + 86400;
            }
        } else {
            error_log("Unknown company role identifier of " . $employee[EMP_COMPANY_ROLE]);
        }
    } else {
        error_log("Unknown employee identifier of {$employeeID}");
    }
    return $sufficentStaffInRole;
}
function CreateEmployee($employeeName, $emailAddress, $password, $dateJoinedTheCompany, $annualLeaveEntitlement, $mainVacationRequestID, $companyRoleID, $isAdministrator = 0, $isManager = 0)
{
    $statusMessage = "";
    $employee = NULL;
    //--------------------------------------------------------------------------
    // Validate Input parameters
    //--------------------------------------------------------------------------
    $inputIsValid = TRUE;
    if (isNullOrEmptyString($employeeName)) {
        $statusMessage .= "Employee Name can not be blank.<br/>";
        error_log("Invalid employeeName passed to CreateEmployee.");
        $inputIsValid = FALSE;
    }
    if (!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
        $statusMessage .= "Email address given is not a valid email format.<br/>";
        error_log("Invalid email address passed to CreateEmployee.");
        $inputIsValid = FALSE;
    }
    $errorArray = isValidPassword($password);
    if (count($errorArray) != 0) {
        foreach ($errorArray as $key => $value) {
            $statusMessage .= $value . "<br/>";
            error_log($value);
        }
        $inputIsValid = FALSE;
    }
    if (!isValidDate($dateJoinedTheCompany)) {
        $statusMessage .= "Value given for Date joined the company is not a " . "valid date.<br/>";
        error_log("Invalid dateJoinedTheCompany passed to CreateEmployee.");
        $inputIsValid = FALSE;
    }
    //------------------------------------------------------------------------
    // Need to check for extreme values for 'date joined the company'
    // Don't allow records to be created if date joined is more than a month
    // in the future, or more than 50 years in the past.
    //------------------------------------------------------------------------
    if (isValidDate($dateJoinedTheCompany)) {
        $now = time();
        $input_date = strtotime($dateJoinedTheCompany);
        $diff_date = $now - $input_date;
        $daysSinceJoiningCompany = floor($diff_date / (60 * 60 * 24));
        if ($daysSinceJoiningCompany > 365 * 50) {
            $statusMessage .= "Value given for Date joined the company can not be " . "more than 50 years in the past.<br/>";
            error_log("Invalid dateJoinedTheCompany passed to CreateEmployee.");
            $inputIsValid = FALSE;
        }
        if ($daysSinceJoiningCompany < -30) {
            $statusMessage .= "Value given for Date joined the company can not " . "be more than 30 days in the future.<br/>";
            error_log("Invalid dateJoinedTheCompany passed to CreateEmployee.");
            $inputIsValid = FALSE;
        }
    }
    if (!is_numeric($annualLeaveEntitlement)) {
        $statusMessage .= "Please enter a valid value for annual leave " . "entitlement.<br/>";
        error_log("Invalid annualLeaveEntitlement passed to CreateEmployee.");
        $inputIsValid = FALSE;
    }
    if ($mainVacationRequestID != NULL) {
        $record = RetrieveMainVacationRequestByID($mainVacationRequestID);
        if ($record == NULL) {
            $statusMessage .= "Main Vacation Request ID does not exist in the " . "database.<br/>";
            error_log("Invalid mainVacationRequestID passed to CreateEmployee.");
            $inputIsValid = FALSE;
        }
    }
    $record = RetrieveCompanyRoleByID($companyRoleID);
    if ($record == NULL) {
        $statusMessage .= "Company Role ID does not exist in the database.<br/>";
        error_log("Invalid companyRoleID passed to CreateEmployee.");
        $inputIsValid = FALSE;
    }
    //Ensure email address doesn't already exist in the database.
    $filter[EMP_EMAIL] = $emailAddress;
    $result = RetrieveEmployees($filter);
    if ($result != NULL) {
        $statusMessage .= "Unable to create record as a user with email address " . "{$emailAddress} already exists.<br/>";
        error_log("Unable to create record as a user with email address " . "{$emailAddress} already exists");
        $inputIsValid = FALSE;
    }
    //--------------------------------------------------------------------------
    // Only attempt to insert a record in the database if the input parameters
    // are ok.
    //--------------------------------------------------------------------------
    if ($inputIsValid) {
        // Create an array with each field required in the record.
        $employee[EMP_ID] = NULL;
        $employee[EMP_NAME] = $employeeName;
        $employee[EMP_EMAIL] = $emailAddress;
        $encryptedPassword = md5(md5($emailAddress) . $password);
        $employee[EMP_PASSWORD] = $encryptedPassword;
        $employee[EMP_DATEJOINED] = $dateJoinedTheCompany;
        $employee[EMP_LEAVE_ENTITLEMENT] = $annualLeaveEntitlement;
        $employee[EMP_MAIN_VACATION_REQ_ID] = $mainVacationRequestID;
        $employee[EMP_COMPANY_ROLE] = $companyRoleID;
        $employee[EMP_ADMIN_PERM] = $isAdministrator;
        $employee[EMP_MANAGER_PERM] = $isManager;
        $success = sqlInsertEmployee($employee);
        if (!$success) {
            $statusMessage .= "Unexpected error when inserting the record to " . "the database.<br/>";
            error_log("Failed to create Employee. " . print_r($employee));
            $employee = NULL;
            $inputIsValid = false;
        } else {
            $statusMessage = "Record Created Successfully.";
        }
    }
    GenerateStatus($inputIsValid, $statusMessage);
    return $employee;
}
function DeleteCompanyRole($ID)
{
    $statusMessage = "";
    $result = 0;
    $record = RetrieveCompanyRoleByID($ID);
    if ($record != NULL) {
        $filter[EMP_COMPANY_ROLE] = $ID;
        $employees = RetrieveEmployees($filter);
        if ($employees != NULL) {
            foreach ($employees as $employee) {
                DeleteEmployee($employee[EMP_ID]);
            }
        }
        $sql = "DELETE FROM companyroletable WHERE companyRoleID=" . $ID . ";";
        $result = performSQL($sql);
        $statusMessage = "Role Deleted.</br>";
        GenerateStatus(true, $statusMessage);
    }
    return $result;
}
include 'sessionmanagement.php';
if (!isset($_SESSION['StatusDiv'])) {
    $_SESSION['StatusDiv'] = "";
}
if (isset($_POST["submit"])) {
    ClearStatus();
    $email = $_POST["inputEmail"];
    $password = $_POST["inputPassword"];
    if ($email == "") {
        GenerateStatus(false, "You must enter an email address.");
    } else {
        if ($password == "") {
            GenerateStatus(false, "You must enter a password.");
        } else {
            $filter[EMP_EMAIL] = $email;
            $employees = RetrieveEmployees($filter);
            if (count($employees) != 1) {
                GenerateStatus(false, "No matching email address found.");
            } else {
                $encryptedPassword = $employees[0][EMP_PASSWORD];
                $temp = md5(md5($email) . $password);
                if ($temp == $encryptedPassword) {
                    $_SESSION['userID'] = $employees[0][EMP_ID];
                    $_SESSION['administrator'] = $employees[0][EMP_ADMIN_PERM];
                    $_SESSION['manager'] = $employees[0][EMP_MANAGER_PERM];
                    header('Location: index.php');
                } else {
                    GenerateStatus(false, "Password is incorrect.");
                }
            }
        }