<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Home extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->db->query('SET SESSION sql_mode = ""');
        $this->load->model('home_model');
        $this->load->model('Country_model');
        $this->load->model('rewardpoint/rewardpoints_model');

        if (!$this->session->userdata('isLogIn')) {
            redirect('login');
            if ($this->session->userdata('login_status') != '1') {
                redirect('dashboard/home/setNewPassword');
            }
        }

    }

    function index()
    {
        //Getting permission_exception from Permission library and showing exception message..
        if ($this->session->userdata('isLogIn') && $this->session->userdata('permission_exception')) {

            $this->session->unset_userdata('permission_exception');
            $this->session->set_flashdata('exception', "You do not have permission to access. Please contact with administrator.");

        }
        //End of getting permission exception
        $data['title'] = "Dashboard";
//        $data['ttle_empl'] = $this->db->count_all('employee_history');
        $data['present_empl'] = $this->home_model->count_attent_employee();
        $data['male'] = $this->home_model->count_male_employee();
        $data['female'] = $this->home_model->count_female_employee();
        $data['todys_leave'] = $this->home_model->leave_employee()->leave_total;
        $last_30days = $data['last_30days'] = $this->home_model->last_thirtydays_attendance();

        $attendancelabel = '';
        foreach ($last_30days as $alldays) {

            if (!empty($alldays['mydate'])) {
                $attendancelabel .= $alldays['mydate'] . ",";
            } else {
                $attendancelabel .= ",";
            }
        }
        $attendancedata = '';
        foreach ($last_30days as $alldays) {
            $value = $this->home_model->count_30daysattendance($alldays['mydate']);
            if (!empty($value)) {
                $attendancedata .= $value . ",";
            } else {
                $attendancedata .= ",";
            }
        }
        $tlvmonth = '';
        $month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        for ($i = 0; $i <= 11; $i++) {
            $tlvmonth .= $month[$i] . ',';
        }

        $data['month'] = $tlvmonth;
        $recruitedemployee = '';
        for ($i = 1; $i <= 12; $i++) {
            $hired = $this->home_model->hired_employee_current_year($i);
            if (!empty($hired)) {
                $recruitedemployee .= $hired . ",";
            } else {
                $recruitedemployee .= ",";
            }
        }
        $data['recruitedemp'] = $recruitedemployee;
        $data['attendanclabel'] = $attendancelabel;
        $data['attendancdata'] = $attendancedata;
        $precentage_departments = $this->home_model->percentage_employee_by_department();
        foreach ($precentage_departments as $per){
            if (!empty($per)) {

                if($per->department_name == "") {
                    $data['per_dep_pie'] .= "{ name : 'Other', y: ".$per->per."},";
                }else{
                    $data['per_dep_pie'] .= "{ name : '".$per->department_name."', y: ".$per->per."},";
                }

            }
        }

        $absent_15days = $this->home_model->last_15days_absent();
        $totalabsentfftdayslabel = '';
        foreach ($absent_15days as $allabdate) {
            $abdate = $allabdate['mydate'];
            if (!empty($abdate)) {
                $totalabsentfftdayslabel .= $abdate . ",";
            } else {
                $totalabsentfftdayslabel .= ",";
            }
        }

        $totalabsentfftdaysval = '';
        foreach ($absent_15days as $allabdate) {
            $absbalue = $this->home_model->count_15daysabsent($allabdate['mydate']);
            if (!empty($absbalue)) {
                $totalabsentfftdaysval .= $absbalue . ",";
            } else {
                $totalabsentfftdaysval .= ",";
            }
        }
        $data['abdfftdaylabel'] = $totalabsentfftdayslabel;
        $data['abdfftdayval'] = $totalabsentfftdaysval;

        $loanstatisticpayment = '';
        for ($i = 1; $i <= 12; $i++) {
            $loanpayment = $this->home_model->givenloan($i);
            if (!empty($loanpayment)) {
                $loanstatisticpayment .= $loanpayment . ",";
            } else {
                $loanstatisticpayment .= ",";
            }
        }

        $loanstatisticreceived = '';
        for ($i = 1; $i <= 12; $i++) {
            $loanreceived = $this->home_model->receivedloan($i);
            if (!empty($loanreceived)) {
                $loanstatisticreceived .= $loanreceived . ",";
            } else {
                $loanstatisticreceived .= ",";
            }
        }
        $awardedemployee = '';
        for ($i = 1; $i <= 12; $i++) {
            $awarded = $this->home_model->awarded_person($i);
            if (!empty($awarded)) {
                $awardedemployee .= $awarded . ",";
            } else {
                $awardedemployee .= ",";
            }
        }
        $data['loanstatisticpayment'] = $loanstatisticpayment;
        $data['loanstatisticreceived'] = $loanstatisticreceived;
        $data['awardedempl'] = $awardedemployee;
        $data['notice'] = $this->home_model->notice_list();
        $data['lnamountpaid'] = $this->home_model->paidloanamnt();
        $data['lnreceiveamount'] = $this->home_model->receiveloanamnt();
        $data['latestrecruitedemple'] = $this->home_model->latest_recuited_employee();
        $data['allEmployeeData'] = $this->home_model->getAllEmployeeData();
        $data['employee_points'] = $this->rewardpoints_model->dshboard_employee_points();
        $data['employee_box_data'] = $this->rewardpoints_model->get_employee_box_data();

        $today = date('Y-m-d');
        $two_week=Date('Y-m-d', strtotime('+14 days'));
        $start_date = date('Y-m-01');
        $employee_id = $this->session->userdata('employee_id');

        $startDate = new DateTime($start_date);
        $endDate = new DateTime($today);
        $difference = $endDate->diff($startDate);
        $total_days =  $difference->format("%a") + 1;
        $ss = 0;
        for($i=0 ; $i < $total_days ;$i++) {
            $xmasDay = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($start_date)));
            $day = date("D", strtotime($xmasDay));
            if($day == "Sat" || $day == "Sun"){
                $ss++;
            }
        }
        $working_days = $total_days - $ss;

        $data['this_month_employee_present'] = $this->home_model->this_month_employee_present($employee_id,$start_date,$today);
        $data['this_month_employee_absent'] = $working_days - $data['this_month_employee_present'][0]->present;
        $data['today_attendance_status'] = $this->home_model->today_attendance_status($employee_id,$today);
        $data['this_month_late_comings'] = $this->home_model->this_month_late_comings($employee_id,$start_date,$today);
        $data['this_month_absent_dates'] = $this->home_model->this_month_absent_dates($employee_id);

        $absent_dates = array();
        $k=0;
        for($i=0 ; $i < $total_days  ;$i++) {
            $date = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($start_date)));
            $day = date("D", strtotime($date));
            $full_date = date("Y-m-d", strtotime($date));
            if($full_date != $data['this_month_absent_dates'][$k]->check_in_date){
                if($day != "Sat" && $day != "Sun"){
                    $absent_dates[] = $full_date;
                }
            }else{
                $k++;
            }
        }
        $data['this_month_absent_dates'] = $absent_dates;
        $isManager = $this->home_model->check_manager($employee_id);
        if($isManager[0]->is_manager) {
            $data['teit'] = $this->home_model->total_employee_in_team($employee_id);
            $data['tepit'] = $this->home_model->total_employee_present_in_team($employee_id,$today);
            $data['teait'] = ($data['teit'][0]->total_emp) - ($data['tepit'][0]->present);
            $data['lcwm'] = $this->home_model->late_comers_with_mimutes($employee_id,$today);
            $data['tpl'] = $this->home_model->team_pending_leaves($employee_id);
            $data['tpr'] = $this->home_model->team_pending_resignation($employee_id);
            $data['otpr'] = $this->home_model->over_time_pending_request($employee_id);
            $data['is_manager']=$isManager[0]->is_manager;
        }

//        Inam Start
        $data['tae'] = $this->home_model->total_active_employees();
        $data['tpe'] = $this->home_model->total_present_employee($today);
        $data['ttlc'] = $this->home_model->today_total_late_comers($today);
        $data['tlcwm_a'] = $this->home_model->late_comers_with_mimutes_admin($today);
        $data['pl_a'] = $this->home_model->pending_leaves_admin();
        $data['otpr_a'] = $this->home_model->over_time_pending_request_admin($employee_id);
        $data['ucec_a'] = $this->home_model->upcomming_employee_confirmations($today,$two_week);

        $data['ecd_a'] = $this->home_model->employee_confirmations_due($today,$two_week);
        $data['letm_a'] = $this->home_model->leaving_employees_this_month($start_date,$today);
        $data['pebd_a'] = $this->home_model->percentage_employee_by_department();
//        print_r($data['pebd_a']);
//        Inam END

        $data['module'] = "dashboard";
        $data['page'] = "home/index";
        echo Modules::run('template/layout', $data);
    }

    public function setNewPassword()
    {
        $this->form_validation->set_rules('password', 'Password', 'required|max_length[50]');

        if ($this->form_validation->run()) {
            $email = $this->session->userdata('email');
            $new_password = md5($this->input->post('password', true));
            $employee_id = $this->session->userdata('employee_id');
            $data['user'] = (object)$postData = [
                'email' => $email,
                'password' => $new_password,
                'login_status' => 1,
            ];
            $data['employee'] = (object)$postEmpData = [
                'employee_id' => $employee_id,
                'password' => $new_password,
            ];
            if ($this->home_model->update_password($postData)) {
                $this->home_model->update_emp_password($postEmpData);
                $this->session->set_flashdata('message', 'Password has been reset');
                redirect('dashboard/Auth/logout');
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
        }

        $data['title'] = "Please set new password";
        $data['module'] = "dashboard";
        $data['page'] = "home/new_password";
        $data['id'] = $this->session->userdata('id');
        $this->load->view('home/new_password', $data);
    }


    public function profile()
    {
        $data['title'] = "Profile";
        $data['module'] = "dashboard";
        $data['page'] = "home/profile";
        $id = $this->session->userdata('id');//
        $emp_id = $this->session->userdata('employee_id');//
        $data['user'] = $this->home_model->profile($id);
        $data['row'] = $this->home_model->employee_data($emp_id);
        $data['prob_evaluation'] = $this->home_model->prob_evaluation($data['row']->evaluation_by);
        $data['edu'] = $this->home_model->updateedu($emp_id);
        $data['benifit'] = $this->home_model->benifit($emp_id);
        $data['award'] = $this->home_model->award($emp_id);
        $data['perform'] = $this->home_model->performance($emp_id);
        $data['salarylog'] = $this->home_model->salary_log_single($emp_id);
        $data['warnings'] = $this->home_model->get_warnings($emp_id);
        echo Modules::run('template/layout', $data);
    }

    public function setting()
    {
        $data['title'] = "Profile Setting";
        $id = $this->session->userdata('id');
        /*-----------------------------------*/
        $this->form_validation->set_rules('firstname', 'First Name', 'required|max_length[50]');
        $this->form_validation->set_rules('lastname', 'Last Name', 'required|max_length[50]');
        #------------------------#
        $this->form_validation->set_rules('email', 'Email Address', "required|valid_email|max_length[100]");
        /*---#callback fn not supported#---*/
        #------------------------#
        $this->form_validation->set_rules('password', 'Password', 'max_length[32]|md5');
        $this->form_validation->set_rules('about', 'About', 'max_length[1000]');
        /*-----------------------------------*/
        $config['upload_path'] = './assets/img/user/';
        $config['allowed_types'] = 'gif|jpg|png';

        $this->load->library('upload', $config);

        if ($this->upload->do_upload('image')) {
            $data = $this->upload->data();
            $image = $config['upload_path'] . $data['file_name'];

            $config['image_library'] = 'gd2';
            $config['source_image'] = $image;
            $config['create_thumb'] = false;
            $config['maintain_ratio'] = TRUE;
            $config['width'] = 115;
            $config['height'] = 90;
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();
            $this->session->set_flashdata('message', "Image Upload Successfully!");
        }


        /*-----------------------------------*/
        $data['user'] = (object)$userData = array(
            'id' => $this->input->post('id'),
            'firstname' => $this->input->post('firstname', true),
            'lastname' => $this->input->post('lastname', true),
            'email' => $this->input->post('email', true),
            'password' => (!empty($this->input->post('password', true)) ? md5($this->input->post('password', true)) : $this->input->post('oldpassword', true)),
            'about' => $this->input->post('about', true),
            'image' => (!empty($image) ? $image : $this->input->post('old_image'))
        );

        /*-----------------------------------*/
        if ($this->form_validation->run()) {

            $old_email = $this->input->post('old_email', true);

            if ($old_email != $this->input->post('email', true)) {
                $this->session->set_flashdata('exception', 'Please contact with admin to change email from Employee section !');
                redirect("dashboard/home/setting");

            }

            if ($image === false) {
                $this->session->set_flashdata('exception', display('invalid_logo'));
            }


            if ($this->home_model->setting($userData)) {

                $this->session->set_userdata(array(
                    'fullname' => $this->input->post('firstname', true) . ' ' . $this->input->post('lastname', true),
                    'email' => $this->input->post('email', true),
                    'image' => (!empty($image) ? $image : $this->input->post('old_image'))
                ));


                $this->session->set_flashdata('message', display('update_successfully'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("dashboard/home/setting");

        } else {
            $data['module'] = "dashboard";
            $data['page'] = "home/profile_setting";
            if (!empty($id))
                $data['user'] = $this->home_model->profile($id);
            echo Modules::run('template/layout', $data);
        }
    }

    public function edit_profile()
    {

        $this->form_validation->set_rules('first_name', display('first_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('last_name', display('last_name'), 'required|max_length[50]');

        $this->load->library('myupload');

        $resume_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'resume'
        );

        $id_card_front_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'id_card_front'
        );

        $id_card_back_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'id_card_back'
        );

        $signed_nda_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'signed_nda'
        );

        $signed_offer_letter_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'signed_offer_letter'
        );

        $master_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'master_attachment'
        );

        $bachelors_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'bachelors_attachment'
        );

        $inter_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'inter_attachment'
        );

        $matric_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'matric_attachment'
        );

        $old_resume = $this->input->post('old_resume');
        $old_id_card_front = $this->input->post('old_id_card_front');
        $old_id_card_back = $this->input->post('old_id_card_back');
        $old_signed_nda = $this->input->post('old_signed_nda');
        $old_signed_offer_letter = $this->input->post('old_signed_offer_letter');
        $old_master_attachment = $this->input->post('old_master_attachment');
        $old_bachelors_attachment = $this->input->post('old_bachelors_attachment');
        $old_inter_attachment = $this->input->post('old_inter_attachment');
        $old_matric_attachment = $this->input->post('old_matric_attachment');

        $p_e_company_name = $this->input->post('p_e_company_name', true);
        $p_e_start_date = $this->input->post('p_e_start_date', true);
        $p_e_end_date = $this->input->post('p_e_end_date', true);
        $p_e_skill_name = $this->input->post('p_e_skill_name', true);
        $p_e_designation = $this->input->post('p_e_designation', true);
        $p_e_location = $this->input->post('p_e_location', true);

        $c_t_name = $this->input->post('c_t_name', true);
        $c_t_start_date = $this->input->post('c_t_start_date', true);
        $c_t_end_date = $this->input->post('c_t_end_date', true);
        $c_t_institute = $this->input->post('c_t_institute', true);
        $c_t_location = $this->input->post('c_t_location', true);

        /*-----------------------------------*/
        $config['upload_path'] = './assets/img/user/';
        $config['allowed_types'] = 'gif|jpg|png';
        $this->load->library('upload', $config);
        if ($this->upload->do_upload('image')) {
            $data = $this->upload->data();
            $image = $config['upload_path'] . $data['file_name'];

            $config['image_library'] = 'gd2';
            $config['source_image'] = $image;
            $config['create_thumb'] = false;
            $config['maintain_ratio'] = TRUE;
            $config['width'] = 115;
            $config['height'] = 90;
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();
            $this->session->set_flashdata('message', "Image Upload Successfully!");
        }

        $employee_id = $this->session->userdata('employee_id');

        if ($this->form_validation->run() === true) {

            if ($resume_file == null && $old_resume != null) {
                $resume = $old_resume;
            } elseif ($resume_file == null && $old_resume == null) {
                $resume = '';
            } else {
                $resume = base_url() . $resume_file;
            }

            if ($id_card_front_file == null && $old_id_card_front != null) {
                $id_card_front = $old_id_card_front;
            } elseif ($id_card_front_file == null && $old_id_card_front == null) {
                $id_card_front = '';
            } else {
                $id_card_front = base_url() . $id_card_front_file;
            }

            if ($id_card_back_file == null && $old_id_card_back != null) {
                $id_card_back = $old_id_card_back;
            } elseif ($id_card_back_file == null && $old_id_card_back == null) {
                $id_card_back = '';
            } else {
                $id_card_back = base_url() . $id_card_back_file;
            }

            if ($signed_nda_file == null && $old_signed_nda != null) {
                $signed_nda = $old_signed_nda;
            } elseif ($signed_nda_file == null && $old_signed_nda == null) {
                $signed_nda = '';
            } else {
                $signed_nda = base_url() . $signed_nda_file;
            }

            if ($signed_offer_letter_file == null && $old_signed_offer_letter != null) {
                $signed_offer_letter = $old_signed_offer_letter;
            } elseif ($signed_offer_letter_file == null && $old_signed_offer_letter == null) {
                $signed_offer_letter = '';
            } else {
                $signed_offer_letter = base_url() . $signed_offer_letter_file;
            }

            if ($master_attachment_file == null && $old_master_attachment != null) {
                $master_attachment = $old_master_attachment;
            } elseif ($master_attachment_file == null && $old_master_attachment == null) {
                $master_attachment = '';
            } else {
                $master_attachment = base_url() . $master_attachment_file;
            }
            if ($bachelors_attachment_file == null && $old_bachelors_attachment != null) {
                $bachelors_attachment = $old_bachelors_attachment;
            } elseif ($bachelors_attachment_file == null && $old_bachelors_attachment == null) {
                $bachelors_attachment = '';
            } else {
                $bachelors_attachment = base_url() . $bachelors_attachment_file;
            }
            if ($inter_attachment_file == null && $old_inter_attachment != null) {
                $inter_attachment = $old_inter_attachment;
            } elseif ($inter_attachment_file == null && $old_inter_attachment == null) {
                $inter_attachment = '';
            } else {
                $inter_attachment = base_url() . $inter_attachment_file;
            }
            if ($matric_attachment_file == null && $old_matric_attachment != null) {
                $matric_attachment = $old_matric_attachment;
            } elseif ($matric_attachment_file == null && $old_matric_attachment == null) {
                $matric_attachment = '';
            } else {
                $matric_attachment = base_url() . $matric_attachment_file;
            }

            $data['employee'] = (object)$postData = [
                'employee_id' => $this->input->post('employee_id', true),
                'first_name' => $this->input->post('first_name', true),
                'middle_name' => $this->input->post('middle_name', true),
                'last_name' => $this->input->post('last_name', true),
                'personal_email' => $this->input->post('personal_email', true),
                'password' => (!empty($this->input->post('password', true)) ? md5($this->input->post('password', true)) : $this->input->post('old_password', true)),
                'phone' => $this->input->post('phone', true),
                'state' => $this->input->post('state', true),
                'city' => $this->input->post('city', true),
                'zip' => $this->input->post('zip', true),
                'emp_exp_start_date' => $this->input->post('emp_exp_start_date', true),
                'emp_exp_end_date' => $this->input->post('emp_exp_end_date', true),
                'dob' => $this->input->post('dob', true),
                'marital_status' => $this->input->post('marital_status', true),
                'ethnic_group' => $this->input->post('ethnic_group', true),
                'shift_start' => $this->input->post('shift_start', true),
                'shift_end' => $this->input->post('shift_end', true),
                'duty_type' => $this->input->post('duty_type', true),
                'name_emg_contact_person_1' => $this->input->post('name_emg_contact_person_1', true),
                'phone_emg_contact_person_1' => $this->input->post('phone_emg_contact_person_1', true),
                'relation_emg_contact_person_1' => $this->input->post('relation_emg_contact_person_1', true),
                'account_title' => $this->input->post('account_title', true),
                'bank_name' => $this->input->post('bank_name', true),
                'account_number' => $this->input->post('account_number', true),
                'iban_number' => $this->input->post('iban_number', true),
                'masters_degree_title' => $this->input->post('masters_degree_title', true),
                'masters_majors' => $this->input->post('masters_majors', true),
                'masters_year_completion' => $this->input->post('masters_year_completion', true),
                'masters_institute' => $this->input->post('masters_institute', true),
                'masters_location' => $this->input->post('masters_location', true),
                'masters_cgpa' => $this->input->post('masters_cgpa', true),
                'bachelors_degree_title' => $this->input->post('bachelors_degree_title', true),
                'bachelors_majors' => $this->input->post('bachelors_majors', true),
                'bachelors_year_completion' => $this->input->post('bachelors_year_completion', true),
                'bachelors_institute' => $this->input->post('bachelors_institute', true),
                'bachelors_location' => $this->input->post('bachelors_location', true),
                'bachelors_cgpa' => $this->input->post('bachelors_cgpa', true),
                'inter_degree_title' => $this->input->post('inter_degree_title', true),
                'inter_majors' => $this->input->post('inter_majors', true),
                'inter_year_completion' => $this->input->post('inter_year_completion', true),
                'inter_institute' => $this->input->post('inter_institute', true),
                'inter_location' => $this->input->post('inter_location', true),
                'inter_percentage' => $this->input->post('inter_percentage', true),
                'matric_degree_title' => $this->input->post('matric_degree_title', true),
                'matric_majors' => $this->input->post('matric_majors', true),
                'matric_year_completion' => $this->input->post('matric_year_completion', true),
                'matric_institute' => $this->input->post('matric_institute', true),
                'matric_location' => $this->input->post('matric_location', true),
                'matric_percentage' => $this->input->post('matric_percentage', true),
                'resume' => $resume,
                'id_card_front' => $id_card_front,
                'id_card_back' => $id_card_back,
                'signed_nda' => $signed_nda,
                'signed_offer_letter' => $signed_offer_letter,
                'master_attachment' => $master_attachment,
                'bachelors_attachment' => $bachelors_attachment,
                'inter_attachment' => $inter_attachment,
                'matric_attachment' => $matric_attachment,
            ];

            if ($this->home_model->update_employee($postData)) {

                $user_his = $this->db->select('*')
                    ->from('user')
                    ->where('email', $this->input->post('email', true))
                    ->get()
                    ->num_rows();

                if ($user_his > 0) {

                    $userData = array(
                        'firstname' => $this->input->post('first_name', true),
                        'lastname' => $this->input->post('last_name', true),
                        'password' => (!empty($this->input->post('password', true)) ? md5($this->input->post('password', true)) : $this->input->post('old_password', true)),
                        'image' => (!empty($image) ? $image : $this->input->post('old_image'))
                    );
                    $this->db->where('email', $this->input->post('email', true))
                        ->update("user", $userData);

                }

                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('professional_experience');
                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('certificate_and_trainings');

                for ($i = 0; $i < sizeof($p_e_company_name); $i++) {
                    $custom_exp = [
                        'p_e_company_name' => $p_e_company_name[$i],
                        'p_e_start_date' => $p_e_start_date[$i],
                        'p_e_end_date' => $p_e_end_date[$i],
                        'p_e_skill_name' => $p_e_skill_name[$i],
                        'p_e_designation' => $p_e_designation[$i],
                        'p_e_location' => $p_e_location[$i],
                        'employee_id' => $this->input->post('employee_id', true),
                    ];
                    if (!empty($p_e_company_name[$i])) {
                        $this->db->insert('professional_experience', $custom_exp);
                    }
                }

                for ($i = 0; $i < sizeof($c_t_name); $i++) {
                    $custom_cert = [
                        'c_t_name' => $c_t_name[$i],
                        'c_t_start_date' => $c_t_start_date[$i],
                        'c_t_end_date' => $c_t_end_date[$i],
                        'c_t_institute' => $c_t_institute[$i],
                        'c_t_location' => $c_t_location[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($c_t_name[$i])) {
                        $this->db->insert('certificate_and_trainings', $custom_cert);
                    }
                }

                $this->session->set_flashdata('message', display('update_successfully'));
                redirect("dashboard/Home/profile");
            }
        } else {

            $data['title'] = "Edit Profile";
            $data['module'] = "dashboard";
            $data['page'] = "home/edit_profile";
            $data['skillslist'] = $this->home_model->skills_list_dropdown();
            $data['documentsinfo'] = $this->home_model->documentsinfo($employee_id);
            $data['certificationsinfo'] = $this->home_model->certificationsinfo($employee_id);
            $data['country_list'] = $this->Country_model->state();
            $emp_id = $this->session->userdata('employee_id');
            $data['user'] = $this->home_model->employee_data($emp_id);
        }

        echo Modules::run('template/layout', $data);
    }

    ///// Notice
    public function view_details()
    {
        $id = $this->uri->segment(4);
        $data['module'] = "dashboard";
        $data['page'] = "home/notice_details";
        $data['detls'] = $this->evencal->details($id);
        echo Modules::run('template/layout', $data);

    }


    public function incomeinfo()
    {
        $year = $this->input->post('year', true);
        echo json_encode($year);
    }

    public function hired_employee_current_year($month)
    {
        $data = $this->home_model->hired_employee_current_year($month);
        echo json_encode($data);
    }

    //get_employee_attendence for current month for employee dashboard gaph reports
    public function monthly_employee_attendence()
    {

        $employee_id = $this->session->userdata['employee_id'];
        $data_arr = [];

        $current_date = date("Y-m-d h:i:sa");
        $dt = new DateTime($current_date);
        $date = $dt->format('Y-m-d');
        $date_y = $dt->format('Y');
        $date_m = $dt->format('m');
        $time = $dt->format('H:i:s');

        $this->db->select('*');
        $this->db->from('point_attendence');
        $this->db->where('employee_id', $employee_id);
        $this->db->where('point', 1);
        $this->db->where("YEAR(create_date)=" . $date_y, NULL, FALSE);
        $this->db->where("MONTH(create_date)=" . $date_m, NULL, FALSE);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data_arr = $query->result();
        } else {
            $data_arr = array();
        }

        // for each day in the month
        $data_points_fianl = [];
        $data_points = [];

        for ($i = 1; $i <= date('t'); $i++) {
            // add the date to the dates array
            $dates[] = date('Y') . "-" . date('m') . "-" . str_pad($i, 2, '0', STR_PAD_LEFT);
            $days[] = str_pad($i, 2, '0', STR_PAD_LEFT);

            $day = str_pad($i, 2, '0', STR_PAD_LEFT);

            foreach ($data_arr as $key => $value) {

                if ((int)$day == (int)date("d", strtotime($value->create_date)) && (int)$value->point == 1) {
                    $data_points[$day] = 1;
                }
            }
        }

        // create days and points based array
        foreach ($days as $key => $value) {

            $respo_days[] = (string)$value;

            if (array_key_exists($value, $data_points)) {
                $data_points_fianl[$value] = $data_points[$value];
            } else {
                $data_points_fianl[$value] = 0;

            }

        }

        $respo_data['days'] = $respo_days;
        $respo_data['points'] = array_values($data_points_fianl);

        echo json_encode($respo_data);
    }

    //yearly_employee_points for employee dashboard gaph reports .. calculating from point_reward table..
    public function yearly_employee_points()
    {

        $employee_id = $this->session->userdata['employee_id'];
        $data_arr = [];

        $current_date = date("Y-m-d h:i:sa");
        $dt = new DateTime($current_date);
        $date_y = $dt->format('Y');

        $this->db->select('*');
        $this->db->from('point_reward');
        $this->db->where('employee_id', $employee_id);
        $this->db->where("YEAR(date)=" . $date_y, NULL, FALSE);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data_arr = $query->result();
        } else {
            $data_arr = array();
        }

        $data_reward = array();
        $data_respo_final = array();

        // for each month in the year
        for ($i = 1; $i <= 12; $i++) {

            $months[] = $i;

            foreach ($data_arr as $key => $value) {

                if ($i == (int)date("m", strtotime($value->date))) {
                    $data_reward[$i] = (int)$value->total;
                }
            }

        }

        // create yearly points array based months and data_reward array
        foreach ($months as $key => $value) {

            if (array_key_exists($value, $data_reward)) {
                $data_reward_final[] = $data_reward[$value];
            } else {
                $data_reward_final[] = 0;
            }
        }

        echo json_encode($data_reward_final);

    }

    //get_employee_attendence for current month for employee dashboard graph reports
    public function monthly_employee_points()
    {

        $data_boxes = array();

        $employee_id = $this->session->userdata['employee_id'];

        //Attendence data
        $this->db->select_sum('point');
        $this->db->from('point_attendence');
        $this->db->where('employee_id', $employee_id);
        $this->db->where("create_date BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()");
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data_attendence = $query->result();
        } else {
            $data_attendence = array('point' => 0);
        }

        $data_boxes['attendence'] = $data_attendence[0];

        //Collaborative data
        $current_date = date("Y-m-d h:i:sa");
        $dt = new DateTime($current_date);
        $date_y = $dt->format('Y');
        $date_m = $dt->format('m');

        $date_m = $date_m - 1;
        if ($date_m == 0) {
            $date_y = $date_y - 1;
            $date_m = 12;
        }

        $this->db->select_sum('point');
        $this->db->from('point_collaborative');
        $this->db->where('point_shared_with', $employee_id);
        $this->db->where("YEAR(point_date)=" . $date_y, NULL, FALSE);
        $this->db->where("MONTH(point_date)=" . $date_m, NULL, FALSE);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data_collaborative = $query->result();
        } else {
            $data_collaborative = array('point' => 0);
        }

        $data_boxes['collaborative'] = $data_collaborative[0];

        //Management data
        $this->db->select_sum('point');
        $this->db->from('point_management');
        $this->db->where('employee_id', $employee_id);
        $this->db->where("create_date BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()");
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data_management = $query->result();
        } else {
            $data_management = array('point' => 0);
        }

        $data_boxes['management'] = $data_management[0];

        $data_points = array();

        if ($data_boxes) {
            $data_points[] = (int)$data_boxes['attendence']->point;
            $data_points[] = (int)$data_boxes['management']->point;
            $data_points[] = (int)$data_boxes['collaborative']->point;
        } else {
            $data_points[] = 0;
            $data_points[] = 0;
            $data_points[] = 0;
        }

        echo json_encode($data_points);

    }

    public function yearly_employee_attendance()
    {

        $employee_id = $this->session->userdata['employee_id'];
        $data_arr = [];

        $current_date = date("Y-m-d h:i:sa");
        $dt = new DateTime($current_date);
        $date_y = $dt->format('Y');

        $this->db->select("DATE_FORMAT(check_in_date, '%m') as month,
                            COUNT(check_in_date) as total_present");
        $this->db->from('employee_attendance');
        $this->db->where('employee_id', $employee_id);
        $this->db->where('check_in_date BETWEEN CONCAT(year(curdate()), "-01" , "-01" ) AND CURDATE()');
        $this->db->group_by("DATE_FORMAT(check_in_date, '%m')");
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $data_arr = $query->result();
        } else {
            $data_arr = array();
        }

        $data_reward = array();
        $data_respo_final = array();

        // for each month in the year
        for ($i = 1; $i <= 12; $i++) {

            $months[] = $i;

            foreach ($data_arr as $key => $value) {

                if ($i == (int)$value->month) {
                    $data_reward[$i] = (int)$value->total_present;
                }
            }

        }
        // create yearly points array based months and data_reward array
        foreach ($months as $key => $value) {

            if (array_key_exists($value, $data_reward)) {
                $data_reward_final[] = $data_reward[$value];
            } else {
                $data_reward_final[] = 0;
            }
        }
        echo json_encode($data_reward_final);

    }
    //  inam start
    public function total_employee_department_wise_percentage(){
        $value = $this->home_model->percentage_employee_by_department();
        print_r($value);
    }
//  inam end

}
