<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Attendants extends CI_controller {

    var $main_menu_name = 'pay_role';
    var $sub_menu_name = 'attendants';

    public function __construct() {
        parent::__construct();
        $this->load->model('Common_Model');
        $this->load->model("Attendants_Model");
        $this->load->model("Warehouse_Model");
		 $this->load->model("User_Model");
		  $this->load->model("User_Group_Model");
		   $this->load->model("User_model");
		   $this->load->model("Salary_model");
    }

    public function index() {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = $this->sub_menu_name;
$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('attendants', $data);
    }
	
	public function finalize_attendants_add() {
        $user_id = $this->input->post('user_id');
		$month_id = $this->input->post('month_id');
		$warehouse_id=$this->input->post('srh_warehouse_id');
		$month_name=$this->input->post('month_name');
		$srh_fd_date=date('Y-m-d',strtotime($this->input->post('srh_fd_date')));
		$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
		$status=1;
		$testing='1';
		if($this->session->userdata('ss_user_id')==1) {
			//$testing='';
		}
		$testing='';
		
		$testing=1;
        
		//echo "user_id , 1  $user_id";
		$user_list=$this->User_model->getUsers(1,$user_id);
		//echo "Test , 2";
	//	print_r($user_list);
		$return_msg="<table class=\"sl_des_table\"><tr><td width='50px'><strong>#</strong></td><td><strong>Name</strong></td><td><strong>Amount</strong><td><td><strong>Note</strong><td></tr>";
		$user_count=0;
		
		$status='';
		$return_msg='';
		foreach ($user_list as $user) {
			
			//echo " <br/> 1";
			
			$user_name='';
			$user_last_name='';
			
			
			//Start Send Salary
			$mstr_sal_type_id=20;//Employer ETF Contribution
			$employer_epf=0;
			
			$att_sal_amount=0;
			$att_sal_amount=100;
			
			if(floatval($att_sal_amount)){
				//echo " <br/> 2";
				$warehouse_code=$warehouse_dtls['code'];
				$warehouse_last_id=(1+$this->Common_Model->get_next_warehouse_ref_no($warehouse_id,'warehouse_id','warehouse_last_id','salary'));
				$reference_number=$warehouse_code.'/SLR/'.sprintf("%04d",$warehouse_last_id);	
				$sl_note="$month_name Month Employer Attendants";			
				 $commi_data = array(
                'reference_number' => $reference_number,
				 'warehouse_last_id' => $warehouse_last_id,
				 'warehouse_id' => $warehouse_id,
                'mstr_sal_type_id' => $mstr_sal_type_id,
                'mstr_sal_type_did_add' => 2,
                'user_id' => $user_id,
                'sl_amount' => $att_sal_amount,
                'sl_date' => $srh_fd_date,
				'issue_card_id' => '',
                'sl_note' => $sl_note,
                'added_user' => $this->session->userdata('ss_user_id')
           		 );
					//check is added this month
				$is_added=$this->Salary_model->check_is_added_for_selected_month($user_id,$mstr_sal_type_id,$month_id);
				$is_added=0;
				if(!$is_added){
					//echo " <br/> 3";
					if(!$testing) $this->Salary_model->save_salary('',$commi_data);
				}else{
					//echo " <br/> 4";
					$sl_note="<span style=\"color:#d9534f\">Allredy Added $sl_note: $is_added</span>";
					//$employer_epf=0;
				}
					$user_count++;
					$att_sal_amount=number_format($att_sal_amount, 2, '.', '');
					$return_msg.="<tr><td>$user_count. </td><td> $user_name $user_last_name </td><td> $att_sal_amount <td><td> $sl_note <td></tr>"; 
				}
				//End Send Salary
			
			$status=1;
		}
		
		$return_msg.='</table>';
		
		echo json_encode(array('status' => $status,'return_msg'=>$return_msg));
	}
	
		 public function attendants_finalize() {
        $data['main_menu_name'] = 'pay_role';
        $data['sub_menu_name'] = 'attendants_finalize';
		 $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['user_group_list'] = $this->User_Group_Model->get_all_user_group();
		$data['user_list']=$this->User_Model->getUsers(1);
        $this->load->view('attendants_finalize', $data);
    }
	
	
	 public function attendants_submit() {
		// echo "555555555555555555555555555555555555";
		  $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = 'attendants_submit';
		 $tam_id = $this->uri->segment(3);
		 
		// echo "tam_id:$tam_id";
		
		$tmp_attendants_list=array();
		if($tam_id){
		$tmp_attendants_list=$this->Attendants_Model->get_tmp_attendants($tam_id);
		
	//	echo $this->db->last_query();
		}
		$data['tmp_attendants_list'] = $tmp_attendants_list;
		 $data['tam_id'] =$tam_id;
		
		  $this->load->view('attendants_submit', $data);
	 }
	 


 public function update_attendants_csv() {
	 
	 $tam_id=$this->input->get('tam_id');
	 
	// echo "tam_id:$tam_id";
	 	if($tam_id){
			$tmp_attendants_list=$this->Attendants_Model->get_tmp_attendants($tam_id);
			
			 foreach ($tmp_attendants_list as $row)

			 {
				 
				 $att_last_warehouse_id='';
				  $warehouse_id = 1;//$this->input->post('warehouse_id');
            $warehouse_dtls = $this->Warehouse_Model->get_warehouse_info($warehouse_id);
            //print_r($warehouse_dtls);
            $warehouse_code = $warehouse_dtls['code'];
            $att_last_warehouse_id = (1 + $this->Common_Model->get_next_warehouse_ref_no($warehouse_id, 'warehouse_id', 'att_last_warehouse_id', 'attendants'));
			// echo $this->db->last_query();
			
			//echo "att_last_warehouse_id:$att_last_warehouse_id";
			 $att_ref_no = $warehouse_code . '/AT/' . sprintf("%04d", $att_last_warehouse_id);
			 
			 $ta_id=$row->ta_id;
			 
			 //calculate time 
			 $ta_time=$row->ta_time;
			 
			
			 
			 $arr_time=explode(":",$ta_time);
			 
			 $at_hour=$arr_time[0];
			 $at_minith=$arr_time[1];
			 $ta_date=date('Y-m-d',strtotime($row->ta_datetime));;
			 
			 $att_date_time="$ta_date $at_hour:$at_minith:00";
			 
			//  echo "att_date_time:$att_date_time , ta_date:$ta_date , at_hour:$at_hour , at_minith:$at_minith";
			  
			  
			  
			// exit();
			 if($row->ta_added==0){
			
				// $warehouse_id='';
	 				$data = array(
                    'att_ref_no' => $att_ref_no,
                    'att_last_warehouse_id' => $att_last_warehouse_id,
                    'warehouse_id' => $warehouse_id,
                      'tam_id' => $tam_id,
                        'ta_id' => $ta_id,
                    'att_date_time' => $att_date_time,
                    'user_id' => $row->user_id,
                   // 'att_note' => '',
                   'att_added_date_time' => date("Y-m-d H:i:s"),
                    'att_added_user' => $this->session->userdata('ss_user_id')
                );
				 $this->Attendants_Model->save_attendants('', $data);
				 
				 
				 //update temp attendets table status
				 if($ta_id){
				 $data = array(
'ta_added' => 1,
);

	$this->Attendants_Model->save_tmp_attendants($ta_id, $data);
				 
				 }
				 
			 }
				// echo $this->db->last_query();
 			}
		}
		
	 
	 $error=0;
	  $return_msg='';
	   $tam_id='';
	 echo json_encode(array('error' => $error,'return_msg'=>$return_msg,'tam_id'=>$tam_id));
 }
	 public function attendants_submit_save() {
		 
		// echo "<br/> 1 Test";
		// print_r($this->input->post());
		 
		 
		 // echo "<br/> 1 userfile".$_FILES["userfile"]['name'];
		 if (!empty($_FILES["userfile"]['name'])) {
			 
			 
			 
               
                $image_name_enc = "PRODUCT_".time().$_FILES["userfile"]['name'];
                $this->load->library('upload',$this->image_manipulation->image_config($image_name_enc));
				
				//print_r($this->image_manipulation->image_config($image_name_enc));
				//echo "type:".$this->image_manipulation->image_config($image_name_enc);
                if ( ! $this->upload->do_upload()){
					
					// echo "<br/> 2 Test";
                   $st = array('status' =>0,'validation' => $this->upload->display_errors());
                   echo json_encode($st);
                }
                else{
					
					 $path = $this->upload->data();
					 
					// print_r($path);
					// echo "<br/> 3 Test";
					 $imgName    = $this->upload->data();
					 
					// print_r($imgName);
					 
					 
					 $csv_name=$imgName['file_name'];
					 /* */ 
					 



//                echo 'edit';




					 /* */
					 
					 //echo "imgName:$imgName";
				}
		 }
		 
	 
	 
	
	//echo "<br/>Start<br/>"; 
	
 $csv = "/home/djsalleeposcom/public_html/thems/uploads/$csv_name";

$handle = fopen($csv,"r");

$data = array(
'tam_user_id' =>  $this->session->userdata('ss_user_id'),
'tam_date_time' => date("Y-m-d H:i:s"),
);

$this->Attendants_Model->save_tmp_attendants_mst('', $data);
$tam_id = $this->db->insert_id();

while (($row = fgetcsv($handle, 10000, ",")) != FALSE) //get row vales
{
   // print_r($row); //rows in array
   
 //  echo "<br/> Row ($row[0]). $row[1] ";

   //here you can manipulate the values by accessing the array
   
   	$user_id=$row[1];
	$ta_datetime=date('Y-m-d H:i:s',strtotime($row[6]));
		$ta_time=$row[7];
	
//	echo "date:".$row[1];
//                echo 'edit';
$data = array(
'ta_user_id' =>  $this->session->userdata('ss_user_id'),
'ta_datetime' => $ta_datetime,
'user_id' => $user_id,
'tam_id' => $tam_id,
'ta_added' => 0,
'ta_time' => $ta_time,
);

if(intval($user_id)){
	$this->Attendants_Model->save_tmp_attendants('', $data);
}
	


}	
	
	
		//echo "<br/>End<br/>"; 
	 
		// exit();
		 $status='';
		 $return_msg='';
		 
		 $url=base_url('attendants/attendants_submit/'.$tam_id);
		 
		redirect($url,'refresh');
		// $this->load->helper($url);
		 
		// echo json_encode(array('status' => $status,'return_msg'=>$return_msg,'tam_id'=>$tam_id));
		 
	 }
	  public function upload_csv() {
		 //$csv = $_FILES['file']['tmp_name'];
		 
		 $csv = "/home/djsalleeposcom/public_html/thems/uploads/PRODUCT_1559037902dj_csv_2.csv";

$handle = fopen($csv,"r");
while (($row = fgetcsv($handle, 10000, ",")) != FALSE) //get row vales
{
   // print_r($row); //rows in array
   
   echo "<br/> Row ($row[0]).  ";

   //here you can manipulate the values by accessing the array


}
	  }

    public function get_attendants_list() {
        $search_key = $this->input->post('search');
        $search_key_val = $search_key['value'];
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        $warehouse_id = $this->input->post('warehouse_id');
        $srh_user_id = $this->input->post('srh_user_id');
        $srh_from_date = $this->input->post('srh_from_date');
        $srh_to_date = $this->input->post('srh_to_date');

        $attendants_list = $this->Attendants_Model->get_attendants_list($start, $length, $search_key_val, $srh_user_id, $warehouse_id, $srh_from_date, $srh_to_date);
        $attendants_list_count = $this->Attendants_Model->get_attendants_list('', '', $search_key_val, $srh_user_id, $warehouse_id, $srh_from_date, $srh_to_date);

        $totalData = $attendants_list_count;
        $totalFiltered = $totalData;

        $data = array();
        $balance_amount = 0;
        foreach ($attendants_list as $row) {
            $nestedData = array();
            $nestedData[] = $row['att_ref_no'];
            $nestedData[] = $row['user_first_name'] . ' ' . $row['user_last_name'];
            $nestedData[] = $row['att_date_time'];
           
           // $nestedData[] = '';//$type;
			 $nestedData[] = '';//$row['att_note'];
           // $nestedData[] = '';//number_format($row['sp_amount'], 2, '.', '');
           // $tem_warehouse = $this->Warehouse_Model->get_warehouse_info($row['warehouse_id']);
           // $nestedData[] = $tem_warehouse['name'];

            $actionTxtUpdate = '<a onClick="click_attendants_btn(' . $row['att_id'] . ')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="glyphicon fa fa-edit"></i></a> &nbsp;';
			$actionTxtDelete = '';
			if($this->session->userdata('ss_user_id')==1 || $this->session->userdata('ss_user_id')==2){
            $actionTxtDelete = '<a class="btn btn-xs btn-bricky tooltips" data-placement="top" data-original-title="Delete supplier" onClick="deleteSalaryPaymentData(' . $row['att_id'] . ')">
															<i class="glyphicon fa fa-trash-o"></i></a>';
			}

            $nestedData[] = $actionTxtUpdate . $actionTxtDelete;

            $data[] = $nestedData;
        }

        $json_data = array(
         //  "draw"            => intval( $requestData['draw'] ),  
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        echo json_encode($json_data);
    }

    public function create_attendants() {
		 $data['warehouse_list']=$this->Warehouse_Model->get_all_warehouse();
        if (isset($_GET['att_id'])) {
            $att_id = $_GET['att_id'];
        } else {
            $att_id = '';
        }


        if ($att_id) {
            $data['att_id'] = $att_id;
            $data['type'] = 'E';
            $data['pageName'] = 'Update Attendants';
            $data['btnText'] = 'Update Attendants';
            $data['attendants_pay_byid'] = $this->Attendants_Model->get_salary_pay_details($att_id);
        } else {
            $data['att_id'] = '';
            $data['type'] = 'A';
            $data['pageName'] = 'Add Attendants';
            $data['btnText'] = 'Add Attendants';
             $data['attendants_pay_byid'] =  array();
        }

        $this->load->view("models/create_attendants", $data);
    }

    public function save_attendants() {
        $att_id = $this->input->post('att_id');
		

//        echo $salary_id;
        $type = $this->input->post('type');
//        $mstr_sal_type_id = $this->input->post('mstr_sal_type_id');
//        $temp_sal_type = explode("_", $this->input->post("mstr_sal_type_id"));
//        $mstr_sal_type_id = $temp_sal_type[0];
//        $mstr_sal_type_did_add = $temp_sal_type[1];
//        $mstr_sal_type_did_add = $this->input->post('mstr_sal_type_did_add');
        $user_id = $this->input->post('user_id');
       // $sp_amount = $this->input->post('sp_amount');
        $att_date_time = date('Y-m-d H:i:s', strtotime($this->input->post("att_date_time")));
        $att_note = $this->input->post('att_note');
       // $sp_is_sal_advance = $this->input->post('sp_is_sal_advance');

        if ($type == 'A') {
            //start get next referance no
           // $warehouse_id = $this->session->userdata('ss_warehouse_id');
            //echo "warehouse_id:$warehouse_id";
			 $warehouse_id = $this->input->post('warehouse_id');
            $warehouse_dtls = $this->Warehouse_Model->get_warehouse_info($warehouse_id);
            //print_r($warehouse_dtls);
            $warehouse_code = $warehouse_dtls['code'];
            $att_last_warehouse_id = (1 + $this->Common_Model->get_next_warehouse_ref_no($warehouse_id, 'warehouse_id', 'att_last_warehouse_id', 'attendants'));
			
			//$curr_warehouse_last_id=$this->Common_Model->get_next_warehouse_ref_no($warehouse_id, 'warehouse_id', 'warehouse_last_id', 'attendants');

            //
            $att_ref_no = $warehouse_code . '/AT/' . sprintf("%04d", $att_last_warehouse_id);
			

        }




        $this->load->library('form_validation'); //form validation lib

        if ($type == 'A') {
            $this->form_validation->set_rules('user_id', 'sp_amount', 'sp_date', 'sp_is_sal_advance', 'required');
        } else if ($type == 'E') {
            $this->form_validation->set_rules('user_id', 'sp_amount', 'required');
        }

        if ($this->form_validation->run() == FALSE) {
            $st = array('status' => 0, 'validation' => validation_errors());
            echo json_encode($st);
        } else {
            if ($type == 'A') {
//                echo 'add';
                $data = array(
                    'att_ref_no' => $att_ref_no,
                    'att_last_warehouse_id' => $att_last_warehouse_id,
                    'warehouse_id' => $warehouse_id,
                    'att_date_time' => $att_date_time,
                    'user_id' => $user_id,
                    'att_note' => $att_note,
                  'att_added_date_time' => date("Y-m-d H:i:s"),
                    'att_added_user' => $this->session->userdata('ss_user_id')
                );
            } else if ($type == 'E') {
//                echo 'edit';
                $data = array(
                    'user_id' => $user_id,
                  //  'att_date_time' => $att_date_time,
                 
                    'att_note' => $att_note,
                    
                    'att_updated_user' => $this->session->userdata('ss_user_id')
                );
            }


            $this->Attendants_Model->save_attendants($att_id, $data);

            $lastid = $this->db->insert_id();

            if ($type == 'A') {
                if ($lastid) {
                    echo json_encode(array('id' => $att_id, 'type' => $type, 'status' => 1));
                } else {
                    echo json_encode(array('status' => 0));
                }
            }
            if ($type == 'E') {
                echo json_encode(array('type' => $type, 'status' => 1));
            }
        }
    }

    public function delete() {
        $id = $this->input->post('id');
        $this->Attendants_Model->delete_attendants($id);
        if ($id) {
            echo json_encode(array('id' => $id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }
	
	
	    public function upload_file($image,$path='upload',$width=0,$height=0,$wm=false)
    {
        //$this->load->library('email');
        $uploadedFiles = array();
        $config['upload_path'] = './assets/pdf/'.$path;
        if(!is_dir($config['upload_path']))
        {
            mkdir($config['upload_path'],0777);
        }
        $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg|JPG|JPEG|pdf|doc|docx|csv';
        //$config['allowed_types'] = 'pdf';
        $config['max_size'] = '3000';
        $config['max_width'] = '4000';
        $config['max_height'] = '4000';
        $this->load->library('upload', $config);
        $upload = $this->upload->do_upload($image);
        $path = $this->upload->data();
		
		//print_r($path);

        $configThumb = array();
        $configThumb['image_library'] = 'gd2';
        $configThumb['source_image'] = $path['full_path'];
        $configThumb['create_thumb'] = FALSE;
        $configThumb['maintain_ratio'] = FALSE;
        $configThumb['overwrite'] = FALSE;

        return $path;
    }

}
