<?php

function display_open_approved_ot_filtering_controls() {
    start_table();
        date_cells("Cutoff Date:", 'cutoff_date', '', null, null, null, null, null, true);
        submit_cells('Refresh', 'Refresh');
    end_table(2);
}

function open_ot_records($cutoff_date_) {
    $cutoff_date = date2sql($cutoff_date_);
    $num_selected_recs = 0;
    
    $emp_result = get_approved_and_calculated_ot_employees($cutoff_date);
        while ($myrow = db_fetch($emp_result)) {
            $msg = open_employee_ot_records($myrow["employee_code"], $cutoff_date,$num_selected_recs);
                if ($msg['success'] === false) {
                    return $msg;
                }
        }
        
        if (! ($num_selected_recs > 0)) {
            return array('success' => false, 'message' => "At least one record should be selected before opening.");
        }
        
        return array('success' => true, 'message' => "Selected OT records have been reopened.");
}

function open_employee_ot_records($employee_code, $cutoff_date, &$num_selected_recs) {
    $result = get_approved_and_calculated_employee_ot_records($employee_code, $cutoff_date);
        while ($myrow = db_fetch($result)) {
            $rec_id = $myrow["id"];
            $from_date_time1 = $myrow["from_date_time1"];

            if ((isset($_POST["selected_".$rec_id."_".$from_date_time1]))) {
                if ($_POST["selected_".$rec_id."_".$from_date_time1] == true) {

                    $payroll_run_id = $myrow["calculated_payroll_run_id"];
                    
                    $ot_status_code = $myrow['ot_status_code'];
                        if (! in_array($ot_status_code, array('A', 'L', 'C'))) {
                            if (in_array($ot_status_code, array('U'))) {
                                return array('success' => false, 'message' => "Record #$rec_id is already opened by another user.");
                            } else {
                                return array('success' => false, 'message' => "Record #$rec_id approval status is already changed by another user.");
                            }
                        }
                    
                    begin_transaction();
                    
                        if ($payroll_run_id > 0) {
                            $msg = check_and_delete_payroll_run_details($payroll_run_id);
                                if ($msg['success'] === false) {
                                    cancel_transaction();

                                    return $msg;
                                }
                        }
                    
                        $naf_rows = update_approved_or_calculated_attendance_ot_status_code($rec_id, 'U');
                            if ($naf_rows != 1) {
                                cancel_transaction();

                                return array('success' => false, 'message' => "Could not upate Record #$rec_id.");
                            }
                    
                    commit_transaction();
                    
                    $num_selected_recs++;
                }
            }
        }
        
        return array('success' => true, 'message' => "");
}

function display_approved_and_calculated_ot_records($cutoff_date_, &$show_button=false) {
    $cutoff_date = date2sql($cutoff_date_);
    
    $emp_result = get_approved_and_calculated_ot_employees($cutoff_date);
        while ($myrow = db_fetch($emp_result)) {
            display_approved_and_calculated_ot_employee_records($myrow["employee_code"], $cutoff_date);
            
            $show_button = true;
        }
}

function display_approved_and_calculated_ot_employee_records($employee_code, $cutoff_date) { 
    $employee_name = get_employee_formatted_long_name($employee_code);
        display_heading2($employee_name);   br();
        
        start_table(TABLESTYLE, "width=80%");
        $th = array(_("Id"), _("Date"), _("In"), _("Out"), _("Entered Duration"), _("Shift"), _("Calculated OT Hours"), _("OT Hours"), _("Rate Table"), 
                    _("Status"), _(""));

        table_header($th);

            $k = $j = 0; //row colour counter
            $rec_count = $hour_count_s = $total_ot_hours_granted_s = $total_ot_hours_calcuklated_s = $total_df_hours_deducted_s = 0;

        $result = get_approved_and_calculated_employee_ot_records($employee_code, $cutoff_date);
            while ($myrow = db_fetch($result)) {
                alt_table_row_color($k);
                
                    $rec_id = $myrow["id"];
                    $from_date_time1 = $myrow["from_date_time1"];
                    $_POST['date'.$rec_id] = sql2date($myrow["from_date_time1"]);
                    $date_s = strtotime($myrow["from_date_time1"]);
                    label_cell($rec_id);
                    $link = $date_s."~".$rec_id."~".$employee_code;
                    label_cell(get_trans_view_str(ST_ATTENDANCE, $link, sql2date($myrow["from_date_time1"]).", ".date('l',strtotime($myrow['from_date_time1']))));
                    label_cell(sql2time($myrow["from_date_time1"]), "align=center");
                    label_cell(sql2time($myrow["to_date_time1"]), "align=center");

                    $from1_s = strtotime($myrow["from_date_time1"]);
                    $to1_s = strtotime($myrow["to_date_time1"]);
                    $from2_s = strtotime($myrow["from_date_time2"]);
                    $to2_s = strtotime($myrow["to_date_time2"]);

                    $d1 = $to1_s - $from1_s;
                    $d2 = $to2_s - $from2_s;

                    $total_entered_duration_s = $d1 + $d2; 

                    $total_entered_duration = "00:00:00";
                    if ($total_entered_duration_s >= 0) {
                        $total_entered_duration = gmdate("H:i:s", $total_entered_duration_s);
                    }

                    $hour_count_s += $total_entered_duration_s;
                    label_cell(substr($total_entered_duration, -8, 5), "align=center");
                    label_cell($myrow["shift_name"], "align=left");
                    label_cell(substr($myrow['calculated_ot_time'], 0, 5), "align=center");

                    set_post_not_set_string("granted_ot_time".$rec_id, substr($myrow['granted_ot_time'], 0, 5));
                    label_cell($_POST["granted_ot_time".$rec_id], "align=center");
                    label_cell($myrow["rate_table_name"], "align=center");
                    label_cell($myrow["ot_status_name"], "align=center");
                        
                    if (in_array($myrow["ot_status_code"], array("A", "L"))) {
                        check_cells('', 'selected_'.$rec_id."_".$from_date_time1, null, false, false, 'align=center');
                    } else {
                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    }
                    
                    end_row();

                    $rec_count++;

                    $cal_ot_s = strtotime($myrow["calculated_ot_time"]);
                    $cal_ot_t = get_time_array($myrow["calculated_ot_time"]);
                    $cal_ot_s = $cal_ot_t[0]*3600 + $cal_ot_t[1]*60 + $cal_ot_t[2];
                    $total_ot_hours_calcuklated_s += $cal_ot_s;     

                    $ot_s = strtotime($_POST["granted_ot_time".$rec_id]);
                    $ot_t = get_time_array($_POST["granted_ot_time".$rec_id].":00");
                    $ot_s = $ot_t[0]*3600 + $ot_t[1]*60 + $ot_t[2];
                    $total_ot_hours_granted_s += $ot_s;     

                    $df_s = strtotime($myrow["deducted_deficit_time"]);
                    $df_t = get_time_array($myrow["deducted_deficit_time"]);
                    $ot_s = $df_t[0]*3600 + $df_t[1]*60 + $df_t[2];
                    $total_df_hours_deducted_s += $ot_s; 
                }

                start_row();
                    label_cell('', "colspan=3 align=right");
                    label_cell("<b>".'Total'."<b>", "colspan=3 align=right");
                    label_cell("<b>".convert_to_hours($total_ot_hours_calcuklated_s)."</b>", "colspan=1 align=center");
                    label_cell("<b>".convert_to_hours($total_ot_hours_granted_s)."</b>", "colspan=1 align=left");
                    label_cell(_(""), "colspan=3");
                end_row();

                $rec_count = $hour_count = 0;
        
    end_table(2);
}

function convert_to_hours($s) {
    $h = floor($s/3600); 
    $h = str_pad($h, 2, '0', STR_PAD_LEFT);

    $m = number_format2((($s/3600) - $h) * 60,0); 
    $m = str_pad($m, 2, '0', STR_PAD_LEFT);

    $hm = $h.":".$m;

    return $hm;
}

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

    if (! isset($_POST['search_employee_code'])) {
        $_POST['search_employee_code'] = "";
    } else {
        $_POST['search_employee_code'] = $_POST['search_employee_code'];
    }

    $y = date("Y", strtotime($date));
    $m = date("m", strtotime($date));
    $d = date("d", strtotime($date));

    $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 +7 days'.$week_start_date));

    switch ($_POST['search_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." 23:59:59";

    $_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'); 
    
    $_POST['filtering_employee_code'] = $_POST['search_employee_code'];
    hidden('filtering_employee_code'); 
}

function initialize_values($id) {
    $_POST['id'.$id] = "";
    $_POST['date'.$id] = "";
    $_POST['work_time_name'.$id] = "";
    $_POST['date'.$id] = "";
    $_POST['work_time_name'.$id] = "";
    $_POST['from_date_time'.$id] = "";
    $_POST['to_date_time'.$id] = "";
    $_POST['duration'.$id] = "";
    $_POST['comment'.$id] = "";
    $_POST['leave_status_name'.$id] = "";
    $_POST['real_name'.$id] = "";
    $_POST['created_on'.$id] = "";

    $_POST['rec_type'.$id] = "";
}