<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/includes/date_functions.inc");

//$pcs = "";

function display_file($selected_id, $payroll_module_parameters)
{
    clear_session_variable('import_attendance_organized_data');
    

    if(check_import_attendance_data($selected_id) == false){
        $row = get_attendance_file($selected_id);
    
        if(!$row)
        {
            display_error(_("Could not find file details for the selected file"));
        }
        else
        {
            $file_data = read_file($row, $selected_id);
            if(is_array($file_data)){
                $organized_data = organize_file_data($file_data, $payroll_module_parameters);
                set_session_variable('import_attendance_organized_data', $organized_data);
            }
            else{

            } 
        }
    }
    display_time_data();
    
}

function check_import_attendance_data($selected_id)
{
    $result = get_import_attendance_data($selected_id);
    $number_of_rows = db_num_rows($result);
    if($number_of_rows > 0){
        $organized_data = organize_import_data($result);
        set_session_variable('import_attendance_organized_data', $organized_data);
        return true;
    }
 else {
        return false;    
    }
}

function organize_import_data($attendance_data)
{
    while ($myrow = db_fetch($attendance_data)) 
    {
        $imported_data = array('id' => $myrow['id'], 
            'file_id' => $myrow['file_id'], 
            'employee_code' => $myrow['employee_code'], 
            'date' => $myrow['entry_date'], 
            'shift_id' => $myrow['shift_id'], 
            'table_id' => $myrow['table_id'],
            'task_id' => $myrow['task_id'],
            'in' => $myrow['in_time'],
            'out' => $myrow['out_time'],
            'non_working_time' => $myrow['non_working_time'],
            'times' => $myrow['times'],
            'attendance_rec_id' => $myrow['attendance_rec_id'],
            'message' => $myrow['message']);

    $organized_data[] = $imported_data;
    
    }
    return $organized_data;
}

function add_to_organized_data_array($file_id, $employee_code, $date,
                                    $shift_id, $shift_start_s, $shift_end_s,
                                    $rate_table_id, $task_id, 
                                    &$time_array, &$organized_data)
        
{
    if(!strlen(trim($employee_code)) > 0){
        $time_array = '';
        return;
    }
        
    $in = $out = $non_working_time = 0;
    
    calculate_time_entry_durations($time_array, $date, $shift_start_s, $shift_end_s,
                                        $in, $out, $non_working_time);
    
    $time_string = '';
    
    if(is_array($time_array)){
        foreach ($time_array as $time_value) {
            if(strlen($time_string) > 1){
                $time_string .= " | ";
            }
            $time_string .= substr($time_value,11,5);
        }
    }
        
    if(substr($in,11,5) == "00:00"){
        $in = substr($in,0,10)." ??:??";
    }
    
    $d = array('id' => 0, 
            'file_id' => $file_id, 
            'employee_code' => $employee_code, 
            'date' => $date, 
            'shift_id' => $shift_id, 
            'table_id' => $rate_table_id,
            'task_id' => $task_id,
            'in' => $in,
            'out' => $out,
            'non_working_time' => $non_working_time,
            'times' => $time_string,
            'attendance_rec_id' => '',
            'message' => '');

    $organized_data[] = $d;
    $time_array = '';
}


function calculate_time_entry_durations(&$time_array, $date, $shift_start_s, $shift_end_s,
                                        &$in, &$out, &$non_working_time)
{
    $non_working_time_s = 0;
    $date_s = strtotime($date." UTC");
    $array_count = count($time_array);

    
    if($array_count == 0){
        //no time entries
        $in = $out = $date." ??:??";
        $non_working_time = "00:00";
    }
    elseif($array_count == 1){
        //Only one time entry
        $shift_duration_s = $shift_end_s - $shift_start_s;
        $shift_mid_time_s = ($shift_end_s + $shift_start_s) / 2;        
        $shift_mid_s = $date_s + $shift_mid_time_s;
        $shift_mid = gmdate("Y-m-d H:i:s", $shift_mid_s);
            
        if(!isset($time_array[1])){
            $in = $out = $date." ??:??";
            $non_working_time = "00:00";
        }
        elseif($time_array[1] < $shift_mid){
            $in = $time_array[1];
            $out = $date." ??:??";
        }
        else{
            $in = $date." ??:??";
            $out = $time_array[1];
        }
        $non_working_time = "00:00";
    }
    elseif($array_count == 2){
        //Two time entries
        $in = $time_array[1];
        $out = $time_array[2];
        $non_working_time = "00:00";
    }
    elseif($array_count % 2 == 0){
        //Even number of time entries
        $in = $time_array[1];
        $out = $time_array[$array_count];
        
        for ($i = 2; $i < count($time_array); $i++) {
            $non_working_time_s += calculate_non_working_time($time_array, $i);
            $i++;
        }
        if($non_working_time_s > (3600*24-60)){
            $non_working_time_s = 3600*24-60;
        }
        $non_working_time = gmdate("Y-m-d H:i:s", $non_working_time_s);
        $non_working_time = substr($non_working_time, 11, 5);
    }
    else{
        //Odd number of time entries
        $shift_end_time = gmdate("Y-m-d H:i:s", $date_s + $shift_end_s);
        if($time_array[$array_count] > $shift_end_time){
            $in = $date." ??:??";
            $out = $time_array[$array_count];
            for ($i = 1; $i < count($time_array); $i++) {
                $non_working_time_s += calculate_non_working_time($time_array, $i);
                $i++;
            }
            $non_working_time = gmdate("Y-m-d H:i:s", $non_working_time_s);
        }
        else{
            $in = $time_array[1];
            $out = $date." ??:??";
            for ($i = 2; $i < count($time_array); $i++) {
                $non_working_time_s += calculate_non_working_time($time_array, $i);
                $i++;
            }
            $non_working_time = gmdate("Y-m-d H:i:s", $non_working_time_s);
        }
    }
}

function calculate_non_working_time($time_array, $j)
{
    if(isset($time_array[$j]) && isset($time_array[$j+1])){
        $temp_out_s = strtotime($time_array[$j]." UTC");
        $temp_in_s = strtotime($time_array[$j+1]." UTC");
        $non_working_time_s = $temp_in_s - $temp_out_s;
        return $non_working_time_s;
    }
    else{
        return 0;
    }
}

function organize_file_data($file_data, $payroll_module_parameters)
{
    $summary = '';
    $time_array = array();
    $previous_employee = '';
    $current_employee = '';
    $current_date = '';
    $previous_date = '';
    $entry_date = '';
    $organized_data = array();
    $applicable_shift_id = 0;
    $applicable_rate_table_id = 0;
    $file_id = 0;
    $task_id = 0;
    $day_start_s = 0;
    $shift_start_s = strtotime("1970-01-01 ".$payroll_module_parameters['default_from_time1']." UTC");
    $shift_end_s = strtotime("1970-01-01 ".$payroll_module_parameters['default_to_time1']." UTC");
    $read_attendance = true;
    $employee_name = "";
    $shift_name = "";
    
    foreach($file_data as $line){
        $file_id = $line['file_id'];
        $current_date = $line['date'];
        
        if($previous_employee == '' && $entry_date == ''){
            $entry_date = $line['date'];
            
        }
        
//        if($line['shift_id'] != $applicable_shift_id || $applicable_shift_id == 0){
//            $shift = get_shift_details($applicable_shift_id);
//            if($shift){
//                $shift_name = $shift['shift_name'];
//            }
//            else{
//                $shift_name = "Shift details not found";
//            }
//            $line['shift_id'] = $applicable_shift_id;
//        }
        
        if($line['employee_code'] != $current_employee){

            
            add_to_organized_data_array($file_id, $current_employee, $entry_date, 
                                        $applicable_shift_id, $shift_start_s, $shift_end_s, 
                                        $applicable_rate_table_id, $task_id, 
                                        $time_array, $organized_data);
            $entry_date = $line['date'];
            
            $previous_employee = $current_employee;
            $current_employee = $line['employee_code'];  
//            $employee = get_employee($current_employee);
//            if($employee){
//                $employee_name = $employee['initials']." ".$employee['last_name']." (".$employee['first_name'].")";
//            }
//            else{
//                $employee_name = "Employee code ".$current_employee." not found";
//            }
            $read_attendance = true;
            
        }
        
        if($read_attendance){
            $result = get_period_attendance_records($entry_date, $entry_date, $current_employee, '');
            $row = db_fetch($result);
            if($row){
                $cid = $row["cid"]."_".$current_employee;
                $new_record = calculate_new_record($cid, $current_employee, $row, $summary, $payroll_module_parameters); 

                $cid = $new_record["cid"];
                $editable = $new_record["editable"];
                $task_id = $new_record["task_id"];
                $day_start_s = $new_record["day_start_s"];
                $shift_start_s = $new_record["shift_start_s"];
                $shift_end_s = $new_record["shift_end_s"];
                $applicable_shift_id = $new_record["applicable_shift_id"];
                $applicable_rate_table_id = $new_record["applicable_rate_table_id"];
            }
            $read_attendance = false;
            $previous_date = $entry_date;
        }
        
        $day_end_s = $day_start_s + 3600 * 24 - 1;
        $day_s = strtotime($entry_date." UTC");
        $date_start_s = $day_s + $day_start_s;
        $date_end_s = $day_s + $day_end_s;
        
        $date_start = gmdate("Y-m-d H:i:s", $date_start_s);
        $date_end = gmdate("Y-m-d H:i:s", $date_end_s);

        $line_time = $current_date." ".$line['time'];
        
        if($day_s > 0){
            if($line_time < $date_start){
                add_to_time_array($time_array, $line_time);
            }
            elseif($date_start < $line_time && $line_time < $date_end){
                add_to_time_array($time_array, $line_time);
            }
            elseif($line_time > $date_end){
                    add_to_organized_data_array($file_id, $current_employee, $entry_date, 
                                        $applicable_shift_id, $shift_start_s, $shift_end_s, 
                                        $applicable_rate_table_id, $task_id, 
                                        $time_array, $organized_data);
                    
                    $entry_date = $line['date'];
                    
                    add_to_time_array($time_array, $line_time);
                    $read_attendance = true;
            }
            else{
                add_to_time_array($time_array, $line_time);
            }
        }
        else{
            add_to_time_array($time_array, $line_time);
        }
        
    }
    
    add_to_organized_data_array($file_id, $current_employee, $entry_date, 
                                        $applicable_shift_id, $shift_start_s, $shift_end_s, 
                                        $applicable_rate_table_id, $task_id, 
                                        $time_array, $organized_data);
    
    return $organized_data;
}

function add_to_time_array(&$time_array, $line_time)
{
    for ($i = 1; $i < 10; $i++) {
        if(!isset($time_array[$i])){
            $time_array[$i] = $line_time;
            return;
        }
    }
}


//function read_file($row, $selected_id)
//{
//        $file_data = array();
//        
//        $handle = fopen(company_path()."/attendance_files/".$row['unique_name'], "r");
//        
//        if ($handle) {            
//            while (($line = fgets($handle)) !== false)
//            {
//                    $line .= "  ";
//                    $department = read_line($line);
//                    $employee_code = read_line($line);
//                    $employee_name = read_line($line);
//                    $enroll_id = read_line($line);
//                    $date = read_line($line);
//                    $date = change_date_format('DDMMYYYY', $date, 'YYYYMMDD', '-');
//                    
//                    while(strpos($line, ",") > 0){
//                        $r = strpos($line, ",");
//                        $time1 = read_line($line);
//                        if(strlen(trim($time1)) > 0){
//                            add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time1, $file_data);
//                        }
//                    }
//                    
//                    $time2 = read_line($line);
//                    if(strlen(trim($time2)) > 0){
//                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time2, $file_data);
//                    }
////                    $time3 = read_line($line);
////                    if(strlen(trim($time3)) > 0){
////                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time3, $file_data);
////                    }
////                    $time4 = read_line($line);
////                    if(strlen(trim($time4)) > 0){
////                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time4, $file_data);
////                    }
////                    $time5 = read_line($line);
////                    if(strlen(trim($time5)) > 0){
////                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time5, $file_data);
////                    }
////                    $time6 = read_line($line);
////                    if(strlen(trim($time6)) > 0){
////                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time6, $file_data);
////                    }
////                    $time7 = read_line($line);
////                    if(strlen(trim($time7)) > 0){
////                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time7, $file_data);
////                    }
////                    $time8 = read_line($line);
////                    if(strlen(trim($time8)) > 0){
////                        add_to_file_data_line($selected_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time8, $file_data);
////                    }
////                    
//            } 
//            
//            fclose($handle);
//            
//            return $file_data;
//        } 
//        else {
//        // error opening the file.
//        }
//}

function add_to_file_data_line($file_id, $department, $employee_code, $employee_name, $enroll_id, $date, $time, &$file_data)
{
    $file_data_line = array("file_id" => $file_id, 
                        "department" => $department, 
                        "employee_code" => $employee_code, 
                        "employee_name" => $employee_name, 
                        "shift_id" => "",
                        "enroll_id" => $enroll_id, 
                        "date" => $date, 
                        "time" => $time);
    
    $file_data[] = $file_data_line;
}

function display_time_data()
{
    $j = $k = 0;
    
    $d = get_session_variable('import_attendance_organized_data');
    
    start_table(TABLESTYLE, "width=90%");
    
    $th = array("Emp. Code", "Employee Name", 
                    "Shift Name", "Date", 
                    "In", "Time",
                    "NWT", "Times",
                    "Comment", "Rec. Id" );

    table_header($th);
    
    $employee_code = '';
    $employee_name = '';
    $shift_id = '';
    $shift_name = '';

        
    if($d == ''){
        
    }
    else{
        foreach ($d as $row) {
            alt_table_row_color($k);
            if($row['shift_id'] != $shift_id){
                $shift = get_shift_details($row['shift_id']);
                if($shift){
                    $shift_name = $shift['shift_name'];
                }
                else{
                    $shift_name = "Shift details not found";
                }
                $shift_id = $row['shift_id'];
            }
            $row['shift_name'] = $shift_name;

            if($row['employee_code'] != $employee_code){        
                $employee = get_employee($row['employee_code']);
                if($employee){
                    $employee_name = $employee['initials']." ".$employee['last_name']." (".$employee['first_name'].")";
                }
                else{
                    $employee_name = "Employee code ".$row['employee_code']." not found";
                }
                $employee_code = $row['employee_code'];
            }
            $row['employee_name'] = $employee_name;

            display_time_data_row($row);
            
            $j++;
            If ($j == 25)
            {
                $j = 1;
                table_header($th);
            }
        } 
    }

    end_table();

}

function display_time_data_row($row)
{
    $times = '';
    
    $file_id = $row['file_id'];
    $employee_code = $row['employee_code'];
    $prefix = $file_id."_".$employee_code."_";
    //label_cell($row['date'], "align=center");
    label_cell($row['employee_code'], "align=center");
    label_cell($row['employee_name']);
    label_cell($row['shift_name']);
    label_cell($row['date'], "align=center");
    //label_cell($row['in'], "align=center");
    time_cells(null, $prefix."in", substr($row['in'],11,5),3);
//    time_cells(null, $prefix."in", $row['in'],3);
    //label_cell($row['out'], "align=center");
    time_cells(null, $prefix."out", substr($row['out'],11,5),3);
    //label_cell($row['non_working_time'], "align=center");
    time_cells(null, $prefix."non_working_time", $row['non_working_time'],3);
    //label_cell($row['employee_name'], "align=center");
    

    $times = $row['times'];
    label_cell($times);
    
    label_cell($row['message']);
    
    $attendance_rec_id = $row['attendance_rec_id'];
    if($attendance_rec_id == 0){
        $attendance_rec_id = '';
    }
    
    $date_s = strtotime($row["date"]);
    $link = $date_s."~".$attendance_rec_id."~".$employee_code;
            
    if($attendance_rec_id > 0){
        label_cell(get_trans_view_str(ST_ATTENDANCE, $link, $attendance_rec_id), 'align=center');
    }
    else{
        label_cell('');
    }
    //label_cell($attendance_rec_id);
    
//    if($row['passed'] == 1){
//        $passed = "";
//    }
//    else{
//        $passed = "Error";
//    }
//    label_cell($passed, "align=center");
//    label_cell($row['message'], "align=center");
}


function create_attendance_records($selected_id, $payroll_module_parameters)
{
    if(check_import_attendance_data($selected_id) == false){
        return array("success" => false, "message" => "Please save the data first.");
    }
    $a = get_session_variable('import_attendance_organized_data');
    
    foreach($a as $row){
        
//        $date = $row['date'];
        $employee_code = $row['employee_code'];
        
//        $result = get_period_attendance_records($date, $date, $employee_code);
//        $att_row = db_fetch($result);
        
//        $summary = '';
//        $cid = $att_row["cid"]."_".$employee_code;
//        
//        $new_record = calculate_new_record($cid, $employee_code, $att_row, $summary, $payroll_module_parameters);
//        
        $data = '';
        
        $data['aid'] = 0;
        $data['single_record'] = '0';
        $data['selected_id'] = $selected_id;
        $data['mode'] = "ADD_ITEM";

        $data['employee_code'] = $employee_code;

        $data['from_date1'] = sql2date(substr($row['in'],0,10));
        $data['from_time1'] = substr($row['in'],11,5);

        $data['to_date1'] = sql2date(substr($row['out'],0,10));
        $data['to_time1'] =  substr($row['out'],11,5);
        
        // Get the latest values. Do not not know whether the configurations are changed
        $shift_schedule_details = get_shift_schedule_details($data['employee_code'], $row['date']);
        if($shift_schedule_details){
            $data['task_id'] = $shift_schedule_details['task_id'];
            $data['shift_id'] = $shift_schedule_details['shift_id'];
        }

        // Let the sstem to decide on the rate table as per the latest configurations
        $data['rate_table_id'] = 0; 
        
        $data['out_of_office_time1'] = $row['non_working_time'];
        $data['granted_ot_time'] = '00:00';
        $data['deducted_deficit_time'] = '00:00';
        $data['comment'] = '';
                        
        $data['leave_time_code'] = '-1';
        $data['leave_comment'] = '';
        
        $data['err_msg_prefix'] = 0;
        
        $calendar_date_result = get_year_dates($row['date'],$row['date']);
        $calendar_date = db_fetch($calendar_date_result);
        $data['calendar_work_time_code'] = $calendar_date['work_time_code'];
        
        $wa_masg = write_attendance_record ($data);

        update_import_attendance_record($wa_masg, $row['id']);
    }
    
    clear_session_variable('import_attendance_organized_data');
    
    return array("success" => true, "message" => "Data import completed");
   
}


function get_time_string($times)
{
    $time_string = '';
    
    if(is_array($times)){
        $first_element = true;
        foreach ($times as $element){
            if(strlen($time_string) > 1){
                $time_string .= " | ";
            }
            if($first_element){
                $time_string .= $element;
            }
            else{
                $time_string .= " ,".$element;
            }
        }
        
        
        

    }
    else{
        $time_string = $times;
    }
    return $time_string;
}

function save_file_data($selected_id)
{
    $number_of_rows = check_import_attendance_data($selected_id);
    if($number_of_rows > 0){
        $number_of_rows_deleted = delete_saved_records($selected_id);
     }

    if($number_of_rows == 0 || $number_of_rows_deleted > 0){
        $a = get_session_variable('import_attendance_organized_data');
    
        foreach($a as $row){
            $file_id = $row['file_id'];
            $employee_code = $row['employee_code'];
            $prefix = $file_id."_".$employee_code."_";
            $date = $row['date'];
            $shift_id = $row['shift_id'];
            $table_id = $row['table_id'];
            $task_id = $row['task_id'];
            $in = $date." ".get_post($prefix.'in');
            $out = $date." ".get_post($prefix.'out');
            $non_working_time = get_post($prefix.'non_working_time');
            $times = get_time_string($row['times']);            

            add_import_attendance_record($file_id, $employee_code, $date,
                                        $shift_id, $table_id, $task_id,
                                        $in, $out, $non_working_time,
                                        $times);
        }

        clear_session_variable('import_attendance_organized_data');

    }
    else{
        
    }
    
}

function display_rows()
{
	$sql = get_sql_for_attendance_files();
	$cols = array(
	    _("Description") => array('name'=>'description'),
	    _("Filename") => array('name'=>'filename'),
            _("Date Uploaded") => array('name'=>'tran_date', 'type'=>'date'),
	    _("Size") => array('name'=>'filesize'),
	    //_("Filetype") => array('name'=>'filetype'),
	    
	    	array('insert'=>true, 'fun'=>'edit_link'),
	    	array('insert'=>true, 'fun'=>'delete_link')
	    );	
		$table =& new_db_pager('trans_tbl', $sql, $cols);

		$table->width = "60%";

		display_db_pager($table);
}

?>
