<?php 

function display_employee_attendance_details($date_, $status) {   
    global $Ajax;
    
    $date = date2sql($date_);
    
    display_heading("Employees' Attendance On ".date("l", strtotime(date2sql($date_))));

        start_table(TABLESTYLE, "width=98%");
            $th = array(_("Rec Id"), _("Employee"), _("Shift"), _("Shift Start Time (24h)"), _("Shift End Time (24h)"), _("In Time (24h)"), _("Out Time (24h)"), 
                        _('Deficit Time'), _('Comment'), _(''));

            table_header($th);

                $def_in_time = get_module_parameter_value('payroll', 'from_time1');
                $def_out_time = get_module_parameter_value('payroll', 'to_time1');
                $def_shift_id_ = get_module_parameter_value('payroll', 'shift_id');
                    
                $def_shift_id = 0;
                $shifts = get_defined_shifts_by_shift_list_value_id_and_date($def_shift_id_, $date_);
                    $shift = db_fetch($shifts);
                        if (isset($shift['id']) && $shift['id'] > 0) {
                            $def_shift_id = $shift['id'];
                        }

                $old_result = get_employee_attendances_details($date_, true);
                $has_old_recs = (db_num_rows($old_result) > 0) ? true : false;
                
                $shifts_array = get_shifts_array($date);

                    $result = get_employee_attendances_details($date_);
                        $k = $j = $total = $saved = 0; //row colour counter
                        while ($row = db_fetch($result)) {
                            $emp_code = $row['employee_code'];
                            
//                            if($emp_code == "YISK/168"){
//                                $ss = 55;
//                            }

                            alt_table_row_color($k);

                                $total++;
                                if ($row['id'] > 0) {
                                    $saved++;
                                    $date_s = strtotime($date);
                                    $att_id = $row['id'];
                                    $link_code = $date_s."~".$att_id."~".$emp_code;
                                    $link = get_payroll_trans_view_str(ST_ATTENDANCE, $link_code, $row['id']);
                                } else {
                                    $link = '';
                                }

                                label_cell($link, 'align=center');
                                label_cell(get_employee_formatted_long_name($emp_code));

                                if ($row['id'] > 0) {
                                    if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                        $_POST['shift_id_'.$emp_code] = $row['shift_id'];
                                        $in_time = substr($row['from_date_time1'], 11, 5);
                                        $out_time = substr($row['to_date_time1'], 11, 5);

                                    } else {

                                        set_post_not_set_numeric('shift_id_'.$emp_code, $def_shift_id, "date", 1);
                                        if (! isset_string_post("in_time_$emp_code")) {
                                            $in_time = substr($row['from_date_time1'], 11, 5);
                                        } else {
                                            $in_time = get_post('in_time_'.$emp_code);
                                        }

                                        if(! isset_string_post("out_time_$emp_code")) {
                                            $out_time = substr($row['to_date_time1'], 11, 5);
                                        } else {
                                            $out_time = get_post('out_time_'.$emp_code);
                                        }
                                    }

                                    if (! (isset($_POST["comment_$emp_code"]) && strlen($_POST["comment_$emp_code"]) > 0)) {
                                        $_POST["comment_$emp_code"] = $row['comment'];
                                    }
                                    
                                    hidden("id_$emp_code", $row['id']);

                                } else {

                                    $applicable_shift = get_applicable_shift_details($emp_code, date2sql($date_));
                                        if (is_array($applicable_shift)) {
                                            if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                                $_POST['shift_id_'.$emp_code] = $applicable_shift['id'];
                                            } else {
                                                set_post_not_set_numeric('shift_id_'.$emp_code, $applicable_shift['id'], "date", 1);
                                            }
                                            
                                            // read selected shift
                                            $already_selected_shift = get_shift_details($_POST['shift_id_'.$emp_code]);
//                                                if (! isset_string_post("in_time_$emp_code")) {
                                                if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                                    $in_time = substr($already_selected_shift['start_time1'], 0, 5);
                                                } else {
                                                    $in_time = get_post('in_time_'.$emp_code);
                                                }

//                                                if(! isset_string_post("out_time_$emp_code")) {
                                                if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                                    $duration = $already_selected_shift['duration1'];
                                                    $in_dt = "1970-01-01 ".$in_time.":00";
                                                    $in_dt_t = strtotime($in_dt);
                                                    $out_dt_t = strtotime('+'.substr($duration,0,2).' hours', $in_dt_t);
                                                    $out_dt_t = strtotime('+'.substr($duration,3,2).' minutes', $out_dt_t);
                                                    $out_time = date("H:i", $out_dt_t);
                                                } else {
                                                    $out_time = get_post('out_time_'.$emp_code);
                                                }

                                        } else {// No shift schedule

                                            if (isset_string_post('_date_changed')) {
                                                $_POST['shift_id_'.$emp_code] = $def_shift_id;
                                                $in_time = $def_in_time;
                                                $out_time = $def_out_time;
                                            } else {
                                                set_post_not_set_numeric('shift_id_'.$emp_code, $def_shift_id);

//                                                if(! isset_string_post("in_time_$emp_code")) {
                                                if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                                    $in_time = $def_in_time;
                                                } else {
                                                    $in_time = get_post('in_time_'.$emp_code);
                                                }

//                                                if(! isset_string_post("out_time_$emp_code")) {
                                                if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                                    $out_time = $def_out_time;
                                                } else {
                                                    $out_time = get_post('out_time_'.$emp_code);
                                                }
                                            }
                                        }
                                        
                                        if (isset_string_post('_date_changed') || isset($_POST['Search:'])) {
                                            unset($_POST["comment_$emp_code"]);
                                        }

                                    hidden("id_$emp_code", -1);
                                }

                                custom_values_list_cells('', "shift_id_$emp_code", $shifts_array, null, false, true);
                                
                                $selected_shift = get_shift_details($_POST['shift_id_'.$emp_code]);
                                    if (is_array($selected_shift)) {
                                        $selected_shift_start_time = substr($selected_shift['start_time1'], 0, 5);
                                        $selected_shift_duration = $selected_shift['duration1'];
                                    } else {
                                        $time_dura = time_diff_seconds($date_, $def_in_time, $date_, $def_out_time);
                                        $selected_shift_start_time = $def_in_time;
                                        $selected_shift_duration = gmdate("H:i:s", $time_dura);
                                    }
                                        
                                    $selected_shift_start_time_dt = "1970-01-01 ".$selected_shift_start_time.":00";
                                    $selected_shift_start_time_dt_t = strtotime($selected_shift_start_time_dt);
                                    $selected_shift_end_time_dt_t = strtotime('+'.substr($selected_shift_duration,0,2).' hours', $selected_shift_start_time_dt_t);
                                    $selected_shift_end_time_dt_t = strtotime('+'.substr($selected_shift_duration,3,2).' minutes', $selected_shift_end_time_dt_t);

                                $selected_shift_end_time = date("H:i", $selected_shift_end_time_dt_t);

                                label_cell($selected_shift_start_time, 'align=center');
                                $_POST["selected_shift_start_time_$emp_code"] = $selected_shift_start_time;
                                hidden("selected_shift_start_time_$emp_code", $selected_shift_start_time);

                                label_cell($selected_shift_end_time, 'align=center');
                                $_POST["selected_shift_end_time_$emp_code"] = $selected_shift_end_time;
                                hidden("selected_shift_end_time_$emp_code", $selected_shift_end_time);

                                $_POST["in_time_$emp_code"] = $in_time;
                                $_POST["out_time_$emp_code"] = $out_time;

                                if (! $has_old_recs) {
                                    $checked = 1;
                                } else {
                                    ($row['id'] > 0) ? $checked = 1 : $checked = 0;
                                }
                                
                                $_POST["checked_$emp_code"] = $checked;

                                text_cells('', "in_time_$emp_code", null, 5, 5);
                                text_cells('', "out_time_$emp_code", null, 5, 5);

                                if ($row['calculated_deficit_time'] == null || substr($row['calculated_deficit_time'],0,5) == "00:00") {
                                    $deficit_time_text = "";
                                } else {
                                    $deficit_time_text = substr($row['calculated_deficit_time'],0,5);
                                }
                                label_cell($deficit_time_text, 'align=center');
                                
                                text_cells('', "comment_$emp_code", null, 50, 500);

                                check_cells('', "checked_$emp_code", null, false, 'checked ot save record', 'align=center');

                            end_row();
                        }
                
                $text = "Total : ".$total." ".spaces(2)." Saved : ".$saved;
                    start_row();
                        label_cell(text_bold($text), 'colspan=9 align=center');
                    end_row();
        end_table(2);

}

function get_shifts_array($date) {
    $shifts_array = array();
    
        $result = get_shifts_by_date($date);
            while ($row = db_fetch($result)) {
                $shifts = get_defined_shifts_by_shift_list_value_id_and_date($row['shift_list_value_id'], sql2date($date));
                    $shift = db_fetch($shifts);
                
                    $shifts_array[$shift['id']] = $row['shift'];
            }
            
            return $shifts_array;
}

function can_save_employee_attendances($date) {
    $row = get_employee_attendances_header_by_date($date);
        if (is_array($row) && ! in_array($row['attendance_status_code'], array('N', 'U'))) {
            if (in_array($row['attendance_status_code'], array('A', 'L'))) {
                return array('success' => false, 
                             'message' => "Approval status of attendances not allow to further update. Please reopen Attendance records on '$date'.");
            } else {
                return array('success' => false, 
                             'message' => "Approval status of attendances not allow to further update.");
            }
        }
    
        return array('success' => true, '');
}

function save_employee_attendances($date_) {
    $date = date2sql($date_);
    
    $msg = can_save_employee_attendances($date);
        if ($msg['success'] === false) {
            return $msg;
        }
    
        $result = get_employee_attendances_details($date_);

        $updated =  $deleted = 0;
        
        begin_transaction();
        
        while ($row = db_fetch($result)) {
            $emp_code = $row['employee_code'];

            if (isset($_POST["checked_$emp_code"])) {
                $info = array();

                    $info['shift_id'.$emp_code] = $_POST['shift_id_'.$emp_code];
                    $info["selected_shift_start_time".$emp_code] = $_POST["selected_shift_start_time_".$emp_code];
                    $info["selected_shift_end_time".$emp_code] = $_POST["selected_shift_end_time_".$emp_code];

                    $info["from_date_time1".$emp_code] = $_POST["in_time_".$emp_code];
                    $info["to_date_time1".$emp_code] = $_POST["out_time_".$emp_code];

                    $info["out_of_office_time1".$emp_code] = "00:00";
                    $info["deducted_deficit_time".$emp_code] = "00:00";
                    $info["granted_ot_time".$emp_code] = "00:00";
                    $info["rate_table_id".$emp_code] = 0;
                    $info["comment".$emp_code] = $_POST["comment_$emp_code"];

                    $msg_pr = process_record($info, $date, $emp_code, '');

                    unset($info);

                    if ($msg_pr['passed'] !== true) {
                        display_error($msg_pr['message']);
                        return;
                    }

                    $updated++;

            } else {

                $old_key = $_POST["id_".$emp_code];
                
                if ($old_key > 0) {
                    $num_af_row = delete_employee_attendance($old_key, $date_, $emp_code, array("''", "'N'", "'U'"));
                        if ($num_af_row != 1) {
                            cancel_transaction();
                            
                            return array('success' => false, "message" => "Could not delete Record #$old_key. OT approval status not allow to delete.");
                        }
                }

                if ($_POST["id_".$emp_code] > 0) {
                    $deleted++;
                }
            }
        }

        change_employee_attendances_header($date);
            
        commit_transaction();
        
        if ($updated > 0 && $deleted > 0) {
            $msg = $updated." records updated and ".$deleted." records deleted.";
        } elseif($updated > 0) {
            $msg = $updated." records updated.";
        } elseif($deleted > 0) {
            $msg = $deleted." records deleted.";
        }

        return array('success' => true, 'message' => $msg); 
}


function save_employee_attendances1($date) {
    $status = can_process_employee_attendances($date);
    if (! ($status === true)) {
        return false;
    }
    
    $add_rec = $update_rec = $delete_rec = false;

    $old_checked_recs = get_old_checked_employee_attendance_records_array($date);
    $new_checked_recs = get_new_checked_employee_attendance_records_array($date);
    
    if (empty($old_checked_recs)) {
        foreach ($new_checked_recs as $new_key => $nemp) {
            add_employee_attendance($date, $nemp['emp_code'], $nemp['in_time'], $nemp['out_time']);
            $add_rec = true;
        }
    } else {
        foreach ($old_checked_recs as $old_key => $oemp) {
            if (array_key_exists($oemp['emp_code'], $new_checked_recs)) {
                update_employee_attendance($old_key, $date, $oemp['emp_code'], $oemp['in_time'], $oemp['out_time']);
                unset($new_checked_recs[$oemp['emp_code']]);
                $update_rec = true;
            } else {
                delete_employee_attendance($old_key, $date, $oemp['emp_code']);
                $delete_rec = true;
            }
        }

        foreach ($new_checked_recs as $new_key => $nemp) {
            add_employee_attendance($date, $nemp['emp_code'], $nemp['in_time'], $nemp['out_time']);
            $add_rec = true;
        }
    }
    
    if ($update_rec) {
        display_notification("Selected employee attendance records have been updated.");
    } elseif ($add_rec) {
        display_notification("Selected employee attendance records have been added.");
    } elseif ($delete_rec) {
        display_notification("Employee attendance records have been deleted.");
    }
    
    return true;
}

function get_old_checked_employee_attendance_records_array($date) {
    $sql_date = date2sql($date);
    $old_checked_recs = array();
    
    $result = get_employee_attendances_details($date, true);
    while ($row = db_fetch($result)) {
        $emp = $row['employee_code'];
        $old_checked_recs[$row['id']] = array('emp_code' => $row['employee_code'], 'in_time' => $sql_date.' '.substr($_POST["in_time_$emp"], 0, 5), 
                                              'out_time' => $sql_date.' '.substr($_POST["out_time_$emp"], 0, 5)); 
    }
    
    return $old_checked_recs;
}

function get_new_checked_employee_attendance_records_array($date) {
    $sql_date = date2sql($date);
    $old_checked_recs = array();
    
    $result = get_employee_attendances_details($date);
    while ($row = db_fetch($result)) {
        $emp = $row['employee_code'];
        if (isset($_POST["checked_$emp"])) {
            $old_checked_recs[$row['employee_code']] = array('emp_code' => $row['employee_code'], 'in_time' => $sql_date.' '.substr($_POST["in_time_$emp"], 0, 5), 
                                                             'out_time' => $sql_date.' '.substr($_POST["out_time_$emp"], 0, 5));
        }
    }
    
    return $old_checked_recs;
}

function can_process_employee_attendances($date) {
    if (! is_date($date)) {
        display_error("Date is not a valid date.");
        set_focus('date');
        return false;
    }
    
    $result = get_employee_attendances_details($date);
    while ($row = db_fetch($result)) {
        $id = $row['id'];
        ($id > 0) ? $d_id = " [#$id]" : $d_id = "";
        $emp_code = $row['employee_code'];
        
        if (isset($_POST["checked_$emp_code"])) {
            $in_time = substr($_POST["in_time_$emp_code"], 0, 5);
            $out_time = substr($_POST["out_time_$emp_code"], 0, 5);
            
            if (! (strlen($in_time) == 5)) { // if in time 01:55 and out time 1:5 both are valid time but unable to check greater than time; logical error occured
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - In Time is not a valid time.");
                set_focus("in_time_$emp_code");
                return false;
            }
            
            if (! (strlen($out_time) == 5)) {
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - Out Time is not a valid time.");
                set_focus("out_time_$emp_code");
                return false;
            }
            
            if (! (preg_match('/:/', $in_time))) { // without : is_time function give true so db error is occured
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - In Time is not a valid time.");
                set_focus("in_time_$emp_code");
                return false;
            } else {
                if (! (substr_count($in_time, ':') == 1)) {
                    display_error(get_employee_formatted_long_name($emp_code).$d_id." - In Time is not a valid time.");
                    set_focus("in_time_$emp_code");
                    return false;
                }
            }
            
            if (! (preg_match('/:/', $out_time))) {
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - Out Time is not a valid time.");
                set_focus("out_time_$emp_code");
                return false;
            } else {
                if (! (substr_count($out_time, ':') == 1)) {
                    display_error(get_employee_formatted_long_name($emp_code).$d_id." - Out Time is not a valid time.");
                    set_focus("out_time_$emp_code");
                    return false;
                }
            }
            
            if (! (is_time($in_time))) {
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - In Time is not a valid time.");
                set_focus("in_time_$emp_code");
                return false;
            }
            
            if (! (is_time($out_time))) {
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - Out Time is not a valid time.");
                set_focus("out_time_$emp_code");
                return false;
            }
            
            if (! ($out_time > $in_time)) {
                display_error(get_employee_formatted_long_name($emp_code).$d_id." - Out Time must be greater than In Time.");
                set_focus("out_time_$emp_code");
                return false;
            }
        }
    }
    
    return true;
}


function change_employee_attendances_header($date) {
    $svd_recs = get_employee_attendances_details(sql2date($date), true);
    $presents = db_num_rows($svd_recs);
        if (! ($presents > 0)) {
            $num_af_row = delete_employee_attendances_header(0, $date);
                if($num_af_row != 1) {
                    return array('success' => false, "Another user has updated attendance header record.");
                }
        } else {
            $total_emps = get_employee_attendances_details(sql2date($date));
            $total_employees = db_num_rows($total_emps);

//            $absents = ($total_employees - $presents);

            $header_result = get_employee_attendances_header(0, $date, $date);
            $header = db_fetch($header_result);
            if (! is_array($header)) {
                add_employee_attendances_header($date, $total_employees, $presents, 'N');
            } else {
                update_employee_attendances_header($header['id'], $total_employees, $presents, 'U');
            }
        }
}
