<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_EMPLOYEE_PROJECTS';

	$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/projects/includes/db/employee_projects_db.inc");
include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc"); 
include_once($path_to_root . "/payroll/includes/leave_calculation.inc"); 
include_once($path_to_root . "/payroll/includes/db/calendars_db.inc");  
include_once($path_to_root . "/payroll/includes/db/apply_leave_db.inc");  
include_once($path_to_root . "/projects/includes/db/project_boq_items_db.inc");
include_once($path_to_root . "/projects/includes/db/employee_project_work_db.inc"); 

$js = '';

if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
        $js .= get_js_date_picker();
}

page(_($help_context = "Employee Projects"), false, false, "", $js);

simple_page_mode(false);


$_POST['company_code'] = '';


function display_employee_projects($company_code, $employee_code)
{
    $result = get_employee_all_projects($company_code, $employee_code);

    start_table(TABLESTYLE, "width=95%");
    $th = array(_("Rec. Id"), _("Start Date"), _("End Date"), _('Project'), _('Project BOQ Item'), _("Calendar Working Days"), _("Days Assigned"), _("Factor"), 
                _("Days Worked"), "", "");
    //inactive_control_column($th);

    table_header($th);
    $k = 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"]), "align=center");
        
        if(substr($myrow["end_date"], 0, 4) == '3000'){
            label_cell("");
        }
        else{
            label_cell(sql2date($myrow["end_date"]), "align=center");
        }
        label_cell($myrow["project_description"]);
        label_cell($myrow["boq_item_code"]." - ".$myrow["boq_item_name"]);
        label_cell($myrow["calendar_working_days"], 'align=right');
        label_cell($myrow["days_per_month"], 'align=right');
        label_cell($myrow["factor"], 'align=right');
        label_cell($myrow["days_worked"], 'align=right');
        
        edit_button_cell("Edit".$myrow["id"], _("Edit"));

        delete_button_cell("Delete".$myrow["id"], _("Delete"));

        end_row();
    }

    //inactive_control_row($th);
    end_table(1);
}


function display_employee_projects_edit_controls($selected_id, $Mode)
{
    start_table(TABLESTYLE2);


    if ($Mode == 'Edit') {
        //editing an existing item category

        $myrow = get_employee_project($selected_id);
        
        $_POST['project_id'] = $myrow["project_id"];
        $_POST['boq_item_id']  = $myrow["boq_item_id"];
        $_POST['days_per_month']  = $myrow["days_per_month"];
        $_POST['end_date'] = sql2date($myrow["end_date"]);
        hidden('project_id', $myrow["project_id"]);
        hidden('boq_item_id', $myrow["boq_item_id"]);
    }
    else{
        $selected_id = -1;
    }

    hidden('selected_id', $selected_id);

        if (! ($selected_id > 0)) {
            project_list_row("Project", 'project_id', null, 'Select a project', true);

                if ($_POST['project_id'] > 0) {
                    $project_row = get_project_record($_POST['project_id']);
                        if (! isset($_POST['start_date']) || list_updated('project_id')) {
                            $_POST['start_date'] = sql2date($project_row['start_date']);
                        }
                        if (! isset($_POST['end_date']) || list_updated('project_id')) {
                            $_POST['end_date'] = sql2date($project_row['end_date']);
                        }
                }

            project_boq_items_list_cells("Boq Items:", 'boq_item_id', $_POST['project_id'], null, '');
        } else {
            label_row('Record Id:', $selected_id);
            label_row('Project:', get_project_formatted_name($_POST['project_id']));
            $boq_row = get_project_boq_item_record($_POST['boq_item_id']);
                if (isset($boq_row['id']) && $boq_row['id'] > 0) {
                    label_row('Boq Items:', $boq_row['code']." - ".$boq_row['description']);
                } else {
                    label_row('Boq Items:', '');
                }
        }

        date_row(_('Start Date:'), 'start_date'); 
        date_row(_('End Date:'), 'end_date'); 
        qty_row("Days Assigned:", 'days_per_month', null, null, null, 0);
      
    end_table(1);

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

function can_commint_employee_project($selected_id, &$calendar_working_days)
{
    if(! (strlen($_POST['employee_code']) > 0)) {
        display_error(_("Select an employee."));
        set_focus('employee_code');  
        return false;
    }
	
    if(!($_POST['project_id'] > 0))
    {
        display_error(_("Select a project."));
        set_focus('project');  
        return false;
    }

    if(!($_POST['boq_item_id'] > 0))
    {
        display_error(_("Select a BOQ item."));
        set_focus('boq_item_id');  
        return false;
    }
	
    if (!is_date($_POST['start_date']))
    {
        display_error( _("The start date entered is invalid."));
        set_focus('start_date');
        return false;
    }
    
    if (!is_date($_POST['end_date']))
    {
        display_error( _("The end date entered is invalid."));
        set_focus('start_date');
        return false;
    }
    
    if (date1_greater_date2($_POST['start_date'], $_POST['end_date']))
    {
        display_error( _("End date can not be before the end date."));
        set_focus('end_date');
        return false;
    }
    
    $start_date = date2sql($_POST['start_date']);
    $end_date = date2sql($_POST['end_date']);
    
    // check dates overlapping with old records
    $row = get_employee_projects_by_from_and_date_dates($start_date, $end_date, $_POST['employee_code'], $_POST['project_id'], $_POST['boq_item_id'], $selected_id, true);
        if (isset($row['id']) && $row['id']) {
            $id = $row['id'];
            display_error( _("Entered dates are overlapping with record #$id."));
            set_focus('start_date');
            return false;
        }
    
    if(!check_num('days_per_month', 0.1))
    {
        display_error( _("Days assigned should be grater than zero."));
        set_focus('days_per_month');
        return false;
    }
    
    $days_assigned = input_num('days_per_month');
    $leave_details = calculate_leave($start_date, 'F', $end_date, 'F', false, false);
        
        $calendar_working_days = 0.0;
        foreach($leave_details as $day_leave) {
            $calendar_working_days += $day_leave[1];
        }
        
    if ($days_assigned > $calendar_working_days) {
        display_error( _("Entered days assigned is bigger than available calendar working days $calendar_working_days."));
        set_focus('days_per_month');
        return false;
    } 

        return true;
}

if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM')) {
    $can_save = can_commint_employee_project($selected_id, $calendar_working_days);
        if ($can_save === true) {
            
            $factor = input_num('days_per_month') / $calendar_working_days;
    
            if($Mode ==  'UPDATE_ITEM'){
                update_employee_project($selected_id, $_POST['start_date'], $_POST['end_date'], input_num('days_per_month'), $calendar_working_days, $factor);
                display_notification(_('Selected employee project has been updated'));
            }
            else
            {
                add_employee_project($_POST['company_code'], $_POST['employee_code'], $_POST['project_id'], $_POST['boq_item_id'],
                                $_POST['start_date'], $_POST['end_date'], input_num('days_per_month'), $calendar_working_days, $factor);

                display_notification(_('New employee project has been added'));
            }    
    
            $selected = -1;
            $Mode = 'RESET';
        } else {
            if ($selected_id > 0) {
                $Mode = 'Edit';
            }
        }
}

function can_delete_employee_project($selected_id) {
    $row = get_employee_project($selected_id);
        if (! (isset($row['id']) && $row['id'] > 0)) {
            return array('success' => false, "message" => "Selected record #$selected_id is already deleted by another person.");
        }
    
    $epw_row = get_employee_project_works_by_filters(employee_project_id: $selected_id, fetch: true);
        if (isset($epw_row['id']) && $epw_row['id'] > 0) {
            $emp_pw_id = $epw_row['id'];
            return array('success' => false, "message" => "Cannot delete record #$selected_id. It has employee project work record #$emp_pw_id.");
        }
        
        return array('success' => true, "message" => "");
}

if ($Mode == 'Delete') {
    $msg = can_delete_employee_project($selected_id);
        if ($msg['success'] === false) {
            display_error($msg['message']);
        } else {
            $af_row = delete_employee_project($selected_id);
                if ($af_row != 1) {
                    display_error("Could not delete employee project record #$selected_id");
                } else {
                    display_notification(_('Selected employee project has been deleted'));
                }
        }
        
    $Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
	$sav = get_post('show_inactive');
	//unset($_POST);
	$_POST['show_inactive'] = $sav;
}

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

global $Ajax;

start_form();

start_table(TABLESTYLE_NOBORDER);

//    group_companies_list_row("Company:", 'company_code', null, false, true);
    
    group_company_employees_simple_list_cells(_("Employee:"), 'employee_code', $_POST['company_code'], null, '', true);
    submit_cells('Refresh', 'Refresh');

end_table(1);

$Ajax->activate('emp_proj');
div_start('emp_proj');
    display_employee_projects($_POST['company_code'], $_POST['employee_code']);

    display_employee_projects_edit_controls($selected_id, $Mode);
div_end();


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

?>
