<?php
/**********************************************************************
***********************************************************************/

function initialize_values(&$cal)
{
    $cal['rec_type'] = "";
    $cal['total_entered_duration'] = "";
        
}


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

function display_blank_record($work_time_name, $leave_summary_string)
{

        label_cell($work_time_name);
        label_cell("");label_cell("");label_cell("");label_cell("");label_cell("");
        label_cell("");label_cell("");label_cell("");
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        label_cell($leave_summary_string);
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
        
        
        
}

function calculate_saving_record($aid, $employee_code, $task_id,
                                $from_date_time1, $to_date_time1, $entered_duration1, 
                                $shift_row, $rate_table_id, 
                                $out_of_office_time1, 
                                $granted_ot_time, $deducted_deficit_time, 
                                $shift_schedule_details, $holiday_time, $comment,
                                $calendar_work_time_code)
{

        $cal = array();
        
        $cal['aid'] = $aid;
        $cal['employee_code'] = $employee_code;
        $cal['task_id'] = $task_id;
        $cal['rec_type'] = "attendance";
        $cal['from_date_time1'] = $from_date_time1;
        $cal['to_date_time1'] = $to_date_time1;
        $cal['entered_duration1'] = $entered_duration1;
        $cal['out_of_office_time1'] = $out_of_office_time1;
        $cal['granted_ot_time'] = $granted_ot_time;
        $cal['deducted_deficit_time'] = $deducted_deficit_time;
        $cal['comment'] = $comment;
        $cal['calendar_work_time_code'] = $calendar_work_time_code;
    
        $cal['rate_table_id'] = $rate_table_id;
        
        $cal["leave_hours"] = 0;
        $cal['leave_status_name'] = "";
        $cal['ot_status_name'] = "";
        $cal['ot_status_code'] = "";
        $cal['deficit_status_name'] = "";
        $cal['deficit_status_code'] = "";
        $cal['real_name'] = "";
        $cal['created_on'] = "";

        //$shift_schedule_details = get_shift_schedule_details($employee_code, $from_date_time1, $shift_row['id']);
        
        calculate_attendance_record($aid, $shift_row, $shift_schedule_details, $holiday_time, $cal);
        
        return $cal;
}
    

function write_attendance_record ($data)
{
    
    if(isset($data['aid'])){
        $aid = $data['aid'];
    }
    else{
        $aid = 0;
    }
    
    $employee_code = "";
    if(isset($data['employee_code'])){
        $employee_code = $data['employee_code'];
    }
    
    $single_record = $data['single_record'];
    $Mode = $data['mode'];
    
    $from_date1 = date2sql($data['from_date1']);
    $from_time1 = time2sql($data['from_time1']);
    $from_date_time1 = $from_date1." ".$from_time1;

    $to_date1 = date2sql($data['to_date1']);
    $to_time1 = time2sql($data['to_time1']);
    $to_date_time1 = $to_date1." ".$to_time1;
    
    if($data['err_msg_prefix'] == 0){
        $err_msg_prefix = '';
    }
    else{
        $err_msg_prefix = "Employee [".$employee_code."] - ".$from_date1." - ";
    }
        
    $comment = $data['comment'];

    $from_date_time1_s = strtotime($from_date_time1);
    if($from_date_time1_s == false){
        return array("passed" => false, "message" => $err_msg_prefix." Entered from date or time is invalid");
    }
    $to_date_time1_s = strtotime($to_date_time1);
    if($to_date_time1_s == false){
        return array("passed" => false, "message" => $err_msg_prefix." Entered to date or time is invalid");
    }
    $time_duration1_s = $to_date_time1_s - $from_date_time1_s;
    
    //Assume this is working past midnight for bulk record entry
    if($single_record == false && $time_duration1_s < 0){
            $new_to_date1 = date_time_add(date2sql($data['to_date1']), 3600*24);
            $to_date_time1 = $new_to_date1." ".$to_time1;
            
            $to_date_time1_s = strtotime($to_date_time1);
            $time_duration1_s = $to_date_time1_s - $from_date_time1_s;
    }
    
    $entered_duration1 = gmdate("H:i:s", $time_duration1_s);
    
    $applicable_shift_id = 0;
    $shift_id = 0;
    $applicable_rate_table_id = 0;
    $rate_table_id = 0;
    $split_shift = 0;
    $week_start_day = 0;
    
    if($data['shift_id'] > 0){
        $applicable_shift_id = $data['shift_id'];
    }
    
    $shift_schedule_details = get_shift_schedule_details($data['employee_code'], $from_date_time1);
    if($shift_schedule_details){
        if($applicable_shift_id == 0){
            $applicable_shift_id = $shift_schedule_details['shift_id'];
        }
        $week_start_day = $shift_schedule_details['week_start_day'];
    }
    
    if($data['rate_table_id'] > 0)
    {
        $applicable_rate_table_id = $data['rate_table_id'];
    }
    
    $holiday_time = get_holiday_time_details($from_date1);
    
    $shift_row = get_shift($data['employee_code'], $from_date_time1, $applicable_shift_id);
   if($shift_row){
        $shift_id = $shift_row['id'];
        $split_shift = $shift_row['split_shift'];
        
        if($applicable_rate_table_id == 0){
            if($holiday_time){
                if($holiday_time['ot_type'] == 1){
                    $applicable_rate_table_id = $shift_row['table1_id'];
                }
                elseif($holiday_time['ot_type'] == 2){
                    $applicable_rate_table_id = $shift_row['table2_id'];
                }
            }
        }
        if($applicable_rate_table_id == 0){
            $weekend_day_no = get_weekend_day_no($data['employee_code'], $from_date_time1, $week_start_day);
            if($weekend_day_no == 7){
                $applicable_rate_table_id = $shift_row['table2_id'];
            }
            else{
                $applicable_rate_table_id = $shift_row['table1_id'];
            }
        }
    }
        
    if($applicable_shift_id > 0){
        $shift_id = $applicable_shift_id;
    }
    
    if($applicable_rate_table_id > 0){ 
        $rate_table_id = $applicable_rate_table_id;
    }
    
    $task_id = "";
    if(isset($data['task_id'])){
        $task_id = $data['task_id'];
    }
    
    $out_of_office_time1 = "00:00:00";
    if(isset($data['out_of_office_time1'])){
        $out_of_office_time1 = $data['out_of_office_time1'];
    }
    
    $granted_ot_time = "00:00:00";
    if(isset($data['granted_ot_time'])){
        $granted_ot_time = $data['granted_ot_time'];
    }
    
    $deducted_deficit_time = "00:00:00";
    if(isset($data['deducted_deficit_time'])){
        $deducted_deficit_time = $data['deducted_deficit_time'];
    }
    
    $calendar_work_time_code = '';
    if(isset($data['calendar_work_time_code'])){
        $calendar_work_time_code = $data['calendar_work_time_code'];
    }
            
    $leave_time_code = '';
    if(isset($data['leave_time_code'])){
        $leave_time_code = $data['leave_time_code'];
    }
    $rec = 0;
    $fullday_leave_only = false;
        

    $can_process_msg = can_process_attendance($aid, $Mode, $employee_code, $task_id,
                                $from_date_time1,$to_date_time1, $time_duration1_s, 
                                $shift_id, $rate_table_id, 
                                $out_of_office_time1,
                                $granted_ot_time, $deducted_deficit_time,
                                $leave_time_code, $single_record);
    if($can_process_msg != ""){
        return array("passed" => false, "message" => $err_msg_prefix.$can_process_msg);
    }
    elseif($can_process_msg == "" && $time_duration1_s == 0){
        $fullday_leave_only = true;
    }
  
    if($fullday_leave_only == false){
        $cal = calculate_saving_record($aid, $employee_code, $task_id,
                                    $from_date_time1,$to_date_time1, $entered_duration1, 
                                    $shift_row, $rate_table_id, 
                                    $out_of_office_time1,
                                    $granted_ot_time, $deducted_deficit_time, 
                                    $shift_schedule_details, $holiday_time, $comment,
                                    $calendar_work_time_code);

        if ($Mode == 'ADD_ITEM' && $leave_time_code != "F" && $aid == 0){
            $cal['ot_status_code'] = $cal['deficit_status_code'] = "N";
            $rec = add_attendance($cal);
        }
        elseif ($Mode == 'UPDATE_ITEM'){
            $cal['ot_status_code'] = $cal['deficit_status_code'] = "U";

            if(isset($_POST['recalculate_selected_records'])){
                $cal['granted_ot_time'] =  $cal['calculated_ot_time'];
                $cal['ot_status_code'] = ATD_NEW;

                $cal['deducted_deficit_time'] = $cal['calculated_deficit_time'];
                $cal['deficit_status_code'] = ATD_NEW;   
            }
            elseif(isset($_POST['release_for_approval'])){

                $granted_ot_time_s = strtotime("1970-01-01 ".$cal['granted_ot_time']." UTC");
                $deducted_deficit_time_s = strtotime("1970-01-01 ".$cal['deducted_deficit_time']." UTC");

                if($granted_ot_time_s > 0 ){
                    if($_SESSION['wa_current_user']->ot_approver){
                        $cal['ot_status_code'] = ATD_APPROVED;
                    }
                    else{
                        $cal['ot_status_code'] = ATD_AWAITING_APPROVAL;
                    }
                }
                else{
                    $cal['ot_status_code'] = ATD_APPROVED;
                }

                $cal['deficit_status_code'] = ATD_APPROVED;            

            }

            $rec = update_attendance($aid, $cal);
        }
    }

        
    if($data['leave_time_code'] != -1){
        if($leave_time_code == "F" && $aid > 0){
            return array("passed" => false, "message" => $err_msg_prefix.'There is an attendance record already. Not possible to create a fullday leave.');
        }
        elseif(isset($_POST['recalculate_selected_records']) ==  false){
            $create_leave_msg = create_leave($employee_code, $data['from_date1'], 
                            $data['leave_time_code'], $data['leave_comment']);
            if($create_leave_msg['passed'] == false){
                return array("passed" => false, "message" => $err_msg_prefix.$create_leave_msg['message']);
            }
        }
    }
    
    return array("passed" => true, "message" => $rec);

}



function calculate_viewing_record($employee_code, $date, &$cal)
{

        $ar_result = get_period_attendance_records($date, $date, $employee_code);
        $ar_row = db_fetch($ar_result);
        
        $cal['aid'] = $ar_row['id'];
        $cal['employee_code'] = $ar_row['employee_code'];
        $cal['rec_type'] = "attendance"; 
        $cal['from_date_time1'] = $ar_row['from_date_time1'];
        $cal['to_date_time1'] = $ar_row['to_date_time1'] ;
        
        $from_date_time1_s = strtotime($cal['from_date_time1']);
        $to_date_time1_s = strtotime($cal['to_date_time1']);
        $time_duration1_s = $to_date_time1_s - $from_date_time1_s;
        $entered_duration1 = gmdate("H:i:s", $time_duration1_s);
    
    
        $cal['entered_duration1'] = $entered_duration1;
        $cal['out_of_office_time1'] = $ar_row['out_of_office_time1'];
        $cal['granted_ot_time'] = $ar_row['granted_ot_time'];
        $cal['payroll_ot_time'] = $ar_row['payroll_ot_time'];
        $cal['deducted_deficit_time'] = $ar_row['deducted_deficit_time'];
        $cal['comment'] = $ar_row['comment'];
        $cal['calendar_work_time_code'] = $ar_row['work_time_code'];
        
        $cal['shift_id'] = $ar_row['shift_id'];
    
        $cal['rate_table_id'] = $ar_row['rate_table_id'];
        
        $cal["leave_hours"] = 0;
        $cal['leave_status_name'] = "";
        $cal['ot_status_name'] = $ar_row["ot_status_name"];
        $cal['ot_status_code'] = $ar_row["ot_status_code"];
        $cal['deficit_status_name'] = $ar_row["deficit_status_name"];
        $cal['deficit_status_code'] = $ar_row["deficit_status_code"];
        $cal['real_name'] = "";
        $cal['created_on'] = "";

        $shift_row = get_shift($cal['employee_code'], substr($cal['from_date_time1'],0,10), $cal['shift_id']);
        
        $shift_schedule_details = get_shift_schedule_details($employee_code, $cal['from_date_time1'], $shift_row['id']);
        
        $holiday_time = get_holiday_time_details($cal['from_date_time1']);
        
        calculate_attendance_record($cal['aid'], $shift_row, $shift_schedule_details, $holiday_time, $cal);
}
  
function calculate_attendance_record($aid, $shift_row, $shift_schedule_details, $holiday_time, &$cal)
{
        $date = substr($cal['from_date_time1'], 0, 10);
        $employee_code = $cal['employee_code'];
        
        $cal['date'] = $date;
        $cal['shift_id'] = $shift_row["id"];
        $cal['shift_name'] = $shift_row["shift_name"];
        $cal['shift_start_time1'] = substr($shift_row["start_time1"], -8, 5);
        $cal['shift_duration1'] = $shift_row["duration1"];
        $cal['split_shift'] = 0;
        $cal['no_ot'] = $shift_row["no_ot"];
        
        
        if($shift_schedule_details){
            $cal['shift_schedule_id'] = $shift_schedule_details['id'];
            $cal['continuous_work'] = $shift_schedule_details["continuous_work"];
            $cal["saturday_work_time_id"] =  $shift_schedule_details["saturday_work_time_id"];
            $cal["sunday_work_time_id"] =  $shift_schedule_details["sunday_work_time_id"];
            $cal["week_start_day"] = $shift_schedule_details["week_start_day"];

        }
        else{
            // default shift
            $cal['shift_schedule_id'] = 0;
            $cal['continuous_work'] = 0;
            $cal["saturday_work_time_id"] =  0;
            $cal["sunday_work_time_id"] =  0;
            $cal["week_start_day"] = "M"; 
        }
            
        if($cal['continuous_work'] == 1){
            $cal['work_time_name'] = "Continuous Work";
        }
        else{
            $weekend_day_no = get_weekend_day_no($employee_code, $date, $cal["week_start_day"]);
            $cal['weekend_day_no'] = $weekend_day_no;

            if($cal['weekend_day_no'] == 6){
                $cal['work_time_name'] = "6th day";
            }
            elseif($cal['weekend_day_no'] == 7){
                $cal['work_time_name'] = "7th day";
            }
            else{
                $cal['work_time_name'] = "Full day";
            }
        }
            
        //$holiday_time = get_holiday_time_details($date);
        if($holiday_time){
            $cal['holiday_name'] = $holiday_time['holiday_name'];
            $cal['holiday_time_code'] = $holiday_time['holiday_time_code'];
            $cal['holiday_time_name'] = $holiday_time['holiday_time_name'];
            $cal['work_time_name'] = "(".$cal['holiday_name']." ".$cal['holiday_time_name'].")";
        }
        else{
            $cal['holiday_name'] = '';
            $cal['holiday_time_code'] = '';
            $cal['holiday_time_name'] = '';
            if(!isset($cal['holiday_time_name'])){
                $cal['work_time_name'] = "";
            }
        }
        
        $cal['ot_rounddown_value'] = get_module_parameter_value("payroll","ot_rounddown_value");
        $cal['deficit_roundup_value'] = get_module_parameter_value("payroll","deficit_roundup_value");
        
        $ot_rounddown_value = $cal['ot_rounddown_value'];
        $deficit_roundup_value = $cal['deficit_roundup_value'];
            

        if($cal['rate_table_id'] == 0){
            $cal['rate_table_name'] = $shift_row["rate_table_name"];
        }
        else{
            $cal['rate_table_name'] = $cal['rate_table_id'] ;
        }
        
        //-----------------------------------------------------------
        
        $shift_start_date_time1 = date_time_add($date, $shift_row["start_time1"]);
        $shift_start_date_time1_s = strtotime($shift_start_date_time1);
        
        $shift_duration1_s = strtotime("1970-01-01 ".$shift_row['duration1']." UTC");
        $shift_end_date_time1_s = $shift_start_date_time1_s + $shift_duration1_s;
        
        $total_shift_duration_s = $shift_duration1_s;
        $total_shift_duration = gmdate("H:i:s", $total_shift_duration_s);
        $cal['total_shift_duration'] = substr($total_shift_duration, -8, 5);
            
        //-------------------------------------------------------------------
        
        $ot_start_gap_s = strtotime("1970-01-01 ".$shift_row['ot_start_gap']." UTC");
        $cal['ot_start_gap'] = substr($shift_row['ot_start_gap'], -8, 5);
        
        $temp_shift_duration_s = $total_shift_duration_s;
        $temp_ot_start_gap_s = $ot_start_gap_s;
        
        if($cal['continuous_work'] == 1){
            $cal['work_time_name'] = "Continuous work";
        }
        else{            
            if($cal['weekend_day_no'] == 6){
                $saturday_work_time_id = $cal["saturday_work_time_id"];
                switch ($saturday_work_time_id) {
                    case 0:
                        // shift hours
                        break;
                    case 1:
                        $temp_shift_duration_s = 3600 * 4;
                        break;
                    case 2:
                        $temp_shift_duration_s = $total_shift_duration_s / 2; 
                        break;
                    case 3:
                        $temp_shift_duration_s = 3600 * 8; 
                        break;
                    case 4:
                        $temp_shift_duration_s = 0; 
                        $temp_ot_start_gap_s = 0;
                        break;
                    case 5:
                        $temp_shift_duration_s = 3600 * 5;
                        break;
                }
            }
            elseif($cal['weekend_day_no'] == 7){
                $sunday_work_time_id = $cal["sunday_work_time_id"];
                switch ($sunday_work_time_id) {
                    case 0:
                        // shift hours
                        break;
                    case 1:
                        $temp_shift_duration_s = 3600 * 4;
                        break;
                    case 2:
                        $temp_shift_duration_s = $total_shift_duration_s / 2; 
                        break;
                    case 3:
                        $temp_shift_duration_s = 3600 * 8; 
                        break;
                    case 4:
                        $temp_shift_duration_s = 0; 
                        $temp_ot_start_gap_s = 0;
                        break;
                    case 5:
                        $temp_shift_duration_s = 3600 * 5;
                        break;
                }
            }
            
            switch ($cal['holiday_time_code']):
                case 'M':
                    if($cal['calendar_work_time_code'] == "M"){
                        $temp_shift_duration_s = 0;
                        $temp_ot_start_gap_s = 0;
                    }
                    else{
                        if($temp_shift_duration_s > (3600 * 4)){
                            $temp_shift_duration_s = 3600 * 4;
                        }
                        $cal['work_time_name'] = $cal['holiday_name']." (".$cal['holiday_time_name'].")";
                    }
                    break;
                case 'A':
                    if($cal['calendar_work_time_code'] == "A"){
                        $temp_shift_duration_s = 0;
                        $temp_ot_start_gap_s = 0;
                    }
                    else{
                        if($temp_shift_duration_s > (3600 * 4)){
                            $temp_shift_duration_s = 3600 * 4;
                        }
                        $cal['work_time_name'] = $cal['holiday_name']." (".$cal['holiday_time_name'].")";
                    }
                    break;
                case 'F':
                    $temp_shift_duration_s = 0;
                    $temp_ot_start_gap_s = 0;
                    $cal['work_time_name'] = $cal['holiday_name']." (".$cal['holiday_time_name'].")";
                    break;
            endswitch;
        }
        
        //$temp_shift_duration1_s = 0;
        //$temp_shift_end_date_time1_s = $shift_end_date_time1_s;
        
        $temp_shift_duration1_s = $temp_shift_duration_s;
        
        $temp_shift_end_date_time1_s = $shift_start_date_time1_s + $temp_shift_duration1_s;

        $cal['applicable_shift_duration'] = "00:00:00";
        if($temp_shift_duration_s >= 0){
            $temp_shift_duration = gmdate("H:i:s", $temp_shift_duration_s);
            $cal['applicable_shift_duration'] = substr($temp_shift_duration, -8, 5);
        }
        $cal['applicable_ot_start_gap'] = "00:00:00";
        if($temp_ot_start_gap_s >= 0){
            $temp_ot_start_gap = gmdate("H:i:s", $temp_ot_start_gap_s);
            $cal['applicable_ot_start_gap'] = substr($temp_ot_start_gap, -8, 5);
        }
        
        
        //----------------------------------------------------------------------
        
        $entered_from_date_time1_s = strtotime($cal["from_date_time1"]);
        $entered_to_date_time1_s = strtotime($cal["to_date_time1"]);
        $out_of_office_time1_s = strtotime("1970-01-01 ".$cal['out_of_office_time1']." UTC");
            
        $entered_duration1_s = $entered_to_date_time1_s - $entered_from_date_time1_s - $out_of_office_time1_s;
        
        $total_entered_duration_s = $entered_duration1_s;
        
        $total_entered_duration = "00:00:00";
        if($total_entered_duration_s >= 0){
            $total_entered_duration = gmdate("H:i:s", $total_entered_duration_s);
        }
        
        $cal['total_entered_duration'] = substr($total_entered_duration, -8, 5);

        //-----------------------------------------------------------
        
        $cal['counted_m'] = "00:00";
        $counted_duration1_s = $entered_to_date_time1_s - $shift_start_date_time1_s;
        if($entered_from_date_time1_s > $shift_start_date_time1_s){
            /* Duration start is calculated based on shift start time in order to avoid OT deduction for late commers.
             * This is temporory modification as per Nilanka's request and below line will enabled once the system is live
             */
            //$counted_duration1_s = $entered_to_date_time1_s - $entered_from_date_time1_s;
        }
        
        if($counted_duration1_s >= $out_of_office_time1_s){
            $counted_duration1_s -= $out_of_office_time1_s;
        }
        else{
            $counted_duration1_s = 0;
        }
        
        $counted_duration1 = gmdate("H:i:s", $counted_duration1_s);
        $cal['counted_duration1'] = substr($counted_duration1, -8, 5);

        $day_counted_duration_s = $counted_duration1_s;

        if($day_counted_duration_s >= 0){
            $day_counted_duration = gmdate("H:i:s", $day_counted_duration_s);
        }
        else{
            $day_counted_duration = "00:00:00";
        }
        $cal['day_counted_duration'] = substr($day_counted_duration, -8, 5);

        //-------------------------------------------------------------------
        
        
        $l_t = get_time_array($cal["leave_hours"]);
        $leave_time_s = $l_t[0]*3600 + $l_t[1]*60 + $l_t[1];

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

        $late_time1 = "00:00:00";

        $late_time1_s = $entered_from_date_time1_s - $shift_start_date_time1_s;

        if($late_time1_s >= 0){
            $late_time1 = gmdate("H:i:s", $late_time1_s);
        }
        else{
            $late_time1_s = 0;
        }
        $cal['late_time1'] = substr($late_time1, -8, 5);

        
        
        $day_late_time_s = $late_time1_s;
        
        $day_late_time = "00:00:00";
        if($day_late_time_s >= 0){
            $day_late_time = gmdate("H:i:s", $day_late_time_s);
            $cal['day_late_time'] = substr($day_late_time, -8, 5);
        }
        else{
            $day_late_time = gmdate("H:i:s", -$day_late_time_s);
            $cal['day_late_time'] = "00:00 (-".substr($day_late_time, -8, 5).")";
        }
            
        //----------------------------------------------------------------
        


   

        $short_leave1 = "00:00:00";
        $short_leave1_s = $temp_shift_end_date_time1_s - $entered_to_date_time1_s;


        if($short_leave1_s >= 0){
            $short_leave1 = gmdate("H:i:s", $short_leave1_s);
            $cal['short_leave1'] = substr($short_leave1, -8, 5);
        }
        else{
            $short_leave1 = gmdate("H:i:s", -$short_leave1_s);
            $cal['short_leave1'] = "00:00 (-".substr($short_leave1, -8, 5).")";
        }

        $day_short_leave_s = $short_leave1_s;
        
        if($day_short_leave_s >= 0){
            $day_short_leave = gmdate("H:i:s", $day_short_leave_s);
            $cal['day_short_leave'] = substr($day_short_leave, -8, 5);
        }
        else{
            $day_short_leave = gmdate("H:i:s", -$day_short_leave_s);
            $cal['day_short_leave'] = "00:00 (-".substr($day_short_leave, -8, 5).")";
        }

        //------------------------------------------------------------------- 
        
        
                            
        //-------------------------------------------------------------------
        
        // late arrival
        if($late_time1_s > 0){
            // early leave
            if($day_short_leave_s > 0){
                $non_working_time_s = $day_late_time_s + $day_short_leave_s;
            }
            // left ontime or worked more. Can't catchup by working more as it is a late arrival
            if($day_short_leave_s <= 0){
                $non_working_time_s = $day_late_time_s;
            }
        }
        else{
        // arrived ontime or before
            // early leave
            if($day_short_leave_s > 0){
                $non_working_time_s = $day_short_leave_s;
            }
            // can go out and come back and work more and catchup lost time as it is an ontime arrival
            if($day_short_leave_s <= 0){
                $non_working_time_s = $day_late_time_s + $day_short_leave_s;
            }
        }
        
        if($non_working_time_s < 0){
            $non_working_time_s = 0;
        }
        
        $non_working_time_s += $out_of_office_time1_s;
        $non_working_time = gmdate("H:i:s", $non_working_time_s);
        $cal['non_working_time'] = substr($non_working_time, -8, 5);
        
        
        
//        if($temp_shift_duration_s > $day_counted_duration_s){
//            $day_deficit_s = $temp_shift_duration_s - $day_counted_duration_s;
//        }else{
//            $day_deficit_s = 0;
//        }
        
        $day_deficit_s = 0;
        if($day_late_time_s > 0){
            $day_deficit_s += $day_late_time_s;
        }
        if($day_short_leave_s > 0){
            $day_deficit_s += $day_short_leave_s;
        }

        if($entered_from_date_time1_s <=  $shift_start_date_time1_s){
            $work_start_time_within_shift1_s = $shift_start_date_time1_s;
        }
        elseif($shift_start_date_time1_s < $entered_from_date_time1_s && 
                    $entered_from_date_time1_s <  $temp_shift_end_date_time1_s){
            $work_start_time_within_shift1_s = $entered_from_date_time1_s;
        }
        else{
            $work_start_time_within_shift1_s = $temp_shift_end_date_time1_s;
        }

        if($entered_to_date_time1_s <=  $shift_start_date_time1_s){
            $work_end_time_within_shift1_s = $shift_start_date_time1_s;
        }
        elseif($shift_start_date_time1_s < $entered_to_date_time1_s && 
                    $entered_to_date_time1_s <  $temp_shift_end_date_time1_s){
            $work_end_time_within_shift1_s = $entered_to_date_time1_s;
        }
        else{
            $work_end_time_within_shift1_s = $temp_shift_end_date_time1_s;
        }
        
        
        $worked_time_within_shift1_s = $work_end_time_within_shift1_s - $work_start_time_within_shift1_s - $out_of_office_time1_s;
        if($worked_time_within_shift1_s < 0){
            $worked_time_within_shift1_s = 0;
        }

        $total_worked_time_within_shift_s = $worked_time_within_shift1_s;
        
        if($total_worked_time_within_shift_s >= 0){
            $total_worked_time_within_shift = gmdate("H:i:s", $total_worked_time_within_shift_s);
        }
        else{
            $total_worked_time_within_shift = "00:00:00";
        }

        $cal['worked_time_within_shift'] = substr($total_worked_time_within_shift, -8, 5);
             
        
        //-------------------------------------------------------------------

        $qualifying_hrs_for_ot_s = strtotime("1970-01-01 ".$shift_row['qualifying_hrs_for_ot']." UTC");
        $cal['qualifying_hrs_for_ot'] = substr($shift_row['qualifying_hrs_for_ot'], -8, 5);
            
        $calculated_ot_time_s = 0;
        $cal['calculation_comment'] = "Full day";

        
        if($shift_row['no_ot'] == 1){
            $calculated_ot_time_s = 0;
        }
        else{
            if($day_counted_duration_s > ($temp_shift_duration_s + $temp_ot_start_gap_s + $qualifying_hrs_for_ot_s)){
                $calculated_ot_time_s = $day_counted_duration_s - ($temp_shift_duration_s + $temp_ot_start_gap_s);
            }
        }
        if($calculated_ot_time_s >= 0){
            $calculated_ot_time = gmdate("H:i:s", $calculated_ot_time_s);
        }
        else{
            $calculated_ot_time = "00:00:00";
        }
        

        

        if($day_deficit_s >= 0){
            $calculated_deficit_time = gmdate("H:i:s", $day_deficit_s);
       
            $calculated_deficit_hours = (int)substr($calculated_deficit_time, -8, 2);
            $calculated_deficit_minutes = (int)substr($calculated_deficit_time, -5, 2);
            $adjusted_deficit_minutes = (int)(ceil($calculated_deficit_minutes/$deficit_roundup_value)*$deficit_roundup_value);

            $h = floor($adjusted_deficit_minutes/60);
            $calculated_deficit_hours += $h;

            $adjusted_deficit_minutes -= $h*60;

            $adjusted_deficit_minutes = substr("00".$adjusted_deficit_minutes, -2, 2);
            $calculated_deficit_hours = substr("00".$calculated_deficit_hours, -2, 2);
            $calculated_deficit_time = $calculated_deficit_hours.":".$adjusted_deficit_minutes.":00";
            
            $cal['calculated_deficit_time'] = substr($calculated_deficit_time, -8, 5);
        }
        else{
            $calculated_deficit_time = gmdate("H:i:s", -$day_deficit_s);
            $cal['calculated_deficit_time'] = "00:00 (-".substr($calculated_deficit_time, -8, 5).")";
        }
        
        
        //-------------------------------------------------------------------
        
        
        if($day_deficit_s > 0){
            $cal['apply_leave'] = 1;
        }
        else{
            $cal['apply_leave'] = 0;
        } 
        
        //-------------------------------------------------------------------
             
        
        $calculated_ot_hours = (int)substr($calculated_ot_time, -8, 2);
        $calculated_ot_minutes = (int)substr($calculated_ot_time, -5, 2);
        $adjusted_ot_minutes = (int)(floor($calculated_ot_minutes/$ot_rounddown_value)*$ot_rounddown_value);
        
        $adjusted_ot_minutes = substr("00".$adjusted_ot_minutes, -2, 2);
        $calculated_ot_hours = substr("00".$calculated_ot_hours, -2, 2);
        $calculated_ot_time = $calculated_ot_hours.":".$adjusted_ot_minutes.":00";
        
        $cal['calculated_ot_time'] = substr($calculated_ot_time, -8, 5);
        
        if($cal['aid'] == 0 && $cal['granted_ot_time'] == "00:00"){
            $cal['granted_ot_time'] = $cal['calculated_ot_time'];
        }
        else{
            $cal['granted_ot_time'] = substr($cal['granted_ot_time'], -8, 5);
        }
        
        
        if($cal['aid'] == 0 && $cal['deducted_deficit_time'] == "00:00"){
            $cal['deducted_deficit_time'] = substr($cal['calculated_deficit_time'],0,5);
        }
        else{
            $cal['deducted_deficit_time'] = substr($cal['deducted_deficit_time'], -8, 5);
        }
        
        $cal['success'] = true;
        $cal['message'] = "";
   
        return $cal;
}


function display_record($cid, $employee_code, $myrow, &$summary, $payroll_module_parameters)
{
    //$cid = "cid".$myrow["cid"]."_".$myrow['employee_code'];
    
    if($myrow["id"] == null){
        $new_record = calculate_new_record($cid, $employee_code, $myrow, $summary, $payroll_module_parameters);
        if(is_array($new_record)){
            display_new_record($new_record);
        }
    }
    else{
        display_attendance_record($cid, $myrow, $summary);
    }
}

function calculate_new_record($cid, $employee_code, $myrow, &$summary, $payroll_module_parameters)
{
    global $default_from_time1, $default_to_time1;
    
    $task_id = 0;
    $week_day_no = 0;
    $applicable_shift_id = 0;
    $applicable_rate_table_id = 0;
    $sunday_work_time_id = 0;
    $saturday_work_time_id = 0;
    $shift_rate1_table_id = 0;
    $shift_rate2_table_id = 0;
    $day_start_s = 0;
    $editable = true;
    
    $applicable_from_time = $myrow['date']." ".$payroll_module_parameters['default_from_time1'].":00";
    $applicable_to_time = $myrow['date']." ".$payroll_module_parameters['default_to_time1'].":00";
            
    $leave_info = array();
    get_leave_record($employee_code, $myrow['date'], $leave_info);
    if(isset($leave_info['total_leave_hours']) && $leave_info['total_leave_hours'] >= 8){
        $editable = false;
    }    
    
    $shift_schedule_details = get_shift_schedule_details($employee_code, $myrow['date']);
    if($shift_schedule_details){
        $task_id = $shift_schedule_details['task_id'];

        if($shift_schedule_details['shift_id'] > 0){
            $applicable_shift_id = $shift_schedule_details['shift_id'];
        }

        $shift_row = get_shift_details($applicable_shift_id);
        $day_start_s = strtotime("1970-01-01 ".$shift_row['day_start']." UTC");
        $shift_start_time_s = strtotime("1970-01-01 ".$shift_row['start_time1']." UTC");
        $shift_duration_s = strtotime("1970-01-01 ".$shift_row['duration1']." UTC");
        
        $shift_rate1_table_id = $shift_row['table1_id'];
        $shift_rate2_table_id = $shift_row['table2_id'];

        $applicable_from_time = $myrow['date']." ".$shift_row['start_time1'].":00";
        
        if($shift_schedule_details['continuous_work'] == 1){
            $temp_shift_duration_s = $shift_duration_s;        
            $work_time_name = "Continuous work";
        }
        else{        
            $week_day_no = get_weekend_day_no($employee_code, $myrow['date'], $shift_schedule_details['week_start_day']);
            if($week_day_no == 7){
                $sunday_work_time_id = $shift_schedule_details['sunday_work_time_id'];
                $applicable_rate_table_id = $shift_rate2_table_id;
                    switch ($sunday_work_time_id) {
                        case 0:
                            $temp_shift_duration_s = $shift_duration_s;
                            break;
                        case 1:
                            $temp_shift_duration_s = 3600 * 4;
                            break;
                        case 2:
                            $temp_shift_duration_s = $shift_duration_s / 2; 
                            break;
                        case 3:
                            $temp_shift_duration_s = 3600 * 8; 
                            break;
                        case 4:
                            $temp_shift_duration_s = 0; 
                            break;
                        case 5:
                            $temp_shift_duration_s = 3600 * 5;
                            break;
                    }
                    $work_time_name = "7th Day";
            }
            elseif($week_day_no == 6){
                    $saturday_work_time_id = $shift_schedule_details['saturday_work_time_id'];
                    $applicable_rate_table_id = $shift_rate1_table_id;
                    switch ($saturday_work_time_id) {
                        case 0:
                            $temp_shift_duration_s = $shift_duration_s;
                            break;
                        case 1:
                            $temp_shift_duration_s = 3600 * 4;
                            break;
                        case 2:
                            $temp_shift_duration_s = $shift_duration_s / 2; 
                            break;
                        case 3:
                            $temp_shift_duration_s = 3600 * 8; 
                            break;
                        case 4:
                            $temp_shift_duration_s = 0; 
                            break;
                        case 5:
                            $temp_shift_duration_s = 3600 * 5;
                            break;
                    }
                    $work_time_name = "6th Day";
            }
            else{
                $temp_shift_duration_s = $shift_duration_s;
                $work_time_name = "Full Day";
                $applicable_rate_table_id = $shift_rate1_table_id;
                //$work_time_name = $myrow['calendar_work_time_name'];
            }       
        }
        
        $shift_to_time_s = $shift_start_time_s + $temp_shift_duration_s;
        $applicable_to_time = gmdate("H:i:s", $shift_to_time_s);
    }
    
    if($myrow['holiday_time_code'] != null){
        if($myrow['holiday_ot_type'] == 1){
            $applicable_rate_table_id = $shift_rate1_table_id;
        }
        elseif($myrow['holiday_ot_type'] == 2){
            $applicable_rate_table_id = $shift_rate2_table_id;
        }
        
        $work_time_name = $myrow['holiday_name']." (".$myrow['holiday_time_name'].")"; 
    }
            
    if($payroll_module_parameters['use_defailt_times'] == 1){
        $applicable_from_time = substr($applicable_from_time, 11,5);
        $applicable_to_time = substr($applicable_to_time, 0,5);
    }
    else{
        $applicable_from_time = "00:00";
        $applicable_to_time = "00:00";
    }
    
    $out_of_office_time = "00:00";
    $granted_ot_time = "00:00";
    $payroll_ot_time = "00:00";
    $deducted_deficit_time = "00:00";
    $total_leave_hours = $leave_info['total_leave_hours'];
    $leave_summary_string = $leave_info['leave_summary_string'];
    
    $new_record = array("cid" => $cid,
            "editable" => $editable,
            "work_time_name" => $work_time_name,
            "task_id" => $task_id,
            "day_start_s" => $day_start_s,
            "shift_start_s" => $shift_start_time_s,
            "shift_end_s" => $shift_to_time_s,
            "applicable_from_time" => $applicable_from_time,
            "applicable_to_time" => $applicable_to_time,
            "out_of_office_time" => $out_of_office_time,
            "applicable_shift_id" => $applicable_shift_id,
            "granted_ot_time" => $granted_ot_time,
            "payroll_ot_time" => $payroll_ot_time,
            "applicable_rate_table_id" => $applicable_rate_table_id,
            "deducted_deficit_time" => $deducted_deficit_time,
            "total_leave_hours" => $total_leave_hours,
            "leave_summary_string" => $leave_summary_string);
    
    return $new_record;
    
}

function display_new_record($new_record)
{
    $cid = $new_record["cid"];
    $editable = $new_record["editable"];
    $work_time_name = $new_record["work_time_name"];
    $task_id = $new_record["task_id"];
    $applicable_from_time = $new_record["applicable_from_time"];
    $applicable_to_time = $new_record["applicable_to_time"];
    $out_of_office_time = $new_record["out_of_office_time"];
    $applicable_shift_id = $new_record["applicable_shift_id"];
    $granted_ot_time = $new_record["granted_ot_time"];
    $payroll_ot_time = $new_record["payroll_ot_time"];
    $applicable_rate_table_id = $new_record["applicable_rate_table_id"];
    $deducted_deficit_time = $new_record["deducted_deficit_time"];
    $total_leave_hours = $new_record["total_leave_hours"];
    $leave_summary_string = $new_record["leave_summary_string"];
    
    if(!$editable){
        display_blank_record($work_time_name, $leave_summary_string);
        return;
    }
    
    label_cell($work_time_name);
    
//    tasks_all_list_cells(null, "task_id".$cid, $task_id, true);
    label_cell('');
    hidden('task_id', 0);
    
    time_cells(null, "from_date_time1".$cid, $applicable_from_time,3);
    time_cells(null, "to_date_time1".$cid, $applicable_to_time,3);
    //time_cells(null, "out_of_office_time1".$cid, $out_of_office_time,3);
    hidden('out_of_office_time1'.$cid, $out_of_office_time);
    
    label_cell('');
    
    shift_list_cells(null, 'shift_id'.$cid, $applicable_shift_id, 'Use Shift Schedule Shift');
    
    label_cell('');
    label_cell('');
    //label_cell('');
    
    time_cells(null, "granted_ot_time".$cid, $granted_ot_time,3);
    
    label_cell('');
    
    value_list_cells(false, 'rate_table_id'.$cid, 'VALUE_TABLES', $applicable_rate_table_id, "Use Shift Rate Table",false);
    
    label_cell('');
    
    time_cells(null, "deducted_deficit_time".$cid, $deducted_deficit_time,3);
    
    //display_leave_record($myrow);
    
    //label_cell($cal['leave_time_name'], "align=center");
    
    if($total_leave_hours > 0){
        label_cell($leave_summary_string);
    }
    else{
        value_list_code_cells(null, 'leave_time_code'.$cid, 'HOLIDAY_TIME', null ,"",false);
    }

    //value_list_code_cells(null, 'leave_time_code'.$cid, 'HOLIDAY_TIME', null ,"",false);
    
    check_cells('', 'selected_'.$cid,1);
    
    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
    
    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
}



function display_attendance_record($cid, $myrow, &$summary)
{
    $editable = false;
    
    $from_date1 = substr($myrow['from_date_time1'],0,10);
    $from_time1 = substr($myrow['from_date_time1'],11,5);
    
    $to_date1 = substr($myrow['to_date_time1'],0,10);
    $to_time1 = substr($myrow['to_date_time1'],11,5);
    
    if($myrow['work_time_name'] == null){
        $work_time_name = $myrow['calendar_work_time_name'];
    }
    else{
        $work_time_name = $myrow['work_time_name'];
    }
    
    label_cell($work_time_name);
                    
    $rec_type = "attendance";
    
    if($rec_type == "attendance"){
        if($myrow['ot_status_code'] == ATD_NEW || $myrow['ot_status_code'] == ATD_UPDATED){
            $editable = true;
        }
    }
    else{
        $editable = true;
    }
    
    $leave_info = array();
    get_leave_record($myrow['employee_code'], substr($myrow['from_date_time1'],0,10), $leave_info);
    if(isset($leave_info['total_leave_hours']) && $leave_info['total_leave_hours'] >= 8){
        $editable = false;
    }
    
    if($editable){
    tasks_all_list_cells(null, "task_id".$cid, $myrow['task_id'], true);
    }
    else{
        label_cell("task name");
    }
        
        
    if($rec_type == "attendance"){  
            if($editable){
                time_cells(null, "from_date_time1".$cid, $from_time1,3);
                time_cells(null, "to_date_time1".$cid, $to_time1,3);
            }
            else{
                label_cell(display_time_value($from_time1));
                label_cell(display_time_value($to_time1));
            }

            //time_cells(null, "out_of_office_time1".$cid, substr($myrow['out_of_office_time1'],0,5),3);
            hidden("out_of_office_time1".$cid, $myrow['out_of_office_time1']);
            
            $from_date_time1_s = strtotime($myrow['from_date_time1']);
            $to_date_time1_s = strtotime($myrow['to_date_time1']);
            $out_of_office_time1_s = strtotime("1970-01-01 ".$myrow['out_of_office_time1']." UTC");
            
            $entered_duration1_s = $to_date_time1_s - $from_date_time1_s - $out_of_office_time1_s;
            $entered_duration1 = gmdate("H:i:s", $entered_duration1_s);
            label_cell(display_time_value($entered_duration1), "align=center");
            
            
    }
    else{
            time_cells(null, "from_date_time1".$cid, $from_time1,3);
            time_cells(null, "to_date_time1".$cid, $to_time1,3);

            label_cell("");
            
            label_cell("");
    }
                
    
    
    if($rec_type == "attendance"){ 
        if(!$editable){
            label_cell($myrow['shift_name'], "align=center");
        }
        else{
            shift_list_cells(null, 'shift_id'.$cid, $myrow['shift_id'], 'Use Shift Schedule Shift');
        }
    }
    else{
        shift_list_cells(null, 'shift_id'.$cid, 0, 'Use Shift Schedule Shift');
    }
    
    
    if($rec_type == "attendance"){ 
            label_cell(substr($myrow['counted_duration1'],0,5), "align=center");
            label_cell(display_time_value($myrow['calculated_ot_time']), "align=center");

            if($editable){
                //time_cells(null, "granted_ot_time".$cid, substr($myrow['granted_ot_time'],0,5),3);
                time_cells(null, "granted_ot_time".$cid, substr($myrow['granted_ot_time'],0,5),3);
                label_cell(display_time_value($myrow['payroll_ot_time']), "align=center");
                value_list_cells(false, 'rate_table_id'.$cid, 'VALUE_TABLES', $myrow['rate_table_id'],"Use Shift Rate Table",false);
                
            }
            else{
                label_cell(display_time_value($myrow['granted_ot_time']), "align=center");
                label_cell(display_time_value($myrow['payroll_ot_time']), "align=center");
                label_cell($myrow['rate_table_name'], "align=center");
            }
    }
    else{
            label_cell("");
            label_cell("");
            time_cells(null, "granted_ot_time".$cid, substr($myrow['granted_ot_time'],0,5),3);
            label_cell(display_time_value($myrow['payroll_ot_time']), "align=center");
            value_list_cells(null, 'rate_table_id'.$cid, 'VALUE_TABLES', null,"Use Shift Rate Table",false);
    }
    
    if($rec_type == "attendance"){ 
            label_cell(display_time_value(substr($myrow['calculated_deficit_time'],0,5)), "align=center");

            if($editable){
                //time_cells(null, "granted_ot_time".$cid, substr($myrow['granted_ot_time'],0,5),3);
                time_cells(null, "deducted_deficit_time".$cid, substr($myrow['deducted_deficit_time'],0,5),3);
                
            }
            else{
                label_cell(display_time_value($myrow['deducted_deficit_time']), "align=center");
            }
    }
    else{
            label_cell("");
            time_cells(null, "deducted_deficit_time".$cid, substr($myrow['deducted_deficit_time'],0,5),3);
    }
    

            //label_cell($cal['calculation_comment']);
            //label_cell($myrow['comment']);
    

    //display_leave_record($myrow);
    
    //label_cell($cal['leave_time_name'], "align=center");
    
    if($leave_info['total_leave_hours'] > 0){
        label_cell($leave_info['leave_summary_string']);
    }
    else{
        value_list_code_cells(null, 'leave_time_code'.$cid, 'HOLIDAY_TIME', null ,"",false);
    }


            
    if($rec_type == "attendance"){            
//            if(!($cal['ot_status_code'] == "N" || $cal['ot_status_code'] == "U" || $cal['ot_status_code'] == "R" )){
//                label_cell($cal['ot_status_name']); 
//            }
//            elseif(!($cal['deficit_status_code'] == "N" || $cal['deficit_status_code'] == "U" || $cal['deficit_status_code'] == "J")){
//                label_cell($cal['deficit_status_name']); 
//            }
//            elseif($cal['ot_status_code'] == "J" ){
//                label_cell($cal['ot_status_name']); 
//            }
//            elseif($cal['deficit_status_code'] == "J"){
//                label_cell($cal['deficit_status_name']); 
//            }
//            elseif($cal['ot_status_code'] == "U" ){
//                label_cell($cal['ot_status_name']); 
//            }
//            elseif($cal['deficit_status_code'] == "U"){
//                label_cell($cal['deficit_status_name']); 
//            }
//            else{
//                label_cell($cal['ot_status_name']); 
//            }
    }
    else{
//            label_cell("");
            check_cells('', 'selected_'.$cid,0);
            label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
            label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
    }
    
    if($rec_type == "attendance"){
        if($editable){
                check_cells('', 'selected_'.$cid,1);
                edit_button_cell("Edit".$cid, _("Edit"));
                edit_button_cell("Delete".$cid, _("Delete"));           
            }
            else{
                    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
            }
    }
    
    calculate_summary($cid, $myrow, $summary);

}

function calculate_summary($cid, $myrow, &$summary)
{
        $rec_count = $summary['rec_count'];

        $total_out_of_office_time_s = $summary['total_out_of_office_time_s'];
        $total_entered_duration_s = $summary['total_entered_duration_s'];
        $total_counted_duration_s = $summary['total_counted_duration_s'];

        $total_ot_time_calculated_s = $summary['total_ot_time_calculated_s'];
        $total_ot_time_granted_s = $summary['total_ot_time_granted_s'];
        $total_payroll_ot_time_s = $summary['total_payroll_ot_time_s'];

        $total_deficit_time_calculated_s = $summary['total_deficit_time_calculated_s'];
        $total_deficit_time_deducted_s = $summary['total_deficit_time_deducted_s'];
    
        $rec_count += 1;
        
        $from_date_time1_s = strtotime($myrow['from_date_time1']);
        $to_date_time1_s = strtotime($myrow['to_date_time1']);
        $out_of_office_time1_s = strtotime("1970-01-01 ".$myrow['out_of_office_time1']." UTC");

        $entered_duration1_s = $to_date_time1_s - $from_date_time1_s - $out_of_office_time1_s;
        
        $total_out_of_office_time_s += $out_of_office_time1_s;
        $total_entered_duration_s += $entered_duration1_s;
        $total_counted_duration_s += strtotime("1970-01-01 ".$myrow['counted_duration1']." UTC");

        $total_ot_time_calculated_s += strtotime("1970-01-01 ".$myrow['calculated_ot_time']." UTC");
        $total_ot_time_granted_s += strtotime("1970-01-01 ".$myrow['granted_ot_time']." UTC");
        $total_payroll_ot_time_s += strtotime("1970-01-01 ".$myrow['payroll_ot_time']." UTC");
        
        $total_deficit_time_calculated_s += strtotime("1970-01-01 ".$myrow['calculated_deficit_time']." UTC");
        $total_deficit_time_deducted_s += strtotime("1970-01-01 ".$myrow['deducted_deficit_time']." UTC");
        
             
        $summary['rec_count'] = $rec_count;

        $summary['total_out_of_office_time_s'] = $total_out_of_office_time_s;
        $summary['total_entered_duration_s'] = $total_entered_duration_s;
        $summary['total_counted_duration_s'] = $total_counted_duration_s;

        $summary['total_ot_time_calculated_s'] = $total_ot_time_calculated_s;
        $summary['total_ot_time_granted_s'] = $total_ot_time_granted_s;
        $summary['total_payroll_ot_time_s'] = $total_payroll_ot_time_s;

        $summary['total_deficit_time_calculated_s'] = $total_deficit_time_calculated_s;
        $summary['total_deficit_time_deducted_s'] = $total_deficit_time_deducted_s;      
                    
}

function display_summary($summary)
{
        $rec_count = $summary['rec_count'];

        $total_out_of_office_time_s = $summary['total_out_of_office_time_s'];
        $total_entered_duration_s = $summary['total_entered_duration_s'];
        $total_counted_duration_s = $summary['total_counted_duration_s'];

        $total_ot_time_calculated_s = $summary['total_ot_time_calculated_s'];
        $total_ot_time_granted_s = $summary['total_ot_time_granted_s'];
        $total_payroll_ot_time_s = $summary['total_payroll_ot_time_s'];

        $total_deficit_time_calculated_s = $summary['total_deficit_time_calculated_s'];
        $total_deficit_time_deducted_s = $summary['total_deficit_time_deducted_s'];
        
 
        start_row();

        label_cell("<b>"."Entries: ".$rec_count."</b>", "colspan=4 align=right");
        label_cell("","colspan=1 align=right");
        //label_cell("<b>".seconds_to_time_string($total_out_of_office_time_s)."</b>","colspan=1 align=center");
        label_cell("<b>".seconds_to_time_string($total_entered_duration_s)."</b>","colspan=1 align=center");
        label_cell("");
        label_cell("<b>".seconds_to_time_string($total_counted_duration_s)."</b>","align=center");
        label_cell("<b>".seconds_to_time_string($total_ot_time_calculated_s)."</b>","align=center");
        label_cell("<b>".seconds_to_time_string($total_ot_time_granted_s)."</b>","align=center");
        label_cell("<b>".seconds_to_time_string($total_payroll_ot_time_s)."</b>","align=center");
        label_cell("");
        label_cell("<b>".seconds_to_time_string($total_deficit_time_calculated_s)."</b>","align=center");
        label_cell("<b>".seconds_to_time_string($total_deficit_time_deducted_s)."</b>","align=center");
        
        label_cell(_(""), "colspan=4");
        end_row();
}

function seconds_to_time_string($timestamp, $include_seconds = false)
{
        $h_floor = floor($timestamp/3600); 
        $h = str_pad($h_floor, 2, '0', STR_PAD_LEFT);
        
        if($include_seconds){
            $m_floor = floor(($timestamp - $h_floor * 3600) / 60);
            $m = str_pad($m_floor, 2, '0', STR_PAD_LEFT);

            $s = ($timestamp - $h_floor * 3600 - $m_floor * 60);
            $s = str_pad($s, 2, '0', STR_PAD_LEFT);
            
            $time = $h.":".$m.":".$s;
        }
        else{
            $m = ($timestamp - $h_floor * 3600) / 60;
            $m = str_pad($m, 2, '0', STR_PAD_LEFT);
            
            $time = $h.":".$m;
        }
        
        return $time;
}


function display_time_value($time)
{
    $time = substr($time,0,5);
    
    if($time == "00:00"){
        return "";
    }
    else{
        return $time;
    }
    
}

function get_duration($duration)
{
        $hours_int = floor(($duration/60));
        
        $hours = "00".($hours_int);
        $hours = substr($hours,-2);
        $minutes = "00".($duration%60);
        $minutes = substr($minutes,-2);
        
        $duration = $hours.":".$minutes;
        
        return $duration;
}

function calculate_empty_record($myrow, &$cal, &$summary)
{
    $rec_count = $summary['rec_count'];
    $total_entered_hour_count = $summary['total_entered_hour_count'];
    
    $total_counted_duration_s = $summary['total_counted_duration_s'];
    $total_ot_hours_granted_s = $summary['total_ot_hours_granted_s'];
            
            
        $cal['rec_type'] = "";
        $cal['from_date_time1'] = "00:00";
        $cal['to_date_time1'] = "00:00";
        
        $cal['from_date_time2'] = "00:00";
        $cal['to_date_time2'] = "00:00";       
        $cal['apply_leave'] = 1;
        $cal['granted_ot_time'] = "00:00";
        $cal['deducted_deficit_time'] = "00:00";
}


function can_process_attendance($aid, $Mode, $employee_code, $task_id,
                    $from_date_time1, $to_date_time1, $time_duration1, 
                    $shift_id, $rate_table_id,
                    $out_of_office_time1,
                    $granted_ot_time, $deducted_deficit_time,
                    $leave_time_code, $single_record = false)
{
    $input_error = 0;
    $msg = "Validation failed";
    
    $from_date1 = sql2date(substr($from_date_time1,0,10));
    $from_time1 = substr($from_date_time1,11,5);

    $to_date1 = sql2date(substr($to_date_time1,0,10));
    $to_time1 = substr($to_date_time1,11,5);
    
    if ($employee_code == ""){
        $input_error = 1;
        $msg = ( _("There is no employee selected."));
        if($single_record) set_focus('editing_employee_code');
        return $msg;
    }
    
    $employee = get_employee($employee_code);
    if (!$employee){
        $input_error = 1;
        $msg = ( _("Employee code [$employee_code] not found."));
        if($single_record) set_focus('editing_employee_code');
        return $msg;
    }
    
    if (!($task_id > 0)){
        $input_error = 1;
        $msg = ( _("There is no project task selected."));
        if($single_record) set_focus('editing_task_id');
        return $msg;
    }
    
    if(!$shift_id > 0){
        $input_error = 1;
        $msg = ( _("Either a shift is not selected or no shift schedule defined."));
        if($single_record) set_focus('editing_shift_id');
        return $msg;
    }
    
    if(!is_date($from_date1))
    {
        $input_error = 1;
        $msg = ( _("In date is not a valid date."));
        if($single_record) set_focus('editing_from_date1');      
        return $msg;
    }

    if(!is_date($to_date1))
    {
        $input_error = 1;
        $msg = ( _("Out date is not a valid date."));
        if($single_record) set_focus('editing_to_date1');       
        return $msg;
    }

    if(!is_time($from_time1))
    {
        $input_error = 1;
        $msg = ( _("In time is not a valid time."));
        if($single_record) set_focus('editing_from_time1');       
        return $msg;
    }

    if(!is_time($to_time1))
    {
        $input_error = 1;
        $msg = ( _("Out time is not a valid time."));
        if($single_record) set_focus('editing_to_time1');       
        return $msg;
    }
    
    if(!is_time($out_of_office_time1))
    {
        $input_error = 1;
        $msg = ( _("Out of office time is not a valid time."));
        if($single_record) set_focus('editing_out_of_office_time');       
        return $msg;
    }
    
    if (date1_greater_date2($from_date1,$to_date1))
    {
        $input_error = 1;
        $msg = ( _("Out Date can not be earlier than In Date."));
        if($single_record) set_focus('editing_to_date');
        return $msg;
    }
    
    if (date1_greater_date2(sql2date($employee['date_of_joining']), $from_date1))
    {
        $input_error = 1;
        $msg = ( _("Employee has not joined with the company yet."));
        if($single_record) set_focus('editing_from_date');
        return $msg;
    }
    
    if($employee['resigned'] == 1 && date1_greater_date2($from_date1, sql2date($employee['date_of_resignation'])))
    {
        $input_error = 1;
        $msg = ( _("Employee has resigned."));
        if($single_record) set_focus('editing_from_date');
        return $msg;
    }
    
    if(!is_time($granted_ot_time))
    {
        $input_error = 1;
        $msg = ( _("Granted OT Time is not a valid time duration."));
        if($single_record) set_focus('editing_granted_ot_time');       
        return $msg;
    }
    
    if(!is_time($deducted_deficit_time))
    {
        $input_error = 1;
        $msg = ( _("Deducted deficit Time is not a valid time duration."));
        if($single_record) set_focus('editing_deducted_deficit_time');       
        return $msg;
    }
    
        
    if(!$rate_table_id > 0){
        $input_error = 1;
        $msg = ( _("Either a rate table is not selected or no shift schedule defined."));
        if($single_record) set_focus('editing_rate_table_id');
        return $msg;
    }
    
    if($leave_time_code != "F"){
        if($time_duration1 <= 0)
        {
            $input_error = 1;
            $msg = ( _("Entered time duration should be possitive."));
            if($single_record) set_focus('editing_from_date1');
            return $msg;
        }

        if(check_overlapping_entries($employee_code, $aid, $from_date_time1, $to_date_time1, 1))
        {
            $input_error = 1;
            $msg = ( _("There is an already entered attendance entry overlapping with this attendance entry."));
            if($single_record) set_focus('from_date1');
            return $msg;
        }
    }
    
    if ($Mode == 'UPDATE_ITEM') 
    {
        $myrow = get_attendance_record($aid);
        if($myrow['ot_status_code'] == "A")
        {
            $input_error = 1;
            $msg = ( _("This record has been approved and can not be updated."));
            if($single_record) set_focus('editing_from_date');            
            return $msg;
        }
        elseif($myrow['ot_status_code'] == "J")
        {
            $input_error = 1;
            $msg = ( _("This record has been rejected and can not be updated."));
            if($single_record) set_focus('editing_from_date');            
            return $msg;
        }
    }
    
    if($input_error == 0){
        return "";
    }
    
    return $msg;
}



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


function get_filtering_dates()
{
    $backward_weeks = 1;
    if(!isset($_POST['selected_date']))
    {
        $date = date('Y-m-d');
    }
    else
    {
        $date = date2sql($_POST['selected_date']);
    }

    $period = get_session_variable('attendance_search_period');
    
    $y = date("Y", strtotime($date));
    $m = date("m", strtotime($date));
    $d = date("d", strtotime($date));

    switch ($period) {
        case 'W':
            $week_no = strtolower(date("W", mktime(0,0,0,$m,$d,$y)));
            $week_start_date = date('Y-m-d', strtotime('Sunday -'.$backward_weeks.' week '.$date));
            $week_end_date = date('Y-m-d', strtotime('Sunday +6 days'.$week_start_date));
            break;
        case 'M':
            // First day of the month.
            $week_start_date = date('Y-m-01', strtotime($date));
            // Last day of the month.
            $week_end_date = date('Y-m-t', strtotime($date));
            break;
        default:
            $week_start_date = $date;
            $week_end_date = $date;
            break;
    }
    
    $_POST['week_start_date'] = $week_start_date;
    $_POST['week_end_date'] = $week_end_date;

    $_POST['filtering_week_start_date'] = $_POST['week_start_date'];
    hidden('filtering_week_start_date');

    $_POST['filtering_week_end_date'] = $_POST['week_end_date'];
    hidden('filtering_week_end_date');    
}


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

function check_overlapping_entries($employee_code, $selected_id,$from_date_time,$to_date_time, $session)
{
    $result = get_overlapping_attendance_records($selected_id, $from_date_time, $to_date_time, $employee_code, $session);

    if (db_num_rows($result) > 0)
    {
        return true;
    }
    return false;
}

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

function get_shift($employee_code, $from_date_time1, $shift_id)
{
    if($shift_id <= 0){
        $shift = get_shift_schedule_details($employee_code, $from_date_time1);
        if(!$shift == null){
            $shift_id = $shift["shift_id"];
        }
    }
    
    if($shift_id > 0){
        return get_shift_details($shift_id);
    }
    else{
         // default shift
        return get_shift_details(get_module_parameter_value("payroll","shift_id"));
    }
    
    return null;
    
}

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

function get_weekend_day_no($employee_code, $from_date_time1, $week_start_day)
{
    $timestamp = strtotime($from_date_time1);
    $day = date('D', $timestamp);
    
    switch ($week_start_day) {
        case 'M':
            if($day == "Sat") return 6;
            elseif($day == "Sun") return 7;
            else{return 0;}
            break;
        case 'T':
            if($day == "Sun") return 6;
            elseif($day == "Sun") return 7;
            else{return 0;}
            break;
        case 'W':
            if($day == "Mon") return 6;
            elseif($day == "Tue") return 7;
            else{return 0;}
            break;
        case 'H':
            if($day == "Tue") return 6;
            elseif($day == "Wed") return 7;
            else{return 0;}
            break;
        case 'F':
            if($day == "Wed") return 6;
            elseif($day == "Thu") return 7;
            else{return 0;}
            break;
        case 'S':
            if($day == "Thu") return 6;
            elseif($day == "Fri") return 7;
            else{return 0;}
            break;
        case 'N':
            if($day == "Fri") return 6;
            elseif($day == "Sat") return 7;
            else{return 0;}
            break;
        default :
            return 0;
            break;
    }
   
}

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

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

function display_apply_leave($cal)
{
    label_cell("No attendance record found", "colspan=5 align=center");    

    if($cal['continuous_work'] == 1){
        label_cell("Full day");
        
    }
    else{
        if($cal['weekend_day_no'] == 6){
            $cal['work_time_name'] = "Morning";
        }
        elseif($cal['weekend_day_no'] == 7){
            $cal['work_time_name'] = "";
        }
        else{
            $cal['work_time_name'] = "Full day";
        }

        if($cal['holiday_time_code'] == "F"){
            $cal['work_time_name'] = "Full day";
        }
        elseif($cal['holiday_time_code'] == "M"){
            $cal['work_time_name'] = "Afternoon";
        }
        elseif($cal['holiday_time_code'] == "A"){
            $cal['work_time_name'] = "Morning";
        }
        
        label_cell($cal['work_time_name']);
    }
}

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

function get_leave_record($employee_code, $date, &$leave_info, &$summary = array())
{
    $leave_info['rec_type'] = "leave";
    $leave_info['total_leave_hours'] = 0;
    $leave_info['leave_details'] = array();
    $leave_info['leave_summary_string'] = "";
    
    if(count($summary) != 0 && isset($summary['last_leave_date']) && $summary['last_leave_date'] == $date){
        return;
    }
    
    $result = get_leave_details($employee_code, $date);
                
    while($myrow = db_fetch($result)){
        $leave_detail['leave_id'] = $myrow['leave_id'];

        $hours = (int)($myrow["leave_days"]*8);
        $leave_info['total_leave_hours'] += $hours;

        $hours = substr("00".$hours,-2);
        $leave_detail['leave_hours'] = $hours.":00";
        $leave_detail['leave_time_code'] = $myrow['leave_time_code'];
        $leave_detail['leave_time_name'] = $myrow['leave_time_name'];
        $leave_detail['leave_status_code'] = $myrow['leave_status_code'];

        $leave_info['leave_summary_string'] .= $myrow['leave_time_name']." ";

        $leave_info['leave_details'][] = $leave_detail;

        $summary['last_leave_date'] = $date;
    }
}

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

function display_leave_record($myrow, $rec_count = 0, $hour_count = 0)
{       
    //label_cell($_POST['id']);
    $leave_info = array();
    $summary = '';
    
    $date = substr($myrow['from_date_time1'],0,10);
    
    get_leave_record($myrow['employee_code'], $date, $leave_info, $summary);
    
    label_cell('date');
    label_cell('work_time_name');

    label_cell('leave_hours');

    label_cell("");label_cell("");label_cell("");label_cell("");label_cell("");
    label_cell("");label_cell("");label_cell("");label_cell("");
    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
    label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");

    end_row();

    //$_POST['last_leave_date'] = $_POST['date'];
    $rec_count += 1;
    $hour_count += $leave_info["leave_hours"];
    
        $apply_leave = 0;
    if(($apply_leave == 1) && 
        //($cal['rec_type'] == "attendance" && $editable == false) && 
            (($rec_type == "attendance" || $rec_type == "") && $editable == true) && 
                (   $leave_info['leave_status_code'] == "")){ 
                            value_list_code_cells(null, 'leave_time_code'.$cid, 'HOLIDAY_TIME', null ,"",false);
    }
    else{
        if($leave_info['leave_status_code'] == "N"){
            label_cell("(".$leave_info['leave_time_name'].")", "align=center");
        }
        else{
            label_cell($leave_info['leave_time_name'], "align=center");
        }
    }
}

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

function create_leave($employee_code, $date, $leave_time_code, $leave_comment)
{
        $Mode = 'ADD_ITEM';
        
        $myrow = get_uninformed_leave_type($employee_code);
        
        if(!$myrow){
            return array("passed" => false, "message" => "No uninformed leave type defined for employee - ".$employee_code);
        }
        else{
            $data["leave_entitlement_id"] = $myrow["id"];
            $data["employee_code"] = $employee_code;
            $data["from_date"] = $date;
            $data["leave_from_time_code"] = $leave_time_code;
            $data["to_date"] = $date; 
            $data["leave_to_time_code"] = $leave_time_code;

            $data["comment"] = $leave_comment;
            $data["is_revoke"] = 0;

            $add_leave_msg = add_leave($data, $Mode, false);
            
            return $add_leave_msg;
        }
        
}


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


function calculate_time_duration($from_date, $from_time, $to_date, $to_time)
{
    /*
    if(!is_date($_POST['from_time']));
    $from_time = is_time($_POST['from_time']);
    $to_time = is_time($_POST['to_time']);
    */
    $duration_mnts = time_diff_seconds($from_date, $from_time, $to_date, $to_time)/60;
    return $duration_mnts;

}

?>
