<?php

function job_activities($jo_id, $width=80) {
    global $Ajax, $path_to_root, $systypes_array;
    
    $Ajax->activate('job_activity');
    div_start('job_activity');
    
        view_job_activity_details_by_jo_id($jo_id, $width);
        
        start_table();
            if ($jo_id > 0) {
                hyperlink_params_separate($path_to_root . "/services/job_activities.php", 'Create a New '.$systypes_array[ST_JOB_ACTIVITY], "jo_id=$jo_id");
            }
        end_table();
        
    div_end();
}

function display_job_activity_details($jo_id, $selected_id, &$Mode, $state=true) {
    global $systypes_array;
    
    $type = ST_JOB_ACTIVITY;
    $trn_type_name = $systypes_array[$type];
    
    display_heading("$trn_type_name Details");    

	start_table(TABLESTYLE, "width=95%");
        
            $th = array(_("Id"), _("Activity Type"), _("Activity Date"), _("Description"), _("Attachments"), _("Created By"), _("Created On"), _("Updated By"), 
                        _("Updated On"), _(""), _(""));
            table_header($th);
            
            $k = 0;  
            $result = get_job_activity_details($jo_id);
            $rec_count = db_num_rows($result);
                while ($row = db_fetch($result)) {
                    $id = $row['id'];
                    
                    if ($selected_id != $id || $Mode == 'Delete') {
                        alt_table_row_color($k);

                            label_cell($id, 'align=center');
                            label_cell($row['activity_type_name']);
                            label_cell(sql2date($row['act_date']));
                            label_cell(nl2br($row['description']));
                            $link = "admin/attachments_wms.php?type=$type&trans_no=$id";
                            label_cell(viewer_link('', $link, '', '',  ICON_DOWN), 'align=center');
                            label_cell($row['real_name']);
                            label_cell($row['created_on']);
                            label_cell($row['updated_user']);
                            if ($row['updated_on'] != INFINITE_START_DATE.' 00:00:00') {
                                label_cell($row['updated_on'], 'align=center');
                            } else {
                                label_cell('');
                            }
                            
                            if ($row['editable'] == 1 && $rec_count == 1) {
                                edit_button_cell("Edit".$id, _("Edit"));
                                delete_button_cell("Delete".$id, _("Delete"));
                            } else {
                                label_cell(''); label_cell('');
                            }

                        end_row();
                    
                    } else {
                        display_job_activity_controls($Mode, $selected_id, $jo_id, $state);
                    }
                    
                    $rec_count--;
                }
                
                if (! ($selected_id > 0) || $Mode == 'Delete') {
                    display_job_activity_controls($Mode, $selected_id, $jo_id, $state);
                }

    end_table(2);
}

function create_job_activity_types_array($skip=true) {
    $job_act_tps_array = array();
    
        $result = get_all_list_values('JOB_ACTIVITY_TYPES');
            while ($row = db_fetch($result)) {
                if ($skip === true && in_array($row['value_code'], array('JOB_COMPLETE', 'JOB_ACCEPTANCE', 'NEXT_JOB_OWNER', 'CUSTOMER_COMPLAIN'))) {
                    continue;
                }
                
                $job_act_tps_array[$row['id']] = $row['value_name'];
            }
            
            return $job_act_tps_array;
}

function display_job_activity_controls(&$Mode, &$selected_id, $jo_id, $state=true) {
    global $Ajax;
    
    echo "<td colspan=9>";
        $Ajax->activate('job_activity_control');
        div_start('job_activity_control');

            start_outer_table(TABLESTYLE2);
                if ($jo_id > 0 && $Mode != 'Delete' && $selected_id > 0 && $state === true) {
                    $row = get_job_activity_record($selected_id);
                        if (is_array($row)) {
                            $_POST['activity_type'] = $row['activity_type'];
                            $_POST['description'] = $row['description'];
                            $_POST['act_date'] = sql2date($row['act_date']);
                        }

                    hidden('selected_id', $selected_id);
                }

                table_section(1);

                    if ($selected_id > 0 && $Mode != 'Delete') {
                        label_row('Line #:', $selected_id);
                    }
                    custom_values_list_row('Activity Type:', 'activity_type', create_job_activity_types_array(), null, '');
                    date_row('Activity Date:', 'act_date');
                    
                table_section(2);
                
                    textarea_row('Description:', 'description', null, 40, 2);
                    
            end_outer_table(1);
            
        div_end();
    echo "</td>";
    
        if ($jo_id > 0 && $selected_id > 0 && $Mode != 'Delete') {
            button_cell('UPDATE_JO_ACTIVITY', _("Update Job Activity"), _('Confirm changes'), ICON_UPDATE);
            hidden('selected_id', $selected_id);

        } elseif ($jo_id > 0) {        
            button_cell('ADD_JO_ACTIVITY', _("Add Job Activity"), _('Confirm changes'), ICON_ADD);
        }

        button_cell("CLEAR_DATA", 'Clear', 'Clear entered data', ICON_CANCEL);
}

function can_save_job_activity($jo_id, &$selected_id) {  
    global $systypes_array;
    
    $jo_row = get_job_order_project_id($jo_id);
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($jo_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    $trn_type_name = $systypes_array[ST_JOB_ACTIVITY];
    
    $jo_hd_row = get_job_order_record($jo_id);
        if (! is_array($jo_hd_row)) {
            return array('success' => false, 'message' => "Could not find ".$systypes_array[ST_JOB_ORDER]." #$jo_id.");
        } else {
            if ($jo_hd_row['closed'] == 1) {
                return array('success' => false, 'message' => "Job card #$jo_id is already closed. Not allow to further update.");
            }
        }
    
    if ($selected_id > 0) {
        $row = get_job_activity_record($selected_id);
            if (! is_array($row)) {
                return array('success' => false, 'message' => "Another user has deleted $trn_type_name record #$selected_id.");
            }
            
        $user_id = $_SESSION['wa_current_user']->user;
        if ($user_id != $row['created_by']) {
            return array('success' => false, 'message' => "Only allow to edit record #$selected_id its creator.");
        }
            
        if ($row['editable'] != 1) {
            return array('success' => false, 'message' => "Record #$selected_id is a non editable record.");
        }    
            
        $last_row = check_job_activity_is_last_entered_record($jo_id, $selected_id);
            if (is_array($last_row)) {
                return array('success' => false, 'message' => "Record #$selected_id is not the last one. Only the last record can be edited.");
            }
            
        hidden('selected_id', $selected_id);
    }
      
    if (! isset($_POST['activity_type']) || ! ($_POST['activity_type'] > 0)) {
        return array("success" => false, "focus_to" => 'activity_type', "message" => "Activity type cannot empty. Please select an activity type.");        
    }
    
    if (! is_date($_POST['act_date'])) {
        return array("success" => false, "focus_to" => 'act_date', "message" => "Activity date is not a valid date.");        
    }
    
    if (! isset($_POST['description']) || ! (strlen($_POST['description']) > 0)) {
        return array("success" => false, "focus_to" => 'description', "message" => "Description cannot empty. Please enter description.");        
    }
        
    return array("success" => true, "message" => "", "focus_to" => '', 'row_state' => $jo_hd_row['row_state']);    
}

function handle_save_job_activity($jo_id, &$selected_id) {
    global $systypes_array;
    
    $trn_type_name = $systypes_array[ST_JOB_ACTIVITY];
    
    $msg = can_save_job_activity($jo_id, $selected_id);   
        if ($msg['success'] === false) {
            return $msg;
        }
        
        $row_state = $msg['row_state'];
        
    begin_transaction();   

        if ($selected_id > 0) {
            $msg = update_job_activity($jo_id, $selected_id, $row_state, $_POST['activity_type'], $_POST['act_date'], $_POST['description']);
                if ($msg['success'] === false) {
                    cancel_transaction();
                    
                    return $msg;
                } else {
                    commit_transaction();
                    
                    return array('success' => true, 'message' => "$trn_type_name record #$selected_id has been updated.");
                }
        } else {
            $msg = add_job_activity($jo_id, $row_state, $_POST['activity_type'], $_POST['act_date'], $_POST['description'], true, '', -1, 0);
                if ($msg['success'] === false) {
                    cancel_transaction();
                    
                    return $msg;
                } else {
                    commit_transaction();
                    
                    return array('success' => true, 'message' => "New $trn_type_name record #".$msg['id']." has been added.");
                }
        }
}

function can_delete_job_activity($jo_id, &$selected_id) { 
    global $systypes_array, $path_to_root;
    
    include_once($path_to_root."/admin/db/attachments_db_wms.inc"); 
    
    $trn_type_name = $systypes_array[ST_JOB_ACTIVITY];
    
    $jo_hd_row = get_job_order_record($jo_id);
        if (is_array($jo_hd_row)) {
            if ($jo_hd_row['closed'] == 1) {
                return array('success' => false, 'message' => "Job card #$jo_id is already closed. Not allow to further update.");
            }
        }
        
    if ($selected_id > 0) {
        $row = get_job_activity_record($selected_id);
            if (! is_array($row)) {
                return array('success' => false, 'message' => "Another user has deleted $trn_type_name record #$selected_id.");
            }
            
        $user_id = $_SESSION['wa_current_user']->user;
        if ($user_id != $row['created_by']) {
            return array('success' => false, 'message' => "Only allow to delete record #$selected_id its creator.");
        }
            
        if ($row['editable'] != 1) {
            return array('success' => false, 'message' => "Record #$selected_id is a non editable record.");
        } 
            
    // check record has some attachments
    $att_recs = get_attachments_by_filters(0, ST_JOB_ACTIVITY, $selected_id);
            
        $last_row = check_job_activity_is_last_entered_record($jo_id, $selected_id);
            if (is_array($last_row)) {
                return array('success' => false, 'message' => "Record #$selected_id is not the last one. Only the last record can be deleted.");
            }
            
        if (db_num_rows($att_recs)) {
            return array('success' => false, 'message' => "Please delete all attachments related to $trn_type_name record #$selected_id.");
        }
            
        hidden('selected_id', $selected_id);
    }

    return array("success" => true, "message" => "", "focus_to" => '');    
}

function handle_delete_job_activity($jo_id, &$selected_id) {
    global $systypes_array;
    
    $trn_type_name = $systypes_array[ST_JOB_ACTIVITY];
    
    $msg = can_delete_job_activity($jo_id, $selected_id);   
        if ($msg['success'] === false) {
            return $msg;
        }
        
        $del_msg = delete_job_activity($selected_id);
            if ($del_msg != 1) {
                return array('success' => true, 'message' => "Could not delete $trn_type_name record #$selected_id.");
            } else {
                return array('success' => true, 'message' => "$trn_type_name record #$selected_id has been deleted.");
            }
}

function clear_job_activity_inputs(&$selected_id) {
    $input_array = array('description', 'stock_id', 'employee_code', 'num_days_worked');
    
        foreach ($input_array as $input) {
            unset($_POST["$input"]);
        }
        
        $_POST["from_date"] = $_POST["to_date"] = $_POST["act_date"] = Today();

        $selected_id = -1;
        unset($_POST['selected_id']);
        hidden('selected_id', -1);
}

function view_job_activity_details_by_jo_id($jo_id, $width=70) {
    global $systypes_array;
    
    $jo_row = get_job_order_project_id($jo_id);
        if (isset($jo_row['project_id']) && $jo_row['project_id'] > 0) {
            $user_id = $_SESSION['wa_current_user']->user;
            $cap = can_access_project($jo_row['project_id'], $user_id);
                if ($cap['success'] !== true) {
                    display_error($cap["message"]);
                    display_footer_exit();
                    exit;
                }
        } else {
            return;
        }
    
    $type = ST_JOB_ACTIVITY;
    display_heading2("$systypes_array[$type] Details");    br();

	start_table(TABLESTYLE, "width=$width%");
        
            $th = array(_("Id"), _("Activity Type"), _("Activity Date"), _("Description"), _("Attachments"), _("Created By"), _("Created On"), _("Updated By"), 
                        _("Updated On"));
            table_header($th);
            
            $k = 0;  
            
            $result = get_job_activity_details($jo_id, true);
                while ($row = db_fetch($result)) {
                    $id = $row['id'];
                    alt_table_row_color($k);

			label_cell($row['id'], 'align=center');
			label_cell($row['activity_type_name']);
			label_cell(sql2date($row['act_date']));
			label_cell(nl2br($row['description']));
                        if ($row['attach_id'] > 0) {
                            label_cell(viewer_link('', "admin/view_attachments.php?type=$type&trans_no=$id", '', '',  ICON_DOWN), 'align=center');
                        } else {
                            label_cell('');
                        }
                        label_cell($row['real_name']);
                        label_cell($row['created_on'], 'align=center');
                        label_cell($row['updated_user']);
                        if ($row['updated_on'] != INFINITE_START_DATE.' 00:00:00') {
                            label_cell($row['updated_on'], 'align=center');
                        } else {
                            label_cell('');
                        }
                        
                    end_row();
            }

        end_table(2);
}

function save_job_activity_log($jo_id, $activity_type, $text='', $row_state=0, $editable=0, $p_jo_id=0, $p_row_state=0, $next_job_owner_id='', $type=-1, $trans_no=0) {
    $activity_type_id = 0;
    
    $jat_row = get_listvalue_by_code('JOB_ACTIVITY_TYPES', $activity_type);
        if (is_array($jat_row)) {
            $activity_type_id = $jat_row['id'];
        }

            if ($activity_type == 'SUB_JOB') {
                $msg = add_job_activity($p_jo_id, $p_row_state, $activity_type_id, Today(), $text, $editable, $next_job_owner_id, $type, $trans_no);
            } else {
                $msg = add_job_activity($jo_id, $row_state, $activity_type_id, Today(), $text, $editable, $next_job_owner_id, $type, $trans_no);
            }
            
                if ($msg['success'] === false) {
                    return $msg;    
                } 

            return array("success" => true, "message" => "");    
}

function display_job_activities_inquiry($jo_id, $activity_type, $from_date_, $to_date_) {
    global $Ajax;
    
    $type = ST_JOB_ACTIVITY;

    $Ajax->activate('job_activities_inquiry');
    div_start('job_activities_inquiry');
	start_table(TABLESTYLE, "width=95%");
        
            $th = array(_("Id"), _("Job Card"), _("Activity Type"), _("Activity Date"), _("Description"), _("Attachments"), _("Created By"), _("Created On"), _("Updated By"), 
                        _("Updated On"));
            table_header($th);
            
            $k = 0;  
            
            $result = get_job_activities_details_with_attachment_by_filters(0, $jo_id, $activity_type, $from_date_, $to_date_);
                while ($row = db_fetch($result)) {
                    $id = $row['id'];
                    alt_table_row_color($k);

			label_cell($id, 'align=center');
                        $jo_id = $row["jo_id"];
                        label_cell(get_service_trans_view_str(ST_JOB_ORDER, $jo_id), 'align=center');
			label_cell($row['activity_type_name']);
			label_cell(sql2date($row['act_date']));
			label_cell(nl2br($row['description']));
                        if ($row['attach_id'] > 0) {
                            $link = "admin/view_attachments.php?type=$type&trans_no=$id";
                            label_cell(viewer_link('', $link, '', '',  ICON_DOWN), 'align=center');
                        } else {
                            label_cell('');
                        }
                        label_cell($row['real_name']);
                        label_cell($row['created_on'], 'align=center');
                        label_cell($row['updated_user']);
                        if ($row['updated_on'] != INFINITE_START_DATE.' 00:00:00') {
                            label_cell($row['updated_on'], 'align=center');
                        } else {
                            label_cell('');
                        }
                        
                    end_row();
            }

        end_table(2);
    div_end();
}

?>