<?php

class Attendance extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->db->query('SET SESSION sql_mode = ""');
        $this->load->helper('url');
        $this->load->model(array(
            'Csv_model',
            'Attendance_model'
        ));
        $this->load->library('excel');

        if (!$this->session->userdata('isLogIn'))
            redirect('login');
    }

    public function attendance_form($id = null)
    {

        $this->permission->check_label('attendance_form')->create()->redirect();

        $employee_id = $this->session->userdata('employee_id');
        $date = date("Y-m-d");

        $data['title'] = display('attendance_list');
        $data['addressbook'] = $this->Csv_model->get_addressbook();
        $data['dropdownatn'] = $this->Csv_model->Employeename();
        if (!empty($id)) {
            $data['editdata'] = $this->Csv_model->attendance_editdata($id);
        }
        $data['shift_time'] = $this->Csv_model->employee_shift_time($employee_id);
        $data['flag'] = $this->Attendance_model->check_flag($employee_id);;
        $data['module'] = "employeeattendance";
        $data['page'] = "attendance_form";
        echo Modules::run('template/layout', $data);

    }

    public function attendence_import_csv()
    {


        if (isset($_FILES["upload_csv_file"]["name"]) && $_FILES["upload_csv_file"]["name"]) {

            $path = $_FILES["upload_csv_file"]["tmp_name"];
            $object = PHPExcel_IOFactory::load($path);
            foreach ($object->getWorksheetIterator() as $sale) {

                $highestRow = $sale->getHighestRow();
                $highestColumn = $sale->getHighestColumn();
                $num = 0;
                for ($row = 2; $row <= $highestRow; $row++) {
                    $EmpNo = $sale->getCellByColumnAndRow(0, $row)->getValue();
                    $Date = $sale->getCellByColumnAndRow(5, $row)->getValue();
                    $Clock_In = $sale->getCellByColumnAndRow(9, $row)->getValue();
                    $Clock_Out = $sale->getCellByColumnAndRow(10, $row)->getValue();
                    $shift_time = $sale->getCellByColumnAndRow(29, $row)->getValue();
                    $emp_code = $EmpNo;
                    $clock_in_date = date('Y-m-d', strtotime("$Date"));
                    $clock_out_date = date('Y-m-d', strtotime("$Date"));
                    $clock_in_time = date('H:i:s', strtotime("$Clock_In"));
                    $shift_time = date('H:i:s', strtotime("$shift_time"));
                    $clock_out_time = date('H:i:s', strtotime("$Clock_Out"));


                    $combine_check_in = date('Y-m-d H:i:s', strtotime("$clock_in_date $clock_in_time"));
                    $combine_check_timestamp = strtotime($combine_check_in);
                    $combine_check_out = date('Y-m-d H:i:s', strtotime("$clock_out_date $clock_out_time"));
                    $combine_check_timestamp = strtotime($combine_check_out);
                    $diff = abs(strtotime($combine_check_out) - strtotime($combine_check_in));
                    $hour = $diff / (60 * 60);
                    $hours = $hour - 1;


                    $dateTimeObject1 = date_create($clock_in_time);
                    $dateTimeObject2 = date_create($shift_time);
                    $difference = date_diff($dateTimeObject1, $dateTimeObject2);
                    $minutes = $difference->days * 24 * 60;
                    $minutes += $difference->h * 60;
                    $minutes += $difference->i;

                    $emp_id = $this->Attendance_model->attendance_import($emp_code);
                    $in_date = $this->Attendance_model->attendance_date($emp_id, $clock_in_date);

                    $atten_id = $this->Attendance_model->attendance_id($emp_id);
                    if ($clock_in_time < $shift_time || $minutes < 10) {
                        $late = '0';
                    } else {
                        $late = '1';
                    }

                    if (!empty($emp_id)) {
                        $postRecord[] = [
                            'employee_id' => $emp_id,
                            'check_in_date' => $clock_in_date,
                            'check_out_date' => $clock_out_date,
                            'check_in_time' => $clock_in_time,
                            'check_out_time' => $clock_out_time,
                            'total_hours' => $hours,
                            'employee_shift_time' => $shift_time,
                            'late' => $late,
                        ];
                    }

                    if ($emp_id == $atten_id && $in_date == $clock_in_date) {

                        if ($this->Attendance_model->attendance_update($postRecord[$num++])) {
                            $this->session->set_flashdata('message', display('successfully_saved'));
                        } else {
                            $this->session->set_flashdata('exception', display('please_try_again'));
                        }

                    } else {
                        if ($this->Attendance_model->attendance_insert($postRecord[$num++])) {
                            $this->session->set_flashdata('message', display('successfully_saved'));
                        } else {
                            $this->session->set_flashdata('exception', display('please_try_again'));
                        }

                    }


                }


            }

        }

        redirect("employeeattendance/Attendance/attendance_log");
    }

    public function check_in()
    {

        $employee_id = $this->input->post('employee_id', true);
        $check_in_date = $this->input->post('check_in_date', true);
        $check_in_time = $this->input->post('check_in_time', true);
        $shift_time = $this->input->post('shift_start', true);
        $get_shift_time = $this->Csv_model->employee_shift_time($employee_id);
        $in_date = $this->Attendance_model->attendance_date($employee_id, $check_in_date);
        if ($shift_time == "") {
            $shift_time = $get_shift_time;
        }


        $combine_check_in = date('Y-m-d H:i:s', strtotime("$check_in_date $check_in_time"));
        $combine_check_timestamp = strtotime($combine_check_in);
        $combine_check_out_add = date('Y-m-d H:i:s', strtotime('+9 hour', $combine_check_timestamp));

        $check_out_date = date('Y-m-d', strtotime("$combine_check_out_add"));
        $check_out_time = date('H:i:s', strtotime("$combine_check_out_add"));

        $diff = abs(strtotime($combine_check_out_add) - strtotime($combine_check_in));
        $hour = $diff / (60 * 60);
        $hours = $hour - 1;

        $dateTimeObject1 = date_create($check_in_time);
        $dateTimeObject2 = date_create($shift_time);
        $difference = date_diff($dateTimeObject2, $dateTimeObject1);
        $minutes = $difference->days * 24 * 60;
        $minutes += $difference->h * 60;
        $minutes += $difference->i;

        if ($check_in_time < $shift_time || $minutes < 10 || empty($shift_time) || $shift_time == '00:00:00') {
            $late = '0';
        } else {
            $late = '1';
        }


        $data['check_in'] = (object)$postData = array(
            'employee_id' => $employee_id,
            'check_in_date' => $check_in_date,
            'check_in_time' => $check_in_time,
            'check_out_date' => $check_out_date,
            'check_out_time' => $check_out_time,
            'total_hours' => $hours,
            'flag' => 1,
            'employee_shift_time' => $shift_time,
            'late' => $late,
        );


        if ($check_in_date == $in_date) {
            if ($this->Attendance_model->in_update($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
        } else {
            if ($this->Attendance_model->check_in($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
        }


        redirect("employeeattendance/Attendance/attendance_log");
    }

    public function check_out()
    {
        $employee_id = $this->input->post('employee_id', true);
        $check_out_date = $this->input->post('check_out_date', true);
        $check_out_time = $this->input->post('check_out_time', true);

        $latest_record = $this->Attendance_model->check_flag($employee_id);

        $check_in_date = $latest_record[0]->check_in_date;
        $check_in_time = $latest_record[0]->check_in_time;

        $combine_check_in = date('Y-m-d H:i:s', strtotime("$check_in_date $check_in_time"));
        $combine_check_out = date('Y-m-d H:i:s', strtotime("$check_out_date $check_out_time"));

        $diff = abs(strtotime($combine_check_out) - strtotime($combine_check_in));
        $hour = $diff / (60 * 60);
        if ($hour >= '8.5') {
            $hours = $hour - 1;
        } else {
            $hours = $hour;
        }


        $data['check_out'] = (object)$postData = array(
            'att_id' => $latest_record[0]->att_id,
            'employee_id' => $employee_id,
            'check_out_date' => $check_out_date,
            'check_out_time' => $check_out_time,
            'total_hours' => $hours,
            'flag' => 0,
        );

        if ($this->Attendance_model->check_out($postData)) {
            $this->session->set_flashdata('message', display('successfully_saved'));
        } else {
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect("employeeattendance/Attendance/attendance_log");

    }

    public function attendance_log()
    {
        if (!$this->session->userdata('isAdmin') == 1) {
            redirect("employeeattendance/Attendance/employee_attendance_log");
        } else {

            $this->form_validation->set_rules('employee_id', 'Employee Name', 'required');
            $this->form_validation->set_rules('start_date', 'Start Date', 'required');
            $this->form_validation->set_rules('end_date', 'End Date', 'required');

            $employee_id = $this->input->post('employee_id', true);
            $start_date = $this->input->post('start_date', true);
            $end_date = $this->input->post('end_date', true);

            if ($this->form_validation->run() === true) {
                $data['title'] = "Attendance Logs";
                $data['module'] = "employeeattendance";
                $data['filter_enable'] = 1;
                $data['emplist'] = $this->Attendance_model->emp_list_dropdown();
                $data['mang'] = $this->Attendance_model->get_filter_attendance($employee_id, $start_date, $end_date);
                $data['overtimes'] = $this->Attendance_model->get_filter_admin_overtime($employee_id, $start_date, $end_date);
                $data['page'] = "attendance_log";
                echo Modules::run('template/layout', $data);
            } else {
                $data['title'] = "Attendance Logs";
                $data['module'] = "employeeattendance";
                $data['emplist'] = $this->Attendance_model->emp_list_dropdown();
                $data['mang'] = $this->Attendance_model->get_all_attendance();
                $data['overtimes'] = $this->Attendance_model->get_admin_overtime();
                $data['page'] = "attendance_log";
                echo Modules::run('template/layout', $data);
            }
        }
    }

    public function employee_attendance_log()
    {
        /*----------FORM VALIDATION RULES----------*/
        $this->form_validation->set_rules('start_date', 'Start Date', 'required');
        $this->form_validation->set_rules('end_date', 'End Date', 'required');

        $start_date = $this->input->post('start_date', true);
        $end_date = $this->input->post('end_date', true);
        $id = $this->session->userdata('employee_id');

        if ($this->form_validation->run() === true) {
            $data['employee_id'] = $this->session->userdata('employee_id');
            $data['title'] = "Attendance Log";
            $data['module'] = "employeeattendance";
            $data['mang'] = $this->Attendance_model->get_filter_employee_attendance($data['employee_id'], $start_date, $end_date);
            $data['ovt_details'] = $this->Attendance_model->get_filter_overtime_details($data['employee_id'], $start_date, $end_date);
            $data['page'] = "employee_attendance_log";
            echo Modules::run('template/layout', $data);
        } else {
            $data['employee_id'] = $this->session->userdata('employee_id');
            $data['title'] = "Attendance Log";
            $data['module'] = "employeeattendance";
            $data['mang'] = $this->Attendance_model->get_employee_attendance($data['employee_id']);
            $data['ovt_details'] = $this->Attendance_model->get_overtime_details($data['employee_id']);
            $data['page'] = "employee_attendance_log";
            echo Modules::run('template/layout', $data);
        }

    }

    public function team_attendance()
    {
        $this->form_validation->set_rules('employee_id', 'Employee Name', 'required');
        $this->form_validation->set_rules('start_date', 'Start Date', 'required');
        $this->form_validation->set_rules('end_date', 'End Date', 'required');

        $employee_id = $this->input->post('employee_id', true);
        $start_date = $this->input->post('start_date', true);
        $end_date = $this->input->post('end_date', true);

        if ($this->form_validation->run() === true) {
            $data['employee_id'] = $this->session->userdata('employee_id');
            $data['title'] = "Attendance Log";
            $data['module'] = "employeeattendance";
            $data['filter_enable'] = 1;
            $data['emplist'] = $this->Attendance_model->emp_team_list_dropdown($data['employee_id']);
            $data['mang'] = $this->Attendance_model->get_filter_attendance($employee_id, $start_date, $end_date);
            $data['ovt_details'] = $this->Attendance_model->get_filter_overtime_details($employee_id, $start_date, $end_date);
            $data['page'] = "team_attendance";
            echo Modules::run('template/layout', $data);
        } else {
            $data['employee_id'] = $this->session->userdata('employee_id');
            $data['title'] = "Attendance Log";
            $data['module'] = "employeeattendance";
            $data['emplist'] = $this->Attendance_model->emp_team_list_dropdown($data['employee_id']);
            $data['mang'] = $this->Attendance_model->get_team_attendance($data['employee_id']);
            $data['ovt_details'] = $this->Attendance_model->get_team_overtime_details($data['employee_id']);
            $data['page'] = "team_attendance";
            echo Modules::run('template/layout', $data);
        }
    }

    public function edit_attendance($id)
    {
        $data['title'] = "Attendance Edit";
        $data['module'] = "employeeattendance";
        $data['record'] = $this->Attendance_model->get_attendance_record($id);
        $data['page'] = "edit_attendance";
        echo Modules::run('template/layout', $data);
    }

    public function check_in_update()
    {

        $att_id = $this->input->post('att_id', true);
        $employee_id = $this->input->post('employee_id', true);
        $check_in_date = $this->input->post('check_in_date', true);
        $check_in_time = $this->input->post('check_in_time', true);
        $employee_shift_time = $this->input->post('employee_shift_time', true);
        $shift_t = $this->Csv_model->employee_shift_time($employee_id);


        $dateTimeObject1 = date_create($check_in_time);
        $dateTimeObject2 = date_create($shift_t);
        $difference = date_diff($dateTimeObject1, $dateTimeObject2);
        $minutes = $difference->days * 24 * 60;
        $minutes += $difference->h * 60;
        $minutes += $difference->i;

        if($check_in_time < $employee_shift_time){
            $late = 0;
        }else{
            if($minutes < 10){
                $late = 0;
            }else{
                $late = 1;
            }
        }

        if ($minutes > 10) {
            $data['check_in'] = (object)$postData = array(
                'att_id' => $att_id,
                'employee_id' => $employee_id,
                'check_in_date' => $check_in_date,
                'check_in_time' => $check_in_time,
                'employee_shift_time' => $employee_shift_time,
                'flag' => 1,
                'late' => $late,
            );

            if ($this->Attendance_model->check_in_update($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }

        } else {
            $data['check_in'] = (object)$postData = array(
                'att_id' => $att_id,
                'employee_id' => $employee_id,
                'check_in_date' => $check_in_date,
                'check_in_time' => $check_in_time,
                'flag' => 1,
                'late' => 0,
            );

            if ($this->Attendance_model->check_in_update($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
        }

        redirect("employeeattendance/Attendance/attendance_log");
    }

    public function check_out_update()
    {
        $att_id = $this->input->post('att_id', true);
        $employee_id = $this->input->post('employee_id', true);
        $check_out_date = $this->input->post('check_out_date', true);
        $check_out_time = $this->input->post('check_out_time', true);

        $latest_record = $this->Attendance_model->get_current_record($att_id);

        $check_in_date = $latest_record[0]->check_in_date;
        $check_in_time = $latest_record[0]->check_in_time;

        $combine_check_in = date('Y-m-d H:i:s', strtotime("$check_in_date $check_in_time"));
        $combine_check_out = date('Y-m-d H:i:s', strtotime("$check_out_date $check_out_time"));

        $diff = abs(strtotime($combine_check_out) - strtotime($combine_check_in));
        $hour = $diff / (60 * 60);
        if ($hour >= '8.5') {
            $hours = $hour - 1;
        } else {
            $hours = $hour;
        }


        $data['check_out'] = (object)$postData = array(
            'att_id' => $latest_record[0]->att_id,
            'employee_id' => $employee_id,
            'check_out_date' => $check_out_date,
            'check_out_time' => $check_out_time,
            'total_hours' => $hours,
            'flag' => 0,
        );

        if ($this->Attendance_model->check_out_update($postData)) {
            $this->session->set_flashdata('message', display('successfully_saved'));
        } else {
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect("employeeattendance/Attendance/attendance_log");
    }
}