<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_EMPLOYEE_SHIFT_SCHEDULE';
if (!@$_GET['popup'])
    $path_to_root = "../..";
else	
    $path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/payroll/includes/db/employee_shifts_db.inc");
include_once($path_to_root . "/payroll/includes/db/employee_departments_db.inc");
include_once($path_to_root . "/payroll/includes/db/shifts_db.inc");

$js = '';
$js .= get_js_date_picker();
$js .= get_js_open_window(900, 500);

page(_($help_context = "Employee Shifts Schedule"));

simple_page_mode(true);

$status = true;

if (isset($_GET['employee_code'])) {
    $_POST['employee_code'] = $_GET['employee_code'];
}

function clear_employee_shits_data() {
    unset($_POST['id']);
    unset($_POST['shift_list_value_id']);
    unset($_POST['start_date']);
    unset($_POST['week_start_day']);
    unset($_POST['saturday_work_time_id']);
    unset($_POST['sunday_work_time_id']);
    unset($_POST['continuous_work']);
    unset($_POST['task_id']);
}

function check_data($selected_id) {	
    if (! isset($_POST['employee_code']) || strlen($_POST['employee_code']) < 1) {
        display_error( _("Please select an employee."));
        set_focus('employee_code');
        return false;
    }

    if (! is_date($_POST['start_date'])) {
        display_error( _("Start date entered is not a valid date."));
        set_focus('start_date');
        return false;
    }
    
    if (! ($_POST['shift_list_value_id'] > 0)) {
        display_error( _("Please select a shift."));
        set_focus('shift_list_value_id');
        return false;
    }  
    
    $result = get_defined_shifts_by_shift_list_value_id_and_date($_POST['shift_list_value_id'], $_POST['start_date']);
        if (! (db_num_rows($result) > 0)) {
            display_error( _("Selected shift not started on or before the selected start date."));
            set_focus('start_date');
            return false;
        }
        
    $row = get_employee_shifts_by_date($_POST['employee_code'], $_POST['start_date'], $selected_id);
        if (is_array($row)) {
            display_error( _("Can not have more than one shift on the same date."));
            set_focus('start_date');
            return false;
        }

    if (! isset($_POST['week_start_day']) || strlen($_POST['week_start_day']) < 1) {
        display_error( _("Please select week start day."));
        set_focus('employee_code');
        return false;
    }  
    
    return true;
}

function can_delete_employee_shift($selected_id) {	

//    $n = check_shift_in_employee_attendance($selected_id);
//    if ($n > 0) {
//        display_error( _("Selected record has been used in employee attendance. It can not be deleted."));
////        set_focus('start_date');
//        return false;
//    }
        
    return true;
}

function get_weekday_name($code) {
    switch ($code) {
        case "M":
            return "Monday";
        case "T":
            return "Tuesday";
        case "W":
            return "Wednesday";
        case "H":
            return "Thursday";
        case "F":
            return "Friday";
        case "S":
            return "Saturday";
        case "N":
            return "Sunday";
        default:
            return "Unknown day";
    }
}

//--------------------------------------------------------------------------------------------------

function get_weekend_work_time_name($code) {
    switch ($code) {
        case "0":
            return "Shift hours";
        case "1":
            return "4 hours";
        case "2":
            return "Half of shift hours";
        case "3":
            return "8 hours";
        case "4":
            return "Zero hours";
        case "5":
            return "5 hours";
        default:
            return "Unknown weekend work time";
    }
}

//--------------------------------------------------------------------------------------------------

if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && $status = check_data($selected_id)) {
    if ($Mode == 'ADD_ITEM') {
        add_employee_shift($_POST['employee_code'], date2sql($_POST['start_date']), $_POST['shift_list_value_id'], $_POST['week_start_day'],
                           $_POST['saturday_work_time_id'], $_POST['sunday_work_time_id'], $_POST['continuous_work'], $_POST['task_id']);

        display_notification(_("Employee shift has been added."));
    } 
    
    if ($Mode == 'UPDATE_ITEM') {
        update_employee_shift($selected_id, $_POST['employee_code'], date2sql($_POST['start_date']), $_POST['shift_list_value_id'], $_POST['week_start_day'],
                              $_POST['saturday_work_time_id'], $_POST['sunday_work_time_id'], $_POST['continuous_work'], $_POST['task_id']);

        display_notification(_("Employee shift #$selected_id has been updated."));
        $selected_ids = -1;
    }
    
    $Mode = 'RESET';
}

//--------------------------------------------------------------------------------------------------

if ($Mode == 'Delete') {
    if(can_delete_employee_shift($selected_id)){
        delete_employee_shift($selected_id);
        $Mode = 'RESET';
    }
}

if ($Mode == 'RESET') {
    $selected_id = -1;
    clear_employee_shits_data();
}

if (isset($_POST['_selected_id_update'])) {
    $selected_id = $_POST['selected_id'];
    $Ajax->activate('_page_body');
}

if (list_updated('employee_code')) {
    $Ajax->activate('price_table');
}

//--------------------------------------------------------------------------------------------------

if (!@$_GET['popup'])
    start_form();

        start_table(TABLESTYLE_NOBORDER);
            start_row();
                emoplyees_list_cells(_("Select an Employee:"), 'employee_code', null, false, true, check_value('show_inactive'));
                if (list_updated('employee_code')) {
                    $selected_id = -1;
                }
            end_row();
        end_table(1);

        $dep_result = get_all_employee_departments($_POST['employee_code']);

        div_start('price_table');
            display_heading("Emplyee Departments");
                start_table(TABLESTYLE, "width=60%");
                    $dep_th = array(_('Department'),_('Rate Category'), _("Start Date"), _("End date"));

                    table_header($dep_th);
                    if (db_num_rows($dep_result) == 0) {
                        end_table(1);
                        display_note(_("This employee is not attached to any department"));
                        br(2);
                    } else {
                            $k = $j = 0; //row colour counter
                            while ($myrow = db_fetch($dep_result)) {
                                alt_table_row_color($k);
                                    label_cell($myrow["department_name"]);
                                    label_cell($myrow["rate_category_name"]);
                                    label_cell($myrow["start_date"]);
                                    if ($myrow["end_date"] == INFINITE_END_DATE) {
                                        label_cell("");
                                    } else {
                                        label_cell(sql2date($myrow["end_date"]),"align=center");
                                    }
                                end_row();
                            }
                        end_table(2);
                    }
                    
        display_heading("Emplyee Shift Schedule");

            start_table(TABLESTYLE, "width=70%");

		$th = array(_("Id"), _("Start Date"), _("Shift"), _("Week Start Day"), _("Continuous Work"), _("6th Day Work Time"), _("7th Day Work Time"), _(""), _(""));
                table_header($th);
                
                    $result = get_employee_shifts($_POST['employee_code']);
                        if (db_num_rows($result) == 0) {
                            end_table(1);
                            display_note(_("There are no shifts defined for selected employee"));
                            br(2);
                        } else {
                                $k = $j = 0; //row colour counter
                                while ($myrow = db_fetch($result)) {
                                    alt_table_row_color($k);
                                        label_cell($myrow["id"], 'align=center');
                                        label_cell(sql2date($myrow["start_date"]));
                                        label_cell($myrow["shift_name"]);
                                        label_cell(get_weekday_name($myrow["week_start_day"]));

                                        if ($myrow["continuous_work"] == 1)
                                            label_cell("Yes", "align=center");
                                        else {
                                            label_cell("No", "align=center");
                                        }

                                        label_cell(get_weekend_work_time_name($myrow["saturday_work_time_id"]));
                                        label_cell(get_weekend_work_time_name($myrow["sunday_work_time_id"]));

                                        edit_button_cell("Edit".$myrow['id'], _("Edit"));
                                        delete_button_cell("Delete".$myrow['id'], _("Delete"));
                                    end_row();

                                    $j++;
                                    If ($j == 12) {
                                        $j = 1;
                                        table_header($th);
                                    } //end of page full new headings
                                } //end of while loop

                            end_table(2);
                        }
        div_end();

//-----------------------------------------------------------------------------------------------
    
if(! isset($_POST['id']) && $status === true) {
    $_POST['id'] = 0;
    $_POST['shift_list_value_id'] = "";
    $_POST['start_date'] = "";
    $_POST['week_start_day'] = "";
    $_POST['saturday_work_time_id'] = 0;
    $_POST['sunday_work_time_id'] = 0;
}

if(! isset($_POST['continuous_work'])) {
    $_POST['continuous_work'] = 0;
}
    
$dec2 = 6;
if ($Mode =='Edit' && $status === true) {
    $myrow = get_employee_shift_details($selected_id);

    $_POST['id'] = $myrow["id"];
    $_POST['shift_list_value_id'] = $myrow["shift_list_value_id"];
    $_POST['start_date'] = sql2date($myrow["start_date"]);
    $_POST['week_start_day'] = $myrow["week_start_day"];
    $_POST['saturday_work_time_id'] = $myrow["saturday_work_time_id"];
    $_POST['sunday_work_time_id'] = $myrow["sunday_work_time_id"];
    $_POST['continuous_work'] = $myrow["continuous_work"];
    $_POST['task_id'] = $myrow["task_id"];
    
    hidden('id', $_POST['id']); 
}

hidden('selected_id', $selected_id);
$_POST['task_id'] = 0;
hidden('task_id', 0);

start_table(TABLESTYLE2);
    if ($Mode!= 'Delete' && $selected_id > 0) {
        label_row('Id:', $selected_id);
    }
    date_row("Start Date:", "start_date", $_POST['start_date']);
    value_list_row('Shift:', 'shift_list_value_id', 'EMPLOYEE_SHIFTS', null);
    weekdays_list_row("Week Start Day:", "week_start_day", $_POST['week_start_day']);
    yesno_list_row("Continuous Work:", 'continuous_work', $_POST['continuous_work'], "Yes", "No", true);
    if ($_POST['continuous_work'] == 0) {
        weekend_work_time_list_row("6th day (Saturday) Work Time:", "saturday_work_time_id", $_POST['saturday_work_time_id']);
        weekend_work_time_list_row("7th day (Sunday) Work Time:", "sunday_work_time_id", $_POST['sunday_work_time_id']);
    } else {
        hidden('saturday_work_time_id', 0);
        hidden('sunday_work_time_id', 0);
    }
end_table(1);

submit_add_or_update_center($selected_id == -1, '', 'both');
br(2);

if (!@$_GET['popup']) {
    end_form();
    end_page(@$_GET['popup'], false, false);
}

?>