<file_sep>            <div class="tile" style="height: 500px;">
          		<div class="content-title">
			        <div class="div">
			          	<p id="_count-task"><?php echo(isset($_task)?count($_task):'0')?> công việc</p>
			        </div>
			        <button class="btn btn-primary header-btn" type="button" id="_btn-task">Công việc</button>
			    </div>
			    <div class="hide" id="_form-task">
			    	<form id="f_task">
			    	    <input class="width-100per font-size-14" type="text" name="title" placeholder="Tiêu đề công việc" required="">
                        <input type="hidden" name="taskmaster" value="<?php echo($this->uri->segment(4))?>">
                        <input type="hidden" name="ticketid" value="<?php echo($this->uri->segment(3))?>">
			    	<ul class="nav nav-tabs no-margin">
		                <li class="nav-item">
		                	<a class="tsk-link active show" data-toggle="tab" href="#tab1"><i class="fa fa-user"></i></a>
		                </li>
		                <li class="nav-item hide">
		                	<a class="tsk-link" data-toggle="tab" href="#tab2"><i class="fa fa-align-left"></i></a>
		                </li>
		                <li class="nav-item hide">
		                	<a class="tsk-link" data-toggle="tab" href="#tab3"><i class="fa fa-paperclip"></i></a>
		                </li>
		          	</ul>
		          	<div class="tab-content" id="myTabContent">
        				<div class="tab-pane fade active show" id="tab1">
        					<div class="hole">
        						<div class="col-md--4 padding-right-5">
        							<label class="tsk-label">Nhóm phụ trách</label>
        							<select data-placeholder="Chọn nhóm phụ trách..." class="tck-select my-chosen" name="tic">
                                        <option value=""></option>
                                        <?php if (isset($l_agentgroup)) {
                                            foreach ($l_agentgroup as $key => $value) {
                                                echo '<option value="'.$value['groupid'].'">'.$value['groupname'].'</option>';
                                            }
                                        } ?>
                                    </select>
        						</div>
        						<div class="col-md--4 padding-right-5">
        							<label class="tsk-label">Phân loại</label>
        							<select class="tck-select" name="tasktype" id="level_1">
                                        <?php if (isset($l_type)) {
                                            foreach ($l_type as $key => $value) {
                                                echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
                                            }
                                        } ?>
                                    </select>
        						</div>
        						<div class="col-md--4 padding-right-5">
        							<label class="tsk-label">Độ ưu tiên</label>
        							<select class="tck-select" name="priority">
        								<option value="1">Thường</option>
        								<option value="1">Cao</option>
        								<option value="1">Khẩn cấp</option>
        							</select>
        						</div>
                                <div class="col-md--4 padding-right-5">
                                    <label class="tsk-label">Phụ trách</label>
                                    <select data-placeholder="Chọn người phụ trách..." class="tck-select my-chosen" name="pic">
                                        <option value=""></option>
                                            <?php if (isset($l_age)) {
                                                foreach ($l_age as $cus) {
                                                    if ($cus['custname']!='') {
                                                        echo('<option value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>');
                                                    }
                                                }
                                            } ?>
                                    </select>
                                </div>
                                <div class="col-md--4 padding-right-5">
                                    <label class="tsk-label">Chi tiết CV</label>
                                    <select class="tck-select" name="taskdetail" id="level_2">
                                        <?php if (isset($l_detail)) {
                                            foreach ($l_detail as $key => $value) {
                                                $c='';
                                                if (isset($l_type[0]['code']) && $value['ref1']!=$l_type[0]['code']) {
                                                    $c="hide";
                                                }
                                                echo '<option class="'.$c.'" ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
                                            }
                                        } ?>
                                    </select>
                                </div>
                                <div class="col-md--4 padding-right-5">
                                    
                                </div>
        						<div class="col-md--4 padding-right-5">
        							<label class="tsk-label">Ngày yêu cầu</label>
        							<input class="tck-input" type="" name="req_date" >
        						</div>
        						<div class="col-md--4 padding-right-5">
        							<label class="tsk-label">Ngày hẹn</label>
        							<input class="tsk-input" type="" name="due_date" >
        						</div>
        						<div class="col-md--4 margin-top-20 padding-right-5">
        							<button type="submit" class="btn btn-gray float-right margin-top-10">
        								<i class="fa fa-share"></i> 
        							Lưu </button>
        							<button type="button" id="_cancel" class="btn btn-default float-right margin-top-10 margin-right-5">
        								<i class="fa fa-times"></i> 
        							Hủy </button>
        						</div>
        					</div>
        				</div>
        				<div class="tab-pane fade" id="tab2">
        					<div class="hole">
        						<div class="col-md-12">
        							<label class="tsk-label">Ghi chú</label>
        							<textarea></textarea>
        						</div>
        						<div class="col-md-12">
        							<button type="submit" class="btn btn-gray float-right margin-top-10">
        								<i class="fa fa-share"></i> 
        							Lưu </button>
        							<button type="button" id="_cancel" class="btn btn-default float-right margin-top-10 margin-right-5">
        								<i class="fa fa-share"></i> 
        							Hủy </button>
        						</div>
        					</div>
        				</div>
        				<div class="tab-pane fade" id="tab3">
        					<div class="hole">
        						<div class="col-md-6">
        							<label class="tsk-label">Đính kèm file</label>
        							<input type="file" name="">
        						</div>
        						<div class="col-md-12">
        							<button type="submit" class="btn btn-gray float-right margin-top-10">
        								<i class="fa fa-times"></i> 
        							Lưu </button>
        							<button type="submit" class="btn btn-default float-right margin-top-10 margin-right-5">
        								<i class="fa fa-share"></i> 
        							Hủy </button>
        						</div>
        					</div>
        				</div>
        			</div>
        			</form>
			    </div>
			    <div class="table-responsive">
	              	<table class="table" id="_tb-task">
		                <tbody>
		                	<?php if (isset($_task)) {
		                		foreach ($_task as $key => $value) {
		                			$class = '';$icon='';
		                			if ($value['status']=='O') {
		                				$class = 'label-circle label-default span-default';$icon = 'fa fa-check';
		                			}elseif ($value['status']=='W') {
		                				$class = 'label-circle label-warning span-warning';$icon = 'fa fa-exclamation';
		                			}elseif ($value['status']=='C') {
		                				$class = 'label-circle span-success';$icon = 'fa fa-check';
		                			}
		                	?>
		                	<tr class="border-bot-1">
			                    <td width="200">
                                    <span class="<?php echo($class)?>">
                                        <i class="<?php echo($icon)?>"></i>
                                    </span> 
                                    <div class="flex" style="float:right;margin-top:-5px"> 
                                        <div class="task-user-name" style="width:100%"><?php echo($value['picname']!=''?$value['picname']:$value['ticname'])?></div>
                                    </div>
			                    </td>
			                    <td>
			                    	<a class="new_tab" onclick="addTab('<?php echo(base_url('task/detail/'.$value['taskid']))?>','#<?php echo($value['taskid'])?>')" href="#"><?php echo($value['title'])?></a>
			                    </td>
			                    <td width="120"><?php echo date('d-m-Y H:i',strtotime($value['duedate']))?></td>
		                  	</tr>
		                	<?php }} ?>
		                </tbody>
	              	</table>
	            </div>
          	</div><file_sep><script type="text/javascript">
      var dayCompare = new Date("2000-01-01T00:00:00");
      $(document).ready( function () {
        loadFirst();
        });
      
      function selectCity(obj){
          var $id = obj.value;

            $('.gicungdc').remove(); 
          $.ajax({
            url: '<?php echo base_url()?>user/selectCity',
            type: 'POST',
            dataType: 'JSON',
            data: {id_city : $id},
          })
          .done(function(data) {
                     for (var i = 0; i < data.length; i++) {
                      $('#dodulieu').after('<option class="gicungdc" value="'+data[i]['id_district']+'">'+data[i]['name']+'</option>');
                     }
                        
                  })
          .fail(function() {
            console.log("error");
          })
        }

        function selectDistrict(obj){
          var $id = obj.value;

            $('.gicungdc1').remove(); 
          $.ajax({
            url: '<?php echo base_url()?>user/selectDistrict',
            type: 'POST',
            dataType: 'JSON',
            data: {id_district : $id},
          })
          .done(function(data) {
                     for (var i = 0; i < data.length; i++) {
                      $('#dodulieu1').after('<option selected class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>');
                     }
                        
                  })
          .fail(function() {
            console.log("error");
          })
        }
      

       $('#demoNotify').click(function(){
            $.notify({
                  title: "Update Complete : ",
                  message: "Something cool is just updated!",
                  icon: 'fa fa-check' ,
                  url: 'https://github.com/mouse0270/bootstrap-notify',
                  target: '_blank'
            },{
                  // settings
                  element: 'body',
                  position: null,
                  type: "info",
                  allow_dismiss: true,
                  newest_on_top: false,
                  showProgressbar: false,
                  placement: {
                        from: "top",
                        align: "right"
                  },
                  offset: {
                        x: 10,
                        y: 40
                  },
                  spacing: 10,
                  z_index: 1031,
                  delay: 5000,
                  timer: 1000,
                  url_target: '_blank',
                  mouse_over: null,
                  animate: {
                        enter: 'animated fadeInDown',
                        exit: 'animated fadeOutUp'
                  },
                  onShow: null,
                  onShown: null,
                  onClose: null,
                  onClosed: null,
                  icon_type: 'class',
                  template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
                        '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
                        '<span data-notify="icon"></span> ' +
                        '<span data-notify="title">{1}</span> ' +
                        '<span data-notify="message">{2}</span>' +
                        '<div class="progress" data-notify="progressbar">' +
                              '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
                        '</div>' +
                        '<a href="{3}" target="{4}" data-notify="url"></a>' +
                  '</div>' 
            });
      });
      $('#demoSwal').click(function(){
            swal({
                  title: "Are you sure?",
                  text: "You will not be able to recover this imaginary file!",
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonText: "Yes, delete it!",
                  cancelButtonText: "No, cancel plx!",
                  closeOnConfirm: false,
                  closeOnCancel: false
            }, function(isConfirm) {
                  if (isConfirm) {
                        swal("Deleted!", "Your imaginary file has been deleted.", "success");
                  } else {
                        swal("Cancelled", "Your imaginary file is safe :)", "error");
                  }
            });
      });
      $('#demoModal').click(function(){
            var modal = $(
            '<div class="modal fade">\
                  <div class="modal-dialog" role="document">\
                        <div class="modal-content">\
                              <div class="modal-header">\
                                    <h5 class="modal-title">Ghép vào một người khác</h5>\
                                    <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\
                              </div>\
                              <div class="modal-body">\
                                    <div class="flex">\
                                          <div class="div user-call-pad col-sm-5">\
                                            <p class="phone-name"><img class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>\
                                            <p class="phone-num header-desc field-click-able">038 8485 4949</p>\
                                            <p class="phone-time header-desc field-click-able">00 : 00 : 25</p>\
                                          </div>\
                                          <div class="row col-sm-7">\
                                                <div class="col-md-3">\
                                                      <span class="user-history-label span-danger">O</span>\
                                                      <span>5</span>\
                                                </div>\
                                                <div class="col-md-3">\
                                                      <span class="user-history-label span-warning">P</span>\
                                                      <span>5</span>\
                                                </div>\
                                                <div class="col-md-3">\
                                                      <span class="user-history-label span-success">S</span>\
                                                      <span>5</span>\
                                                </div>\
                                                <div class="col-md-3">\
                                                      <span class="user-history-label span-info">R</span>\
                                                      <span>5</span>\
                                                </div>\
                                                <div class="col-md-3">\
                                                      <span class="fa fa-phone user-history-icon span-default"></span>\
                                                      <span>5</span>\
                                                </div>\
                                                <div class="col-md-3">\
                                                      <span class="fa fa-comment user-history-icon span-default"></span>\
                                                      <span>5</span>\
                                                </div>\
                                                <div class="col-md-3">\
                                                      <span class="fa fa-file-alt user-history-icon span-default"></span>\
                                                      <span>5</span>\
                                                </div>\
                                          </div>\
                                    </div>\
                                    <p>Tìm người cần ghép</p>\
                                    <div id="call-input">\
                                          <input class="form-control margin-top-10 margin-bot-5" type="text" name="" placeholder="Phone Number or name">\
                                    </div>\
                                    <div class="flex">\
                                          <div class="div user-call-pad col-sm-6">\
                                            <p class="phone-name"><img class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>\
                                            <p class="phone-num header-desc field-click-able">038 8485 4949</p>\
                                            <p class="phone-time header-desc field-click-able">00 : 00 : 25</p>\
                                          </div>\
                                          <div class="div user-call-pad col-sm-6">\
                                            <p class="phone-name"><img class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>\
                                            <p class="phone-num header-desc field-click-able">038 8485 4949</p>\
                                            <p class="phone-time header-desc field-click-able">00 : 00 : 25</p>\
                                          </div>\
                                    </div>\
                              </div>\
                              <div class="modal-footer">\
                                    <button class="btn btn-primary btn-89" type="button" data-dismiss="modal">Hủy</button>\
                                    <button class="btn btn-secondary btn-89" type="button">Ghép</button>\
                              </div>\
                        </div>\
                  </div>\
            </div>');  
            modal.modal("show").on("hidden", function(){
                  modal.remove();
            }); 
      });
  function formatNumber (num) {
      return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
  }
  function arrayContains(needle, arrhaystack)
  {
      return (arrhaystack.indexOf(needle) > -1);
  }
        
  function formatDMY(dd,mm,yyyy)
  {
      if(dd<10){
      dd='0'+dd;
      } 
      if(mm<10){
          mm='0'+mm;
      } 
      var today = dd+'/'+mm+'/'+yyyy;
      return today;
  }
  function loadFirst(){
    $.fn.dataTable.moment('DD/MM/YYYY');
        var arrayCheck = [];
        var contractid = '<?php echo $this->uri->segment(3) ?>';
    $('.nav-tabs')
          .scrollingTabs({
            enableSwiping: true
          })
          .on('ready.scrtabs', function() {
            $('.tab-content').show();
          });
      
        $.ajax({
        url: 'http://crm.tavicosoft.com/api/get_erp_token/C0001',
        type: 'GET',
        dataType: 'JSON'
      })
      .done(function(data) {
        var json = jQuery.parseJSON(data);
      // $(".a_contractid").attr('href','http://demo.tavicosoft.com/connectdb/loginprovider?opid=<?php echo $this->input->get('opid') ?>&returnUrl=%2F%23PCT&token='+json.result.data+'&dataseg=contractid%3D<?php echo $trade[0]['contractid'] ?>%26action%3DV');
      $(".a_contractid").attr('href','http://demo.tavicosoft.com/connectdb/loginprovider?opid=C0001@AGT&returnUrl=%2F%23PCT&token='+json.result.data+'&dataseg=contractid%3D<?php echo $trade[0]['contractid'] ?>%26action%3DV');
      $(".a_custid").attr('href','http://demo.tavicosoft.com/connectdb/loginprovider?opid=<?php echo $this->input->get('opid') ?>&returnUrl=%2F%23NAD&token='+json.result.data+'&dataseg=nadcode%3D<?php echo $trade[0]['clientcode'] ?>%26action%3DV');
              })
      .fail(function() {
         console.log('Load Fail!!!');
      })
      $('#table-1-ticketcontract').DataTable({
          "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollY":        "235px",
                    "scrollX":        true,
                    "scrollCollapse": true,
"bAutoWidth": true,
                    "ajax":
                        "<?php echo base_url() ?>user/loadTicketContract/"+contractid,
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    }
        });

       $.ajax('http://crm.tavicosoft.com/api/get_list_contract',{
            'data': JSON.stringify({  
             "reportcode":"crmContract01e",
            "limit":25,
            "start":0,
            "queryFilters":{"contractid":contractid}
            }),
            'type': 'POST',
            'processData': false,
            'contentType': 'application/json' 
        })
          .done(function(data) {
                      $('#div-content-1').css("background","none");
                     var obj = jQuery.parseJSON(data);
                     if(obj.result.data.length >0)
                     {
                      var data_html='';
                      for (var i = 0; i < obj.result.data.length; i++) {
                        if(obj.result.data[i].name !== null)
                        {
                           var name = obj.result.data[i].name;
                        }else{var name ='';}
                        if(obj.result.data[i].gender !== null)
                        {
                           var gender = obj.result.data[i].gender;
                        }else{var gender ='';}
                        if(obj.result.data[i].birthday !== null)
                        {
                           var birthday = obj.result.data[i].birthday+"/"+obj.result.data[i].birthmonth+"/"+obj.result.data[i].birthyear;
                        }else{var birthday ='';}
                        if(obj.result.data[i].telephone !== null)
                        {
                           var telephone = obj.result.data[i].telephone;
                        }else{var telephone ='';}
                        if(obj.result.data[i].email !== null)
                        {
                           var email = obj.result.data[i].email;
                        }else{var email ='';}
                        if(obj.result.data[i].idcard !== null)
                        {
                           var idcard = obj.result.data[i].idcard;
                        }else{var idcard ='';}
                        if(obj.result.data[i].issueddate !== null)
                        {
                           var t3 = new Date(obj.result.data[i].issueddate);
                           if(t3 > dayCompare)
                           {
                           var issueddate = formatDMY(t3.getDate(),t3.getMonth()+1,t3.getFullYear());
                          }else{var issueddate = ''}
                        }else{var issueddate ='';}
                        if(obj.result.data[i].issuedplace !== null)
                        {
                           var issuedplace = obj.result.data[i].issuedplace;
                        }else{var issuedplace ='';}
                        if(obj.result.data[i].residencyaddress !== null)
                        {
                           var residencyaddress = obj.result.data[i].residencyaddress;
                        }else{var residencyaddress ='';}
                        if(obj.result.data[i].contactaddress !== null)
                        {
                           var contactaddress = obj.result.data[i].contactaddress;
                        }else{var contactaddress ='';}
                        if(obj.result.data[i].title !== null)
                        {
                           var title = obj.result.data[i].title;
                        }else{var title ='';}
                        if(obj.result.data[i].bankaccountno !== null)
                        {
                           var bankaccountno = obj.result.data[i].bankaccountno;
                        }else{var bankaccountno ='';}
                        if(obj.result.data[i].bankname !== null)
                        {
                           var bankname = obj.result.data[i].bankname;
                        }else{var bankname ='';}
                        if(obj.result.data[i].nationalily !== null)
                        {
                           var nationalily = obj.result.data[i].nationalily;
                        }else{var nationalily ='';}
                        if(obj.result.data[i].cellphone !== null)
                        {
                           var cellphone = obj.result.data[i].cellphone;
                        }else{var cellphone ='';}
                         if(obj.result.data[i].authorizedletter !== null)
                        {
                           var authorizedletter = obj.result.data[i].authorizedletter;
                        }else{var authorizedletter ='';}
                        if(obj.result.data[i].company !== null)
                        {
                           var company = obj.result.data[i].company;
                        }else{var company ='';}
                        if(obj.result.data[i].remarks !== null)
                        {
                           var remarks = obj.result.data[i].remarks;
                        }else{var remarks ='';}

                          data_html+='<div class="row">\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Họ và Tên: </strong></label>\
                        <label for="exampleInputName2">'+name+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Giới tính: </strong></label>\
                        <label for="exampleInputName2">'+gender+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                         <label for="exampleInputName2"><strong>Ngày sinh: </strong></label>\
                        <label for="exampleInputName2">'+birthday+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Số điện thoại: </strong></label>\
                        <label for="exampleInputName2">'+telephone+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Email: </strong></label>\
                        <label for="exampleInputName2">'+email+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Số CMND: </strong></label>\
                        <label for="exampleInputName2">'+idcard+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Ngày cấp: </strong></label>\
                        <label for="exampleInputName2">'+issueddate+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Nơi cấp: </strong></label>\
                        <label for="exampleInputName2">'+issuedplace+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-12">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Địa chỉ thường trú: </strong></label>\
                        <label for="exampleInputName2">'+residencyaddress+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-12">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Địa chỉ liên lạc: </strong></label>\
                        <label for="exampleInputName2">'+contactaddress+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Chức vụ: </strong></label>\
                        <label for="exampleInputName2">'+title+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Số TKNH: </strong></label>\
                        <label for="exampleInputName2">'+bankaccountno+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Ngân hàng: </strong></label>\
                        <label for="exampleInputName2">'+bankname+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Quốc gia: </strong></label>\
                        <label for="exampleInputName2">'+nationalily+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Số DTDD: </strong></label>\
                        <label for="exampleInputName2">'+cellphone+'</label>\
                      </div>\
                    </div>\
\
                    <div class="col-md-4">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Giấy uỷ quyền: </strong></label>\
                        <label for="exampleInputName2">'+authorizedletter+'</label>\
                      </div>\
                    </div>\
                    \
                  </div>\
                  <div class="row">\
                    <div class="col-md-12">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Công ty: </strong></label>\
                        <label for="exampleInputName2">'+company+'</label>\
                      </div>\
                    </div>\
                    \
                  </div>\
\
                  <div class="row">\
                    <div class="col-md-12">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Ghi chú: </strong></label>\
                        <label for="exampleInputName2">'+remarks+'</label>\
                      </div>\
                    </div>\
                  </div>';
                      }
                      $('#div-content-1').html(data_html);
                      }
                  })
          .fail(function() {
            console.log("error");
          })
      $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var contractid = '<?php echo $this->uri->segment(3) ?>';
          var target = $(e.target).attr("alt") ;
          var check = arrayContains(target,arrayCheck);
          if(check == true)
          {
            return;
          }
          else{arrayCheck.push(target);}
          if(target == "crmContract01b")
          {
            $('#table-1-history').DataTable({
          "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollX":        true,
                    "scrollCollapse": true,
"bAutoWidth": true,
                    "ajax":
                        "<?php echo base_url() ?>user/getHistory/"+contractid,
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    }
        });
          }
          else if(target == "crmContract01c"){
            $('#table-1-congno').DataTable({
            "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollX":        true,
                    "scrollCollapse": true,
"bAutoWidth": true,
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    },
                    "ajax": '<?php echo base_url() ?>user/getCongnoThanhtoan/'+contractid

          });
          }
          else if(target == "crmContract01d"){
            $('#table-1-gift').DataTable({
          "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollY":        "235px",
                    "scrollX":        true,
                    "scrollCollapse": true,
"bAutoWidth": true,
                    "ajax":
                        "<?php echo base_url() ?>user/getGift/"+contractid,
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    }
        });
          }
        else if(target == "crmContract01f"){
          $('#table-1-buss').DataTable({
          "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollY":        "235px",
                    "scrollX":        true,
                    "scrollCollapse": true,
"bAutoWidth": true,
                    "ajax":
                        "<?php echo base_url() ?>user/getBussEmployee/"+contractid,
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    }
        });
        }
        else if(target == "crmContract01h"){
          $('#table-1-notes').DataTable({
          "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollY":        "235px",
                    "scrollX":        true,
                    "scrollCollapse": true,
"bAutoWidth": true,
                    "ajax":
                        "<?php echo base_url() ?>user/getNotes/"+contractid,
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    }
          });
        }
        else if(target == "crmContract01g")
        {
               $.ajax('http://crm.tavicosoft.com/api/get_list_contract',{
              'data': JSON.stringify({  
               "reportcode":target,
              "limit":25,
              "start":0,
              "queryFilters":{"contractid":contractid}
              }),
              'type': 'POST',
              'processData': false,
              'contentType': 'application/json' 
          })
            .done(function(data) {
                var obj = jQuery.parseJSON(data);
                $("#div-content-6").css('background', 'none');
                      if(obj.result.data.length >0){

                     if (obj.result.data[0].duedate !== null)
                     {
                        var t2 = new Date(obj.result.data[0].duedate);
                        if(t2 > dayCompare)
                           {
                        var duedate = formatDMY(t2.getDate(),t2.getMonth()+1,t2.getFullYear());
                          }
                          else{var duedate = '';}
                     }else{ var duedate = "";}
                     if (obj.result.data[0].adjustdate !== null)
                     {
                        var t2 = new Date(obj.result.data[0].adjustdate);
                        if(t2 > dayCompare)
                           {
                        var adjustdate = formatDMY(t2.getDate(),t2.getMonth()+1,t2.getFullYear());
                          }else{var adjustdate ='';}
                     }else{ var adjustdate = "";}
                     if (obj.result.data[0].value0 !== null)
                     {
                        var value0 = formatNumber(obj.result.data[0].value0);
                     }else{ var value0 = "";}
                     if (obj.result.data[0].value3 !== null)
                     {
                        var value3 = formatNumber(obj.result.data[0].value3);
                     }else{ var value3 = "";}
                     if (obj.result.data[0].value1 !== null)
                     {
                        var value1 = formatNumber(obj.result.data[0].value1);
                     }else{ var value1 = "";}
                     if (obj.result.data[0].value2 !== null)
                     {
                        var value2 = formatNumber(obj.result.data[0].value2);
                     }else{ var value2 = "";}

                     if (obj.result.data[0].pptarea !== null)
                     {
                        var pptarea = obj.result.data[0].pptarea;
                     }else{ var pptarea = "";}
                     if (obj.result.data[0].contractvalue !== null)
                     {
                        var contractvalue = formatNumber(obj.result.data[0].contractvalue); 
                     }else{ var contractvalue = "";}
                     if (obj.result.data[0].comments !== null)
                     {
                        var comments = obj.result.data[0].comments;
                     }else{ var comments = "";}
                    $('#div-content-6').html('<div class="row">\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Ngày Đc: </strong></label>\
                        <label for="exampleInputName2">'+
                        // obj.result.data[0].adjustdate
                        adjustdate
                        +'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Giá bán chưa VAT: </strong></label>\
                        <label for="exampleInputName2">'+
                        value0+'</label>\
                      </div>\
                    </div>\
                    </div>\
                    <div class="row">\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Ngày đến hạn: </strong></label>\
                        <label for="exampleInputName2">'+duedate+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Thuế VAT: </strong></label>\
                        <label for="exampleInputName2">'+ value1 +'</label>\
                      </div>\
                    </div>\
                  </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Diện tích: </strong></label>\
                        <label for="exampleInputName2">'+ pptarea +'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Phí bảo trì: </strong></label>\
                        <label for="exampleInputName2">'+value2+'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Giá trị hợp đồng: </strong></label>\
                        <label for="exampleInputName2">'+ contractvalue+'</label>\
                      </div>\
                    </div>\
                    <div class="col-md-6">\
                      <div class="form-group">\
                        <label for="exampleInputName2"><strong>Giá trị quyền SDĐ:</strong></label>\
                        <label for="exampleInputName2">'+value3 +'</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="row">\
                    <div class="col-md-12">\
                      <div class="form-group">\
                         <label for="exampleInputName2"><strong>Ghi chú: </strong></label>\
                        <label for="exampleInputName2">'+ comments +'</label>\
                      </div>\
                    </div>\
                  </div>');
                      }
            }).fail(function() {
            console.log("error");
          })

        }
        });
          $("a[data-toggle=\"tab\"]").on("shown.bs.tab", function (e) {
              $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
          });
  }
</script>
<style>
::-webkit-scrollbar {
    width: 0px;
    height: 4px;
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: #56b8b6;
}
  </style><file_sep><?php

$handle = fopen("log.txt","a+");
var_dump($_REQUEST);
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
$raw = json_encode($data);
fwrite($handle,$raw."\n\t");
fclose($handle);
echo "</br>Here</br>";

$ch = curl_init("http://crm.tavicosoft.com:3000/call");

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $raw);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json'                                                                
));                                            

$result = curl_exec($ch);

var_dump($result);
?><file_sep><?php
//<NAME>
//Ngày : 10-09-09
//Custid : <NAME> , duy nhất
defined('BASEPATH') OR exit('No direct script access allowed');
class M_user extends CI_Model
{

    /*Xứ lý tất cả logic của user ở đây*/

     public function __construct()
    {
        parent::__construct();
    }
    //API URL Gọi lấy dự liệu DB
	private $url_api_db = "http://test.tavicosoft.com/crm/index.php/";

    //Lấy user bằng custid
	public function getUserByCustId($custid,$dataAuth){
        $user = $this->cache->memcached->get('user_'.$custid);
        //$user = null;
        if (!$user){
            $user = file_get_contents($this->url_api_db.'customer/getcustomerbycustid/'.urlencode($custid).'');
            $this->cache->memcached->save('user_'.$custid,$user, 86400);
        }
        return json_decode($user,true);
    }



    public function getTicketById($ticketid){
        //$result = $this->cache->memcached->get('ticket_'.$ticketid);
        if (!$result){
            $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/search?search=&ticketid='.$ticketid.'');
            $this->cache->memcached->save('ticket_'.$ticketid,$result, 86400);
        }
        return $result;
    }

    public function updateUser($custid,$dataUpdate,$dataAuth){
        $this->cache->memcached->delete('user_'.$custid);
    }

}<file_sep>#!/bin/bash

/usr/bin/pm2 stop ~/callevent/server.js
<file_sep><form id="insertUserVal" method="POST" role="form">
<input type="hidden" name="log_groupid" id="log_groupid" value="<?php echo $detail[0]['groupid'] ?>">
<input type="hidden" name="opid" id="opid" value="<?php echo $detail[0]['opid']?>">
<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phân quyền</label>
	              		<select id="roleid" class="control-label col-md-8 no-border no-padding margin-left-10" <?php 
	              			$var = $this->session->userdata;
        					$roleid = $var['roleid'];
	              		if($roleid =='2'){echo 'disabled';} ?>>
	              			<?php
	              				foreach ($role_list as $key => $value) {
	              					?>
	              						<option value="<?php echo $key ?>" ><?php echo $value?></option>
	              					<?php
	              				}
	              			?>
	              		</select>
	            	</div>
	            	<input type='hidden' custid='<?php echo $detail[0]['custid'] ?>' id="cusit_id" />
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Nhóm</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10 grouplist" id="groupid" name="groupid">
	              			<?php foreach ($group_list as  $value) { ?>
	              				<option value="<?php echo $value['groupid'] ?>" ><?php echo $value['groupname']?></option>
	              			<?php } ?>
	              		</select>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Họ và Tên</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="custname" id="custname" class="col-md-12 no-padding font-size-12" minlength="4" maxlength="30" value="<?php echo $detail[0]['custname'] ?>">
		              	</label>
	            	</div>
	            	<div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>>
	            		<label class="control-label user-label col-md-3 no-padding">Danh xưng</label>
	              		<select name="gender"class="control-label col-md-8 no-border no-padding margin-left-10" id="gender">
	              			<option value="M">Ông</option>
	              			<option value="F">Bà</option>
	              		</select>
	            	</div>

	            	<div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>>
	            		<label class="control-label user-label col-md-3 no-padding">CMND/Passport:</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input type="text" name="idcard" id="idcard" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['idcard'] ?>" required minlength="8" />
		              	</label>
	            	</div>
	            	<div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>>
	            		<label class="control-label user-label col-md-3 no-padding">Ngày sinh:</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="fullbirthday" id="fullbirthday" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['fullbirthday'] ?>">

		              	</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Điện thoại</label>
	            		
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input 
		              		<?php if($detail[0]['roleid']== '3'){
		              			echo '';
		              		}
		              		else{echo 'readonly';}  ?>  minlength="10" maxlength="11" name="telephone" id="telephone" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['telephone'] ?>">
		              	</label>
		              	
		              	<input type="hidden" name="listtelephone" id="listtelephone" value="<?php echo $detail[0]['telephonelist'] ?>">
	            	<?php if($detail[0]['telephonelist'] != ''){ ?> 
	            		<label class="control-label user-label col-md-3 no-padding"></label>
		              	<label class="control-label col-md-8 no-padding-right">
	              			<?php 
	              			$arrayTelephone = explode(",",$detail[0]['telephonelist']);
	              			if(count($arrayTelephone) >0)
	              			{
	              			foreach ($arrayTelephone as $rows) { ?>
	              				<div class="row">
	              				<input class="col-md-9 padding-left-15 font-size-12" value="<?php echo $rows  ?>">
	              				<a href="#" onclick="removephone('<?php echo $rows  ?>','<?php echo $detail[0]['telephonelist'];?>','<?php echo $detail[0]['roleid'];?>','<?php echo $detail[0]['groupid'];?>')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>
	              				<!--<a href="#"><i class="fas fa-arrow-circle-up fa-md float-right margin-top-3"></i></a>-->
	              				</div>
	              			<?php }}} ?>
		              		
		              	</label>

	            	</div>
	            	<?php if($detail[0]['queue']!=null ){?>
	            	<div class="div-queue">
                  <label class="control-label user-label col-md-3 no-padding">Hàng chờ cuộc gọi</label>
		                    <select class="control-label col-md-8 no-border no-padding margin-left-10" id="queue">
		                       <option <?php if($detail[0]['queue'] == '21114'){echo 'selected';} ?> value="21114" >Chuyển nhượng hợp đồng</option>
		                      <option <?php if($detail[0]['queue'] == '21115'){echo 'selected';} ?> value="21115" >Thanh toán vay</option>
		                      <option <?php if($detail[0]['queue'] == '21121'){echo 'selected';} ?> value="21121" >Tiếng Anh</option>
		                      <option <?php if($detail[0]['queue'] == '21116'){echo 'selected';} ?> value="21116" >Khác</option>
		                    </select>
		                    <input type="hidden" id="queue_old" value="<?php echo $detail[0]['queue'] ?>">
                	</div>
                	 <?php } ?>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding"></label>
	              		<label class="control-label col-md-8 no-padding-right field-click-able"><a data-toggle="modal" data-target="#insertPhone">+ Thêm số liên lạc</a></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>

	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">E-mail</label>
	            		
	            		<label class="control-label col-md-8 no-padding-right">
		              		<input name="email" id="email"  minlength="4" maxlength="30" type="email" class="col-md-9 no-padding font-size-12" value="<?php echo $detail[0]['email'] ?>">
		              	</label>
	            	<?php if($detail[0]['emaillist'] != ''){ ?> 
	            		<label class="control-label user-label col-md-3 no-padding"></label>
	            		<label class="control-label col-md-8 no-padding-right">
		              		<?php 
	              			$arrayEmail = explode(",",$detail[0]['emaillist']);
	              			if(count($arrayEmail) >0)
	              			{
	              			foreach ($arrayEmail as $rows) { ?>
	              				<div class="row">
	              				<input  class="col-md-9 padding-left-15 font-size-12" value="<?php echo $rows  ?>">
		              			<a href="#" onclick="removeemail('<?php echo $rows  ?>','<?php echo $detail[0]['emaillist'];?>','<?php echo $detail[0]['roleid'];?>','<?php echo $detail[0]['groupid'];?>')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>
	              				<!--<a href="#" ><i class="fas fa-arrow-circle-up fa-md float-right margin-top-3"></i></a>-->
	              			</div>
	              			<?php }}} ?>
		              	</label>

	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding"></label>
	              		<label class="control-label col-md-8 no-padding-right field-click-able"><a data-toggle="modal" data-target="#insertEmail">+ Thêm địa chỉ e-mail</a></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="div-address" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>>
	            		<?php 
	            		if (count($address) == 0) { ?>
	            			<label class="control-label user-label col-md-3 no-padding">Địa chỉ</label>
		              		<label class="control-label col-md-8 no-padding-right">
		              			<input class="col-md-12 no-padding font-size-12" value="">
			              	</label>
	            		<?php }
	            		for ($i=0; $i < count($address); $i++) {
	            				if($address[$i]['hidden'] != 1 && $address[$i]['mainaddress'] == 1){ ?>
		            		<label class="control-label user-label col-md-3 no-padding">Địa chỉ</label>
		              		<label class="control-label col-md-8 no-padding-right">
		              			<input onclick="openModalEdit(
		              			'<?php echo $address[$i]['label'] ?>',
		              			'<?php echo $address[$i]['city'] ?>',
		              			'<?php echo $address[$i]['district'] ?>',
		              			'<?php echo $address[$i]['ward'] ?>',
		              			'<?php echo $address[$i]['street'] ?>',
		              			'<?php echo $address[$i]['address'] ?>',
		              			'<?php echo $address[$i]['addressid'] ?>'
		              			)" class="col-md-12 no-padding font-size-12" value="<?php echo $address[$i]['label'] ?>" data-toggle="tooltip" data-placement="right" title="<?php echo $address[$i]['fulladdress'] ?>">
			              	</label>
	            		<?php }} 
	            		for ($i=0; $i < count($address); $i++) {
	            				if($address[$i]['hidden'] != 1 && $address[$i]['mainaddress'] == 0){ ?>
		            		<label class="control-label user-label col-md-3 no-padding"></label>
		              		<label class="control-label col-md-7 no-padding-right">
		              			<input onclick="openModalEdit(
		              			'<?php echo $address[$i]['label'] ?>',
		              			'<?php echo $address[$i]['city'] ?>',
		              			'<?php echo $address[$i]['district'] ?>',
		              			'<?php echo $address[$i]['ward'] ?>',
		              			'<?php echo $address[$i]['street'] ?>',
		              			'<?php echo $address[$i]['address'] ?>',
		              			'<?php echo $address[$i]['addressid'] ?>'
		              			)" class="col-md-12 no-padding font-size-12" value="<?php echo $address[$i]['label'] ?>" data-toggle="tooltip" data-placement="right" title="<?php echo $address[$i]['fulladdress'] ?>">
			              	</label>
			              	<a href="#" onclick="removeAddress('<?php echo $address[$i]['addressid'] ?>')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>
	            		<?php }} ?>

	            	</div>

	            	<div class="" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>>
	            		<label class="control-label user-label col-md-3 no-padding"> </label>
	              		<label class="control-label col-md-8 no-padding-right field-click-able"><a data-toggle="modal" data-target="#updateAddress">+ Thêm địa chỉ</a></label>
	            	</div>
	            </div>
	            <div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ghi chú</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="comments" id="comments" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['comments'] ?>"  maxlength="30">
		              	</label>
	            	</div>
          	</div>
          </form>	
          <form id="dataExt" method="POST" role="form">
          	<?php 
          	if($detail[0]['extinfo'] !=null)
          	{
          	$data = json_decode($detail[0]['extinfo'],true);
          	}
          	else{$data = null;}
          	 ?>
          	
          	<div class="tile p-0 padding-5 margin-bot-5 div-bonus" <?php if($detail[0]['roleid'] !='3'){echo 'hidden';} ?>>
	            <div class="tile-body padding-left-10">
	            	<?php 
	            	if(count($list_ext)>0){
	            	foreach ($list_ext as $value) {
	            	if($value['formid'] == 'user' && $value['status'] == '1'){
	             ?>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">
	            			<?php echo $value['fieldname'] ?>
	            		</label>
	              			<?php if($value['fieldtype'] == 'T') {
	              				$dataReal='';
	              				if($data !=null)
	              				{
	              				foreach ($data as $extkey => $extvalue){
	              					if($extkey == $value['fieldcode']){
	              						$dataReal = $extvalue;
	              						break;
	              					}else{$dataReal = '';}}}?>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="<?php echo $value['fieldcode'] ?>" id="<?php echo $value['fieldcode'] ?>" class="col-md-12 no-padding font-size-12 available" value="<?php echo $dataReal ?>" placeholder="<?php echo $value['fieldname'] ?>">
		              	</label>
		              		<?php }else if($value['fieldtype'] == 'D'){
		              			?>
		              			<select name="<?php echo $value['fieldcode'] ?>" class="control-label col-md-8 no-border no-padding margin-left-10" id="<?php echo $value['fieldcode'] ?>">
		              			<?php 
		              			foreach ($list_codic as $material) {
		              				if($material['category'] == $value['datasource'] && $material['status'] =='W'){
		              				?>
		              				<option
		              				<?php 
		              					if(count($data)>0)
		              					{
		              					foreach ($data as $extkey => $extvalue){
		              						if($extvalue == $material['code'])
		              						{
		              							echo 'selected';
		              							break;
		              						}
		              					}}
		              				 ?>
		              				 value="<?php echo $material['code'] ?>"><?php echo $material['name'] ?></option>
		              			<?php }}?> 
		              			</select>
		              		<?php } ?>
	            	</div>
	            <?php }}} ?>
	            </form>
	            </div>
          	</div>

          	<div>
	        <div class="fc-corner-right">
          		<div class="fc-button-group" style="float:right">
					<button type="submit" id="updateUser" class="btn btn-primary float-right margin-bot-5 btn-update"><i class="fa fa-share"></i>Lưu thông tin</button>
				</div>
          	</div>
          	</div>
          	<div class="padding-5 margin-bot-5" style="margin-top: 40px">
	          	<div class="">
	        		<label class="control-label user-label col-md-3 no-padding">Ngày tạo</label>
	          		<label class="control-label col-md-8 no-padding-right"><?php
	          		if($detail[0]['createddate'] !=null)
	          		{
	          		echo date("d/m/Y", strtotime($detail[0]['createddate']));}
	          		 ?></label>
	        	</div>
	        </div>
	        <?php
	        try
	        { 
	        $id = isset($_GET['cusid']) ? $_GET['cusid'] :'' ;
	    	}catch(exception $Ex)
	    	{
	    		$id = '';
	    	} 
	        
    		if($id == '')
    		{
    			$id = strval($_GET['phone']);
    		}
    		$idcard = strval($_GET['idcard']);
    		$roleid = strval($_GET['roleid']);
	         ?>
	        <div class="modal fade" id="insertPhone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 5%" role="document">
			    <div class="modal-content">
			    	<!--<form method="post" enctype="multipart/form-data" action="<?php echo base_url().'user/insertPhoneList/?cusid='.$id.'&idcard='.$idcard.'&roleid='.$roleid ?>">-->
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">Thêm số điện thoại</h4>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Đóng"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
			        	<div class="form-group">
					    <label for="exampleInputEmail1">Số Điện Thoại</label>
					    <input type="text" class="form-control" name="telephonelist" id="telephonelist" name="tvcdb" placeholder="-Số điện thoại">
					  </div>
			      </div>
			      <div class="modal-footer">
			        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
			        <button type="button" class="btn btn-primary btn-add-phone" onclick="addTelephone('<?php echo $id ?>','<?php echo $idcard ?>','<?php echo $roleid ?>','<?php echo $detail[0]['groupid'];?>')"><i class=""></i>Thêm</button>
			      </div>
					<!--</form>-->
			    </div>
			  </div>
			</div>

			<div class="modal fade" id="insertEmail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 5%" role="document">
			    <div class="modal-content">
			    	<!--<form method="post" enctype="multipart/form-data" action="">-->
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">Thêm email</h4>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
			      	<input type="hidden" name="listemail" id="listemail" value="<?php echo $detail[0]['emaillist'] ?>">
			        <div class="form-group">
					    <label for="exampleInputEmail1">Email</label>
					    <input type="email" class="form-control" name="email" id="emailadd" name="tvcdb" placeholder="-Email">
					  </div>
			      </div>
			      <div class="modal-footer">
			        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
			        <button type="button" class="btn btn-primary" onclick="addEmail('<?php echo $id ?>','<?php echo $idcard ?>','<?php echo $roleid ?>','<?php echo $detail[0]['groupid'];?>')">Thêm</button>
			      </div>
			  		<!--</form>-->
			    </div>
			  </div>
			</div>

			<div class="modal fade" id="updateAddress" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">Thêm địa chỉ</h4>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
			      	<div class="form-group">
					    <label class="control-label col-md-12 no-padding-right">
					    <input class="col-md-12 no-padding font-size-12" placeholder="Nhập nhãn địa chỉ" maxlength="30" style="
  border-bottom: 1px solid #DBDBDB;" id="label">
						</label>
					</div>

			      	<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Quốc gia: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_country" placeholder="Quốc Gia" value="Việt Nam" name="country" id="country" class="col-md-12 no-padding font-size-12">
							<datalist id="l_country">
		              				<option>Việt Nam</option>
							</datalist>
		              	</label>
					  </div>
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Tỉnh / Thành Phố: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_city" placeholder="Tỉnh / Thành Phố" id="city" name="city" class="col-md-12 no-padding font-size-12">
							<datalist id="l_city">
								<?php 
		              			if(isset($city)){
		              			foreach ($city as $rows) { ?>
		              				<option id-city="<?php echo $rows->id_city?>" value="<?php echo $rows->name?>"></option>
		              			<?php }} ?>
							</datalist>
	              		</label>
					  </div>
			        <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Quận / Huyện: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_distr" placeholder="Quận / Huyện" id="district" name="district" class="col-md-12 no-padding font-size-12">
							<datalist id="l_distr">
							</datalist>
	              		</label>
					  </div>
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Phường / Xã: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_ward" placeholder="Phường / Xã" id="ward" name="ward" class="col-md-12 no-padding font-size-12">
							<datalist id="l_ward">
							</datalist>
	              		</label>
					  </div>
					  
			      	<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Tên đường: </label>
					    <label class="control-label col-md-8 no-padding-right">
					    <input  placeholder="<NAME>" value="" id="street" class="col-md-12 no-padding font-size-12"  id="fulladdresstemp" placeholder="Địa chỉ" maxlength="30" name="fulladdress">
						</label>
					</div>
					<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Số nhà: </label>
					    <label class="control-label col-md-8 no-padding-right">
					    <input  placeholder="Số nhà" id="address" value="" class="col-md-12 no-padding font-size-12" placeholder="Địa chỉ" maxlength="30" name="fulladdress">
						</label>
					</div>
			      </div>

			      <div class="modal-footer" style="background: #f5f5f5">
			        <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">Đóng</button>
			        <button type="button" class="btn btn-gray-black float-right btn-addfulladdress" data-dismiss="modal"><i class=""></i>Lưu</button>
			      </div>
			    </div>
			  </div>
			</div>

			<div class="modal fade" id="updateIdcard" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">CMND/ID</h4>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Loại hình: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_type" placeholder="Loại hình" name="type" class="col-md-12 no-padding font-size-12" value="CMND">
							<datalist id="l_type">
								<option data-value="cmnd">CMND</option>
								<option data-value="passport">Passport</option>
							</datalist>
	              		</label>
					  </div>
			        <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Số: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input type="text"  placeholder="Số" name="idcard" id="idcard_modal" class="col-md-12 no-padding font-size-12" value="<?php echo $detail[0]['idcard'] ?>" />
	              		</label>
					  </div>
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Ngày cấp: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input placeholder="Ngày cấp" name="issueddate" class="col-md-12 no-padding font-size-12" id="issueddate" value="<?php echo $detail[0]['issueddate']; ?>">
	              		</label>
					  </div>
					  
			      	<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Nơi cấp: </label>
					    <label class="control-label col-md-8 no-padding-right">
					    <input list="l_city" placeholder="Nơi cấp" name="issuedplace" class="col-md-12 no-padding font-size-12" id="issuedplace" value="<?php echo $detail[0]['issuedplace'] ?>">
							<datalist id="l_city">
							</datalist>
						</label>
					</div>
			      </div>

			      <div class="modal-footer" style="background: #f5f5f5">
			        <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">Đóng</button>
			        <button type="button" class="btn btn-primary float-right btn-update-idcard"><i class=""></i>Lưu</button>
			      </div>
			    </div>
			  </div>
			</div>

		<div class="modal fade" id="updateFullAddress" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">Sửa địa chỉ</h4>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
			      	<input type="hidden" name="" id="addressid" value="">
			      	<div class="form-group">
					    <label class="control-label col-md-12 no-padding-right">
					    <input class="col-md-12 no-padding font-size-12" placeholder="Nhập nhãn địa chỉ" maxlength="30" style="
  border-bottom: 1px solid #DBDBDB;" id="label_edit">
						</label>
					</div>

			      	<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Quốc gia: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_country" placeholder="Quốc Gia" value="Việt Nam" name="country" id="country_edit" class="col-md-12 no-padding font-size-12">
							<datalist id="l_country">
		              				<option>Việt Nam</option>
							</datalist>
		              	</label>
					  </div>
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Tỉnh / Thành Phố: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_city" placeholder="Tỉnh / Thành Phố" id="city_edit" name="city" class="col-md-12 no-padding font-size-12">
							<datalist id="l_city">
								<?php 
		              			if(isset($city)){
		              			foreach ($city as $rows) { ?>
		              				<option id-city="<?php echo $rows->id_city?>" value="<?php echo $rows->name?>"></option>
		              			<?php }} ?>
							</datalist>
	              		</label>
					  </div>
			        <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Quận / Huyện: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_distr" placeholder="Quận / Huyện" id="district_edit" name="district" class="col-md-12 no-padding font-size-12">
							<datalist id="l_distr">
							</datalist>
	              		</label>
					  </div>
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Phường / Xã: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_ward" placeholder="Phường / Xã" id="ward_edit" name="ward" class="col-md-12 no-padding font-size-12">
							<datalist id="l_ward">
							</datalist>
	              		</label>
					  </div>
					  
			      	<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Tên đường: </label>
					    <label class="control-label col-md-8 no-padding-right">
					    <input  placeholder="<NAME>" value="" id="street_edit" class="col-md-12 no-padding font-size-12"  id="fulladdresstemp" placeholder="Địa chỉ" maxlength="30" name="fulladdress">
						</label>
					</div>
					<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Số nhà: </label>
					    <label class="control-label col-md-8 no-padding-right">
					    <input  placeholder="Số nhà" id="address_edit" value="" class="col-md-12 no-padding font-size-12"  placeholder="Địa chỉ" maxlength="30" name="fulladdress">
						</label>
					</div>
			      </div>

			      <div class="modal-footer" style="background: #f5f5f5">
			        <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">Đóng</button>
			        <button type="button" class="btn btn-gray-black float-right btn-updatefulladdress"><i class=""></i>Lưu</button>
			      </div>
			    </div>
			  </div>
			</div>

			<div class="modal fade" id="modalDeleteAddress" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 7%" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">Xoá Địa Chỉ</h4>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
			        <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bạn có chắc muốn xoá không?</p>
			        <input type="hidden" id="addressid_delete" name="addressid_delete">
			      </div>
			      <div class="modal-footer">
			        <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">Đóng</button>
			        <button type="button" onclick="deleteAddress()" class="btn btn-delete btn-danger"><i class=""></i>Xoá</button>
			      </div>
			    </div>
			  </div>
			</div><file_sep><main class="app-content padding-5 no-padding-right">
      <div class="row">
        <div class="col-md-3 no-padding padding-left-10 col-md-22">
          	<div class="padding-5 margin-bot-5">
	        	<div class="clearfix">
	        		<div>
		          		<h5 class="tile-title folder-head font-size-12 font-weight-500">Phân chia phiếu <a href="javascript:window.location.reload();" ><i class="fa fa-sync-alt fa-md float-right margin-top-3"></i></a></h5>
		          	</div>
	          		<ul class="nav nav-pills flex-column margin-left-5">
		                <li>
		                	<a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3 active show" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','0',false);">
		                		<p class="no-padding no-margin padding-left-right-10"> Phiếu chưa xử lý của tôi
		                		<label class="float-right">
		                			<?php /*
		                				$i = 0;
		                			if(count($result['data'])>0 && $result['code']==1)
		                			{
		                				//&&  $value['hidden'] == '0'
		                			foreach ($result['data'] as $value) {
		                				if($value['status'] ==0 && $value['agentcurrent']==$custid  && $value['status'] != 9)
		                				{
		                					$i++;
		                				}
		                			}
		                			}
		                				echo $i;
		                				*/
		                				echo $phieuchuaxuly;
		                			 ?>
		                		</label></p>
		                	</a>
		                </li>
		                
		                <li>
		                	<a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','4',false);">
		                		<p class="no-padding no-margin padding-left-right-10"> Phiếu đã hoàn thành
		                		<label class="float-right">
		                			<?php 
		                			/*
		                				$i = 0;
		                			if(count($result['data'])>0 && $result['code']==1)
		                			{
		                			foreach ($result['data'] as $value) {
		                				if($value['status'] == 4 && $value['agentcurrent']==$custid && $value['status'] != 9)
		                				{
		                					$i++;
		                				}
		                			}
		                			}
		                				echo $i;
		                				*/
		                				echo $phieudahoanthanh;
		                			 ?>
		                		</label></p>
		                	</a>
		                </li>

		                <li>
		                	<a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','-1',true);">
		                		<p class="no-padding no-margin padding-left-right-10"> Phiếu liên quan
		                		<label class="float-right">
		                			<?php 
		                			/*
		                				$i = 0;
		                			if(count($result['data'])>0 && $result['code']==1)
		                			{
		                			foreach ($result['data'] as $value) {
		                				if(($value['agentcreated']==$custid || strpos($value['ticketusers'], $custid) !== false) &&  $value['status'] != 9)
		                				{
		                					$i++;
		                				}
		                			}
		                			}
		                				echo $i;
		                				*/
		                				echo $phieulienquan;
		                			 ?>
		                		</label></p>
		                	</a>
		                </li>
		                <li>
		                	<a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="locphieu('<?php echo $custid;?>','-1',false);">
		                		<p class="no-padding no-margin padding-left-right-10"> Toàn bộ phiếu của tôi
		                		<label class="float-right">
		                			<?php 
		                			/*
		                				$i = 0;
		                			if(count($result['data'])>0 && $result['code']==1)
		                			{	
			                			foreach ($result['data'] as $value) {
			                				
		                					if($value['agentcurrent'] == $custid && $value['status'] != 9)
		                					{
		                						$i++;
		                					}
			                			}
		                			}
		                				echo $i;
		                				*/
		                				echo $toanbophieu;
		                			 ?>
		                		</label></p>
		                	</a>
		                </li>
		                <li>
		                	<a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="loctheonhom(0);">
		                		<p class="no-padding no-margin padding-left-right-10"> Toàn bộ phiếu của nhóm
		                		<label class="float-right">
		                			<?php echo isset($counter['count_group'])?$counter['count_group']:'0'?>
		                		</label></p>
		                	</a>
		                </li>
		                <li>
		                	<a id="a_appbarticket" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" role="tab" data-toggle="tab" href="#" onclick="loctheonhom(1);">
		                		<p class="no-padding no-margin padding-left-right-10"> Phiếu của nhóm chưa xử lý
		                		<label class="float-right">
		                			<?php echo isset($counter['count_group_status'])?$counter['count_group_status']:'0'?>
		                		</label></p>
		                	</a>
		                </li>
	              	</ul>
	        	</div>
	        </div>
        </div>
        <iframe class="iframesearch" id="iframesearch" style="width: 78%;height:1000px;display: block; border: none;"  src="<?php echo base_url() ?>search/rightSearchTicket/?search=&agentcreated=&agentcurrent=<?php echo $custid;?>&priority=&status=0&lienquan=false"></iframe>
    </div>
</main>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 5%" role="document">
    <div class="modal-content">
    	<form name="insertTicket" class="insertTicket" action="<?php echo base_url().'ticket/insertTicket' ?>" method="POST" enctype='multipart/form-data'>
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Tạo phiếu thủ công </h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
      <div class="modal-body">
      		<div class="form-group">
		    <label for="exampleInputEmail1">Tvcdb</label>
		    <input type="text" class="form-control" id="tvcdb" name="tvcdb" placeholder="Tvcdb">
		  </div>

		  <div class="form-group">
		    <label for="exampleInputEmail1">Ticket Id</label>
		    <input type="text" class="form-control" id="ticketid" name="ticketid" placeholder="Ticket Id">
		  </div>

		  <div class="form-group">
		    <label for="exampleInputEmail1">Customer Id</label>
		    <select class="control-label col-md-12 no-padding-right" name="custid">
      			<?php 
      			if(count($customer['data'])>0)
		                			{
      			foreach ($customer['data'] as $rows) { ?>
      				<option value="<?php echo $rows['custid'] ?>"><?php echo $rows['custname'] ?></option>
      			<?php }} ?>
			</select>
		  </div>

		  <div class="form-group">
		    <label for="exampleInputEmail1">Priority</label>
		    <input type="text" class="form-control" id="priority" name="priority" placeholder="Priority">
		  </div>

		  <div class="form-group">
		    <label for="exampleInputEmail1">Title</label>
		    <input type="text" class="form-control" id="title" name="title" placeholder="Title">
		  </div>

		  <div class="form-group">
		    <label for="exampleInputEmail1">Loại phiếu</label>
		    <select class="control-label col-md-12 no-padding-right" name="status">
      			<option value="1">Phiếu chưa xử lý của tôi</option>
      			<option value="2">Phiếu đang xử lý của tôi</option>
      			<option value="3">Phiếu chưa phân phối</option>
      			<option value="4">Phiếu chưa xử lý của nhóm</option>
      			<option value="5">Phiếu đang xử lý của nhóm</option>
      			<option value="6">Toàn bộ phiếu của nhóm</option>
			</select>
		  </div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary ">Tạo Phiếu</button>
      </div>
      </form>
    </div>
  </div>
</div>
<file_sep><main class="app-content padding-5 no-padding-right">
	<form id="all-in"><input type="hidden" name="taskid" value="<?php echo($record[0]['taskid'])?>">
    <div class="row">
        <div class="col-md-3 no-padding padding-left-15 height-1024">
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-103">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Người yêu cầu</label>
		              	<select disabled="" data-placeholder="Chọn người yêu cầu..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="taskmaster" log="Người yêu cầu" old-value="<?php echo($record[0]['taskmaster'])?>">
	              			<option value="" ></option>
	              			<?php if (isset($l_cus)) {
                              	foreach ($l_cus as $cus) {
                              		if ($cus['custname']!='') {
                              			$s = '';
                              			if ($record[0]['taskmaster']==$cus['custid']) {
                              				$s = 'selected';
                              			}
                              			echo('<option '.$s.' value="'.$cus['custid'].'">'.$cus['custname'].'</option>');
                              		}
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Nhóm phụ trách</label>
	              		<select data-placeholder="Chọn nhóm phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="tic" log="Nhóm phụ trách" old-value="<?php echo($record[0]['tic'])?>">
	              			<option value=""></option>
	              			<?php if (isset($l_agentgroup)) {
	              				foreach ($l_agentgroup as $key => $value) {
	              					$s = '';
                          			if ($record[0]['tic']==$value['groupid']) {
                          				$s = 'selected';
                          			}
	              					echo '<option '.$s.' value="'.$value['groupid'].'">'.$value['groupname'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phụ trách</label>
		              	<select data-placeholder="Chọn người phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="pic" log="Phụ trách" old-value="<?php echo($record[0]['pic'])?>">
	              			<option value=""></option>
	              			<?php if (isset($l_age)) {
                              	foreach ($l_age as $cus) {
                              		if ($cus['custname']!='') {
                              			$s = '';
                              			if ($record[0]['pic']==$cus['custid']) {
                              				$s = 'selected';
                              			}
                              			echo('<option '.$s.' value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>');
                              		}
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phiếu liên quan</label>
		              	<select data-placeholder="Chọn phiếu liên quan..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="ticketid" log="Phiếu liên quan" old-value="<?php echo($record[0]['ticketid'])?>">
	              			<option value=""></option>
	              			<?php if (isset($l_ticket)) {
                              	foreach ($l_ticket as $cus) {
                              		$s = '';
                          			if ($record[0]['ticketid']==$cus['ticketid']) {
                          				$s = 'selected';
                          			}
                              		echo('<option '.$s.' value="'.$cus['ticketid'].'">'.$cus['ticketid'].'</option>');
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="hide">
	            		<label class="control-label user-label col-md-4 no-padding">CCs</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="ccs">
	              			<option value="1">ccs</option>
	              		</select>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-102">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Độ ưu tiên</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="priority" log="Độ ưu tiên" old-value="<?php echo($record[0]['priority'])?>">
	              			<option value="1" <?php if($record[0]['priority']==1) echo "selected";?>>Thường</option>
	              			<option value="2" <?php if($record[0]['priority']==2) echo "selected";?>>Cao</option>
	              			<option value="3" <?php if($record[0]['priority']==3) echo "selected";?>>Khẩn cấp</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Độ nghiêm trọng</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="severity" log="Độ nghiêm trọng" old-value="<?php echo($record[0]['severity'])?>">
	              			<option value="1" <?php if($record[0]['severity']==1) echo "selected";?>>Thường</option>
	              			<option value="2" <?php if($record[0]['severity']==2) echo "selected";?>>Cao</option>
	              			<option value="3" <?php if($record[0]['severity']==3) echo "selected";?>>Khẩn cấp</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Trạng thái</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="status" log="Trạng thái" old-value="<?php echo($record[0]['status'])?>">
	              			<option value="O" <?php if($record[0]['status']=="O") echo "selected";?>>Chờ xác nhận</option>
	              			<option value="W" <?php if($record[0]['status']=="W") echo "selected";?>>Đang xử lý</option>
	              			<option value="C" <?php if($record[0]['status']=="C") echo "selected";?>>Hoàn thành</option>
	              			<option value="X" <?php if($record[0]['status']=="X") echo "selected";?>>Hủy</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ghi chú T.thái</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12 crm-control" placeholder="Nhập ghi chú..." name="statusnote" 
		              		value="<?php echo $record[0]['statusnote']?>" log="Ghi chú T.thái" old-value="<?php echo($record[0]['statusnote'])?>">
		              	</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-101">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phân loại</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" log="Phân loại" name="tasktype" id="level_1" old-value="<?php echo($record[0]['tasktype'])?>">
	              			<?php if (isset($l_type) && !empty($l_type)) {
	              				foreach ($l_type as $key => $value) {
	              					$sel = '';
	              					if ($record[0]['tasktype']==$value['code']) {
	              						$sel = 'selected';
	              					}
	              					echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Chi tiết CV</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" name="taskdetail" log="Chi tiết CV" id="level_2" old-value="<?php echo($record[0]['taskdetail'])?>">
	              			<?php if (isset($l_detail)) {
	              				foreach ($l_detail as $key => $value) {
	              					$sel = '';
	              					if ($record[0]['taskdetail']==$value['code']) {
	              						$sel = 'selected';
	              					}
	              					$c='';
	              					if ($value['ref1']!=$record[0]['tasktype']) {
	              						$c="hide";
	              					}
	              					echo '<option class="'.$c.'" '.$sel.' ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày yêu cầu</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12 crm-control" log="Ngày yêu cầu" placeholder="dd-mm-yy hh:ii" name="req_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['requestdate']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['requestdate']))?>">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Thời hạn OLA</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12 crm-control" log="Thời hạn OLA" placeholder="dd-mm-yy hh:ii" name="ola_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['sla']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['sla']))?>">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày hẹn</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12 crm-control" log="Ngày hẹn" placeholder="dd-mm-yy hh:ii" name="due_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['duedate']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['duedate']))?>">
		              	</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="hide">
	            		<label class="control-label user-label col-md-4 no-padding">Đếm ngược</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="số ngày">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Hoàn thành</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12 crm-control" log="Hoàn thành" placeholder="dd-mm-yy hh:ii" name="fns_date" value="<?php echo date('d-m-Y h:i',strtotime($record[0]['finishdate']))?>" old-value="<?php echo date('d-m-Y h:i',strtotime($record[0]['finishdate']))?>">
		              	</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-100 hide">
	            <div class="tile-body padding-left-right-10">
	              	<div class="row margin-top-5 height-100">
	            		<label class="control-label user-label col-md-4 no-padding">File đính kèm</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              		</label>
	            	</div>
	            </div>
          	</div>
          	<input type="hidden" name="changelog">
		</div>
		<div class="col-md-7 no-padding padding-left-5">
		    <div class="tile no-margin-bot">
		        <div class="content-title">
			        <div class="div margin-bot-10 width-100per">
			          	<h5 class="flex">
			          		<i class="fa fa-lg fa-file-alt header-icon"></i>
			          		<input class="font-size-18 width-100per crm-control" type="text" required="" name="title" placeholder="Tiêu đề Công việc" value="<?php echo $record[0]['title'];?>" log="Tiêu đề" old-value="<?php echo $record[0]['title'];?>">
			          		<button class="btn btn-primary" type="button" id="btn-accept" taskid="<?php echo $this->uri->segment(3) ?>">
				          	  	<i class="fa fa-share"></i>
				          	  Tiếp nhận</button>
			          	</h5>
			          	<p class="header-desc field-click-able">
			          		<!-- <input class="font-size-12" type="text" name="explain" placeholder="Diễn giải"> -->
			          	</p>
			        </div>
			    </div>
			    <div class="break-line margin-bot-5"></div>
			    <div class="row">
			    	<div class="col-md-12 comment-wrap">
						<div class="photo">
							<img class="avatar" src="<?php echo($this->session->userdata('avatar'));?>">
							<input type="hidden" name="avatar" value="<?php echo($this->session->userdata('avatar'));?>">
						</div>
						<div class="comment-block">
							<!-- <p class="no-margin">Trả lời</p> -->
							<div class="status-upload">
								<form>
									<!-- <ul>
										<li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="Text"><i class="fa fa-font"></i></a></li>
										<li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="File"><i class="fa fa-paperclip"></i></a></li>
									</ul> -->
									<!-- <button type="submit" class="btn btn-success green"><i class="fa fa-share"></i> Share</button> -->
									<textarea name="cmt" placeholder="Nhập bất kỳ một nội dung?"></textarea>
								</form>
							</div><!-- Status Upload  -->
							<button type="submit" class="btn btn-gray float-right margin-top-5 margin-bot-5"><i class="fa fa-share"></i> Lưu thay đổi
							</button>
						</div>
					</div>
				</div>
		  	</div>
		<div class="comments">
			<p>Lịch sử công việc</p>
			<?php if (isset($comment)) {
				foreach ($comment as $key => $value) {
			?>
			<div>
				<div class="comment-wrap">
					<div class="photo">
						<img class="avatar" src="<?php echo($value['avatar'])?>">
					</div>
					<div class="comment-block padding-5">
						<p class="comment-text"><?php echo($value['custname'])?></p>
						<p class="comment-text"><?php echo($value['tskaction'])?></p>
						<p class="comment-text"><?php echo($value['comments'])?></p>
						<div class="bottom-comment">
							<div class="comment-date"><?php echo($value['changelog'])?></div>
						</div>
					</div>
				</div>
				<ul class="app-breadcrumb breadcrumb react-comment">
		    		<p class="margin-right-30"><?php echo date('d-m-Y h:i',strtotime($value['createddate']))?></p>
			        <!-- <li class="breadcrumb-item"><a href="#">Phản hồi</a></li> -->
			        <!-- <li class="breadcrumb-item"><a href="#">Tạo công việc</a></li> -->
		        </ul>
		    </div>
		    <?php }} ?>
		</div>
	</div>
	</form>
</main><file_sep><script type="text/javascript">
		$(document).ready(function(){

			$('.knl-caret').click(function(){
				var caret = $('.fa-angle-double-down');
				if (caret.length>0) {
					$('.knl-caret').removeClass('fa-angle-double-down');
					$('.knl-caret').addClass('fa-angle-double-up');
				}else{
					$('.knl-caret').addClass('fa-angle-double-down');
					$('.knl-caret').removeClass('fa-angle-double-up');
				}
				$(".knl-board").slideToggle("slow");
			});

			$('i.search-knowledge').click(function(){
				var text = $('input[name="knl_text"]').val();
				search(text,'','','');
			});

			$('#knl-btn-back').click(function(){
				$('.knl-content').css('display','none');
                $('#knl_list').css('display','block');
			});

			$('input[name="knl_text"]').keypress(function(e){
			    if(e.keyCode==13){          // if user is hitting enter
			        var text = $('input[name="knl_text"]').val();
					search(text,'','','');
			    }
		  	});
		});
	function search(text='',type='',group='',detail=''){
		var query = '?';
		if (text!='') {query+=('search='+text);}
		if (type!='') {query+=('tickettype='+type);}
		if (group!='') {query+=('groupid='+group);}
		if (detail!='') {query+=('categoryid='+detail);}
		if ($('.knl-caret').hasClass('fa-angle-double-up')) {$('.knl-caret').trigger('click');}
		var url = '<?php echo base_url().'knowledge/fulltext'?>'+query;
		if (query!='' && query.length<=100) {
			$('.knl-content').css('display','none');
        	$('#knl_list').html('Đang tải dữ liệu...').css('display','block');
			$.ajax({
	          url: url,
	          type: 'GET',
	          dataType: 'JSON'
	        })
	        .done(function(data) {
	          console.log(data);
	          var div = '';
	          if(data){
	          for (var i = 0; i < data.length; i++) {
	          	div+='<p><a style="cursor: pointer; color: #009688" onclick="showDetailKnowledge('+data[i]['id']+')">#'+data[i]['title']+'</a></p>';
	          	// if (i==2) {break;}
	          }
	          if (div!='') {
	          	$('#knl_list').html(div).css('display','block');
	          }else{
	          	$('#knl_list').html('Không tìm thấy kết quả nào.');
	          }
	          }else {$('#knl_list').html('Không tìm thấy kết quả nào.');}
	        })
	        .fail(function() {
	            parent.alertLog('Cảnh báo',"Lỗi hệ thống",'warning');
	        });
		}else if(query.length>100){
			parent.alertLog('Cảnh báo',"Chiều dài không phù hợp",'warning');
		}else{
			parent.alertLog('Cảnh báo',"Vui lòng điền từ khóa",'warning');
		}
	}
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Knowledge extends CI_Controller {

	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url','json_output'));
    }

	public function index()
	{
		$_data = [];    
		$json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/select/') ;
		$knowledge['news'] = json_decode($json_data,true)['data'];
		$agent = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getcustomerbyroleid/2');
		$knowledge['agent'] = json_decode($agent,true)['data'];

		$l_group = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwgroup');
		$knowledge['l_group'] = json_decode($l_group,true)['data'];

		$l_cate = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwdetail');
		$knowledge['l_cate'] = json_decode($l_cate,true)['data'];

		$l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tcktype');
		$knowledge['l_type'] = json_decode($l_type,true)['data'];

		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('knowledge/knowledge', $knowledge , TRUE);
		$_data['script'] = $this->load->view('script/script_knowledge', NULL, TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function detail($action = 'add',$id ='')
	{
		$_script = [];
		if($action =='add')
		{
			$_script['action'] = 'add';
		}
		$_data = [];   
		$data=[]; 
		if($action=='edit')
		{
			$json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/select/'.$id);
			$data['knowledge'] = json_decode($json_data,true)['data'];
		}

		$l_group = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwgroup');
		$data['l_group'] = json_decode($l_group,true)['data'];

		$l_cate = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwdetail');
		$data['l_cate'] = json_decode($l_cate,true)['data'];

		$l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tcktype');
		$data['l_type'] = json_decode($l_type,true)['data'];

		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('knowledge/detail', $data , TRUE);
		$_data['script'] = $this->load->view('script/ckeditor', $_script, TRUE);

		$this->load->view('dashboard',$_data);
	}

	public function detailKnowledge()
	{
		$id = $this->input->post('id');
		$json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/select/'.$id) ;
		echo $json_data;
	}

	public function insertKnowledge()
	{
		$var = $this->session->userdata;
        $log_custid = $var['custid'];
        $log_roleid = $var['roleid'];
        $log_groupid = $var['groupid'];
		$data = $this->input->post();
		$postdata = http_build_query([
				'log_groupid' => $log_groupid,
                'title' => isset($data['title'])?$data['title']:null,
                'article' => isset($data['article'])?$data['article']:null,
                'groupid' => isset($data['group'])?$data['group']:null,
                'categoryid' => isset($data['cate'])?$data['cate']:null,
                'hidden' => isset($data['status'])?$data['status']:null,
                'tickettype' => isset($data['type'])?$data['type']:null,
                'createby' => $this->session->userdata('custid'),
                'ticketprioty' => isset($data['ticketprioty'])?$data['ticketprioty']:null
        ]); 
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/insert',false,$context) ;
        echo $result;
	}

	public function updateKnowledge()
	{
		$var = $this->session->userdata;
        $log_custid = $var['custid'];
        $log_roleid = $var['roleid'];
        $log_groupid = $var['groupid'];
		$data = $this->input->post();
		$postdata = http_build_query([
				'log_groupid' => $log_groupid,
                'title' => isset($data['title'])?$data['title']:null,
                'article' => isset($data['article'])?$data['article']:null,
                'groupid' => isset($data['group'])?$data['group']:null,
                'categoryid' => isset($data['cate'])?$data['cate']:null,
                'hidden' => isset($data['status'])?$data['status']:null,
                'tickettype' => isset($data['type'])?$data['type']:null,
                'ticketprioty' => isset($data['ticketprioty'])?$data['ticketprioty']:null
        ]); 
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/update/'.$data['id'],false,$context) ;
        echo $result;
	}


	public function search()
	{
		$get = $this->input->get();
		$query = '?';
		foreach ($get as $key => $value) {
			$v = '';
			if (($key=='categoryid' || $key=='tickettype' || $key=='groupid') && $value == "all") {
				$v = '';
			}else{
				$v = $value;
			}
			$query.=$key.'='.rawurlencode($v).'&';
		}  
		$json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/search'.$query);
		$knowledge['news'] = json_decode($json_data,true)['data'];

		$l_group = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwgroup');
		$knowledge['l_group'] = json_decode($l_group,true)['data'];

		$l_cate = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/knwdetail');
		$knowledge['l_cate'] = json_decode($l_cate,true)['data'];

		$l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tcktype');
		$knowledge['l_type'] = json_decode($l_type,true)['data'];
		$_data['script'] = $this->load->view('script/script_knowledge', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('knowledge/iframe', $knowledge , TRUE);
		$this->load->view('dashboard',$_data);
		// echo $query;
	}

	public function fulltext()
	{
		$get = $this->input->get();
		$query = '?';
		foreach ($get as $key => $value) {
			$query.=$key.'='.rawurlencode($value).'&';
		}  
		$json_data = file_get_contents('http://test.tavicosoft.com/crm/index.php/news/search'.$query);
		$knowledge = json_decode($json_data,true)['data'];
		json_output(200,$knowledge);
	}
}<file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-18 no-padding padding-left-10">
          	<?php echo isset($left)?$left:'' ?>
        </div>
        <div class="col-md-7 col-md-64 no-padding padding-left-1">

        <iframe class="iframesetting" id="iframesetting" style="width: 100%;display: block; border: none;height: 100vh"  src="<?php echo base_url().'setting/viewUser' ?>"></iframe>
        </div>
        <div class="col-md-2 col-md-18 no-padding padding-left-5">
        	<?php echo isset($right)?$right:'' ?>
        </div>
    </div>
</main><file_sep><?php $custidCustomer = $this->input->get('cusid');
	  $var = $this->session->userdata;
      $agentcurrent = $var['custid'];
      $groupid = $var['groupid'];
?>
<div class="tile">
	            <div class="content-title">
			        <div class="div">
			          	<h5><img class="user-avatar" src="<?php echo $user[0]['avatar'] ?>" alt="User Image" onerror="this.src='https://www.freewebmentor.com/default-avatar.png'"> <?php echo $user[0]['custname'] ?></h5>
			        </div>
			        <button class="btn btn-blank" id="btn-plus-ticket" onclick="insertTicket('<?php echo $custidCustomer ?>','<?php echo $agentcurrent ?>','<?php echo $groupid ?>')" type="button"><i class="fas fa-plus"></i> Phiếu hỗ trợ  </button>
			        <button id="demoSwal" style="display: none;" class="btn btn-blank" type="button">+ Phiếu hỗ trợ  </button>
			        <button id="demoNotify" style="display: none;" type="hidden" class="btn btn-blank" type="button">+ Thông báo  </button>
			        <button id="demoModal" style="display: none;" type="hidden" class="btn btn-blank" type="button">+ Modal  </button>
			    </div>
			    <div class="bs-component">
	              	<ul class="nav nav-tabs">
		                <li class="nav-item">
		                	<a class="user-tab active show" id="tab1" data-toggle="tab" href="#tab-content-1">Giao dịch (<?php 
		                				$i = 0;
		                				if(count($trade)>0)
		                				{
		                			foreach ($trade as $value) {
		                					$i++;
		                			}}
		                				echo $i;
		                			 ?>)</a>
		                </li>
		                <li class="nav-item">
		                	<a class="user-tab" id="tab2" data-toggle="tab" href="#tab-content-2">Phiếu (<?php 
		                				echo count($ticket);
		                			 ?>)</a>
		                </li>
	              	</ul>
	              	<div class="tab-content" id="myTabContent">
		                <div class="tab-pane fade" id="tab-content-2">

		                	
		                  	<div class="table-responsive" style="height: 400px" id="div-content-2">
				              	<table class="table" id="table-1-ticket">
				              		<thead class="no-border-top">
				              			<tr>
				              				<th width="9%">ID</th>
				              				<th width="20%">Tiêu đề</th>
				              				<th width="6.8%">Ngày y/cầu</th>
				              				<th width="20%">Người p/trách</th>
				              				<th width="9%">Ngày c/nhật</th>
				              			</tr>
				              		</thead>
					                <tbody>
					                	<?php 
					                	if(count($ticket) >0)
					                	{
					                	foreach ($ticket as $rows) {
					                		/*
					                		if(( $rows['custid'] == $agentcurrent ||strpos($rows['ticketusers'],$agentcurrent)!==false || $groupid == $rows['groupid'] ) && $rows['hidden'] =='0')
					                		{
					                			*/
					                	 ?>
						                  	<tr class="border-bot-1">
							                    <td>
							                    	<a onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.$rows['custid'] ?>','#<?php echo $rows['ticketid'] ?>')" href="#">
							                    	<span class="id-label span-danger">O</span>  #<?php echo $rows['ticketid'] ?></a>
							                    </td>
							                    <td>
							                    	<?php echo $rows['title'] ?>
							                    </td>
							                    <td>
							                    	<?php echo date("d/m/Y", strtotime($rows['createat'])); ?>
							                    </td>
							                    <td><?php echo $rows['name'] ?></td>
							                    <td>
							                    	<?php echo date("d/m/Y", strtotime($rows['lastupdate'])); ?></td>
						                  	</tr>
					                	<?php //}
					                }} ?>
					                </tbody>
				              	</table>
				            </div>
		                </div>
		                <div class="tab-pane fade" id="tab-content-3">
		                  <p>Phiếu liên quan.</p>
		                </div>
		                <div  class="tab-pane fade active show" id="tab-content-1">
		                	<div class="table-responsive" id="div-content-1" style="height: 294px;">
		                		<table class="table table-striped table-bordered" cellspacing="0" id="table-1-contract">
				              		<thead>
								    <tr>
								        <th width="60px">Mã GD</th>
			              				<th width="80px">Tình trạng</th>
			              				<th width="90px">Mã căn hộ</th>
			              				<th width="73px">Ngày bắt đầu</th>
			              				<th width="75px">Ngày hiệu lực</th>
				              			<th width="250px">Ghi chú</th>
								    </tr>
									</thead>
									
				              	</table>
				            </div>
		                </div>
	              	</div>
	            </div>
          	</div><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 padding-left-15">
          	<?php echo isset($left)?$left:'' ?>
        </div>

        <div class="col-md-7 padding-left-1">
          	<?php echo isset($center)?$center:'' ?>
        </div>
        <div class="col-md-2 col-md-18 padding-left-5">
        	
        </div>
    </div>
</main>
<!-- <main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-3 no-padding padding-left-15">
          	<div class="tile p-0 padding-5 margin-bot-5 height-1024">
	            <div class="tile-body padding-left-10 vertical-top" id="search_area">
	              	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giai đoạn</label>
	              		<select name="name" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_1">
	              			<option value="all" selected="">Tất cả</option>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Trạng thái</label>
	              		<select name="status" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_2">
	              			<option value="W" selected="">Working</option>
	              			<option value="C" selected="">Closed</option>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ghi chú</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<textarea class="col-md-12 no-padding font-size-12 control-textarea" placeholder="Nhập bất kỳ một nội dung..."></textarea>
			            </label>
	            	</div>
	            	<div class="flex offset-10 margin-top-10">
	            		<button id="btn-search" class="btn btn-primary float-right" type="button">Lưu</button>
	            	</div>
	           	</div>
          	</div>       
	    </div>
        <div class="col-md-6 col-md-78 no-padding padding-left-5">
        </div> 
    </div>
</main> --><file_sep>function removeTab()
        {
            var id = window.top.$(".nav-tabs").children().length;
            var idtab = window.top.$(".nav-tabs").find("li > a.active").attr('href');
            var idnavbar = window.top.$(".nav-tabs").find("li > a.active").parent();
            $(idnavbar).remove();
            $(idtab).remove();
            window.top.$('.nav-tabs li:nth-child(' + (id-1) + ') a').click();
        }

function addTab(link,title,checkInsert) {
	 var x = Math.floor((Math.random() * 999) + 1);
    var id = window.top.$(".nav-tabs").children().length;
    var idtab = window.top.arrayTab[x];
    window.top.arrayTab.splice(x, 1);
      var ulChildren = window.top.$(".nav-tabs").children();  
      var link = link;
      var title = title;
      var checkLink = false;
      if(checkInsert == true)
      {
           window.top.$( ".nav-link" ).removeClass( "active" );
          window.top.$( ".tab-pane" ).removeClass( "active" );
           //think about it ;)
          window.top.$('.nav-tabs li:nth-child('+id+')').after('<li class="nav-item width-170  role="presentation"">\
      <a class="nav-link active show" name="'+link+'" role="tab" data-toggle="tab" href="#'+idtab+'" title="'+title+'" >\
        <i class="fas fa-tags"></i> \
        <span class="">'+title+'</span> </a><span class="fa fa-times" aria-hidden="true"></span>\
    </li>');
          window.top.$('.tab-content').append('<div class="tab-pane active" id="' + idtab + '"><iframe id="myiframe1" class="myiframe" name="myiframe'+id+'" src="'+link+'" frameborder="0"></iframe></div>');
          var widthsub = window.top.$('.nav-insert').width() * 2;
          var width = window.top.$('#lengthmenu').width() - widthsub;
              if(id >4)
              {
                  window.top.$("ul.nav-tabs li").each(function(){
                    $(this).attr('style', 'width:'+width/(id+1)+'px !important;');
                  });
                 
              }
              else{
                window.top.$("ul.nav-tabs li").each(function(){
                    $(this).attr('style', 'width:170px !important;');
                  });
              }
          var i = id+1;
         window.top.$('.nav-tabs li:nth-child(' + i + ') a').click(); 
         return;
      }
      for(var i = 0; i < id ;i++)
        {
          if(ulChildren[i].children[0].nodeName.toLowerCase() === 'a'){
                  if(link == ulChildren[i].children[0].name)
                  {
                    checkLink = true;
                    var j = i+1;
                     window.top.$('.nav-tabs li:nth-child(' + j + ') a').click();
                     break;
                  }
                }
        }
       if(checkLink == true)
                {
                    return;
                }
                else{
        window.top.$( ".nav-link" ).removeClass( "active" );
        window.top.$( ".tab-pane" ).removeClass( "active" );
         //think about it ;)
        window.top.$('.nav-tabs li:nth-child('+id+')').after('<li class="nav-item width-170  role="presentation"">\
    <a class="nav-link active show" name="'+link+'" role="tab" data-toggle="tab" href="#'+idtab+'" title="'+title+'" >\
      <i class="fas fa-tags"></i> \
      <span class="">'+title+'</span> </a><span class="fa fa-times" aria-hidden="true"></span>\
  </li>');
        window.top.$('.tab-content').append('<div class="tab-pane active" id="' + idtab + '"><iframe id="myiframe1" class="myiframe" name="myiframe'+id+'" src="'+link+'" frameborder="0"></iframe></div>');
        var widthsub = window.top.$('.nav-insert').width() * 2;
        var width = window.top.$('#lengthmenu').width() - widthsub;
            if(id >4)
            {
                window.top.$("ul.nav-tabs li").each(function(){
                  $(this).attr('style', 'width:'+width/(id+1)+'px !important;');
                });
               
            }
            else{
              window.top.$("ul.nav-tabs li").each(function(){
                  $(this).attr('style', 'width:170px !important;');
                });
            }
        var i = id+1;
       window.top.$('.nav-tabs li:nth-child(' + i + ') a').click(); 
     }
  }

<file_sep>
<script type="text/javascript">
	$(document).ready(function(){
		$('#ck-edit').click(function(){
			var stt = $('#content').attr('ck-edit');
			var title = $('#knl-title')[0].innerText;$('#knl-title').html('<input name="title" autofocus value="'+title+'">');
			console.log(title);
			if(stt && stt == 'close'){
				console.log('ck-edit is now close');
				var ck = CKEDITOR.replace( 'content' ,{
			        filebrowserBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html',
			        filebrowserImageBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html?type=Images',
			        filebrowserFlashBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html?type=Flash',
			        filebrowserUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
			        filebrowserImageUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
			        filebrowserFlashUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
			        allowedContent: true,
			        disableAutoInline: true,
			        toolbarStartupExpanded : false,
			        toolbarCanCollapse: false,
			        width: '100%',
			        height: 700,
			        });
			    	ck.on( 'change', function( evt ) {
			          // getData() returns CKEditor's HTML content.
			          $('#content').html(evt.editor.getData());
			        });
			    if (ck) {
			    	$('#content').attr('ck-edit','open');
			    	$(this).css('display','none');
			    	$('#ck-save').css('display','block');
			    }
			}else {
				console.log('ck-edit is now open yet');
			}
		});
		$('#ck-save').click(function(){
			var stt = $('#content').attr('ck-edit');
			var action = $(this).attr('action');
			var id = '<?php echo $this->uri->segment(4) ?>';
			var title = $('#knl-title').find('input').val();$('#knl-title').html(title);
			var content = $('#content').html();
			var group = $('select[name="group"]').val();
			var cate = $('select[name="cate"]').val();
			var type = $('select[name="type"]').val();
			var status = $('select[name="status"]').val();
			var ticketprioty = $('select[name="ticketprioty"]').val();
			console.log(title);
			if(stt && stt == 'open'){
				console.log('ck-edit is now open');
				var aInst = CKEDITOR.instances;
				console.log(aInst);
				for (var key in aInst){
				    CKEDITOR.instances[key].destroy();
				}
				$('#content').attr('ck-edit','close');
				$(this).css('display','none');
			    $('#ck-edit').css('display','block');
			}else {
				console.log('ck-edit is now not close yet');
			}
			if(action =='add')
			{
				var url = '<?php echo base_url().'knowledge/insertKnowledge' ?>';
			}
			else{
				var url = '<?php echo base_url().'knowledge/updateKnowledge' ?>';
			}
			$.ajax({
		          url: url,
		          type: 'POST',
		          dataType: 'JSON',
		          data: {id:id,title:title,article: content,group:group,cate:cate,type:type,status:status,ticketprioty:ticketprioty},
		        })
		        .done(function(data) {
		          if(data.code==0){
		             alert('')
		          }
		          alert(data.message);
		          /*
		          		location.href= '<?php echo base_url().'/ticket/detail/' ?>'+data.data;
		              // alert('<?php echo base_url().'/ticket/detail/' ?>'+data.data);
		              */
		          })
		        .fail(function() {
		            alert('Lỗi hệ thống,vui lòng liên hệ admin để được hỗ trợ');
		        });
		});
		var action = '<?php echo isset($action)?$action:'' ?>';
		if(action !='')
		{
			$('#ck-edit').trigger('click');
		}
		var tickettype = $('select#level_1').val();
    if (tickettype!='') {
      $('select#level_2 option').each(function(){
        var ref1 = $(this).attr('ref1');
        if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');}
        else{$(this).addClass('hide').removeClass('show');}
      });
      $('select#level_2 option.show:first').prop('selected',true);
    }

    var groupid = $('select#level_2').val();
    if (groupid!='') {
      $('select#level_3 option').each(function(){
        var ref2 = $(this).attr('ref2');
        if (ref2==groupid) {$(this).removeClass('hide').addClass('show');}
        else{$(this).addClass('hide').removeClass('show');}
      });
      $('select#level_3 option.show:first').prop('selected',true);
    }

		$('select#level_1').change(function(){
	        var val = $(this).val();
	        if(val){
	          $('select#level_2 option, select#level_3 option').each(function(){
	            var ref1 = $(this).attr('ref1');
	            if (ref1==val) {
	              $(this).removeClass('hide').addClass('show');
	            }else{
	              $(this).addClass('hide').removeClass('show');
	            }
	          });
	        }else{
	          $('select#level_2 option, select#level_3 option').each(function(){
	            $(this).removeClass('hide').addClass('show');
	          });
	        }
	        $('select#level_2 option.show:first').prop('selected',true);
        	$('select#level_3 option.show:first').prop('selected',true);
	    });
	    $('select#level_2').change(function(){
	        var val = $(this).val();
	        if(val){
	          $('select#level_3 option').each(function(){
	            var ref2 = $(this).attr('ref2');
	            if (ref2==val) {
	              $(this).removeClass('hide').addClass('show');
	            }else{
	              $(this).addClass('hide').removeClass('show');
	            }
	          });
	        }else{
	          $('select#level_3 option').each(function(){
	            $(this).removeClass('hide').addClass('show');
	          });
	        }
	        $('select#level_3 option.show:first').prop('selected',true);
	    });
	});
    
</script><file_sep>			<?php 
		    if(count($listticketlog) >0)
		    {
		    foreach ($listticketlog as $rows) {
		     ?>
			<div class="padding-left-right-10">
				<div class="comment-wrap">
					<div class="photo">
						<div class="avatar" style="background-image: url('<?php echo 'http://crm.tavicosoft.com/api/avatar/'.$rows['useraction'] ?>')"></div>
					</div>
					<div class="comment-block padding-5">
						<p class="comment-text" style="font-weight: 600"><?php echo $rows['custname'] ?></p>
						<p class="comment-text"><?php echo $rows['cmt']?></p>
						<p class="comment-text"><?php echo $rows['action']?></p>
						
						<?php 
							if(strlen($rows['srcrecord'])>5){
								?>
								<audio controls>
								  <source src="<?php echo $rows['srcrecord'] ?>" type="audio/ogg">
								  Your browser does not support the audio tag.
								</audio>
								<?php
							}
						?>
						
						<div class="bottom-comment">
							<div class="comment-date"><?php echo $rows['changelog']?></div>
						</div>
					</div>
				</div>
				<ul class="app-breadcrumb breadcrumb react-comment">
		    		<p class="margin-right-30"><?php echo date('d-m-Y H:i',strtotime($rows['createdat'])); ?></p>
		        </ul>
		    </div>
		    <?php }} ?><file_sep><form method="POST" id="dataUpdateGroup">
<div class="tile p-0 padding-5 margin-bot-5">
	          <div class="tile-body padding-left-10">
	          		<input type="hidden" name="groupid" value="<?php echo $gdetail['groupid'];?>" id="groupid"/>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Tên nhóm</label>
	              		<label class="control-label col-md-7 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" name="groupname" value="<?php echo $gdetail['groupname']?>" placeholder="Tên nhóm" id="custname" required="" minlength="4" maxlength="30">
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Trạng thái</label>
	              		<select class="control-label col-md-7 no-border no-padding margin-left-10" id="status" name="status">
	              			<option value="0" <?php if($gdetail['status']==0){echo "selected";} ?>>Không hoạt động</option>
	              			<option value="1" <?php if($gdetail['status']==1){echo "selected";} ?>>Đang hoạt động</option>
	              		</select>
	            	</div>
	            </div>
	        </div>
	        <div class="tile p-0 padding-5 margin-bot-5">
	             <div class="tile-body padding-left-10">
	             	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding"></label>
	            		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label2 col-md-3 no-padding">Xem</label>
		            		<label class="control-label user-label2 col-md-3 no-padding">Thêm</label>
		            		<label class="control-label user-label2 col-md-3 no-padding">Sửa</label>
		              	</label>
		            		
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Phiếu</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="ticketrule" id="ticketrule">
	              			<option value="0" >Không</option>
	              			<option value="1" >Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['ticketrule'], 0,1) == '1') echo 'checked'; ?> name="viewticket" id="viewticket" value="1"></label>
		              		<input id='viewtickethidden' type='hidden' value='0' name='viewticket'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['ticketrule'], 1,1) == '1') echo 'checked'; ?> name="addticket" id="addticket" value="1"></label>
		            		<input id='addtickethidden' type='hidden' value='0' name='addticket'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox"  <?php if (substr($gdetail['ticketrule'], 2,1) == '1') echo 'checked'; ?> name="editticket" id="editticket" value="1"></label>
		            		<input id='edittickethidden' type='hidden' value='0' name='editticket'>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Người dùng</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="userrule" id="userrule">
	              			<option value="0">Không</option>
	              			<option value="1">Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['userrule'], 0,1) == '1') echo 'checked'; ?> name="viewuser" id="viewuser" value="1"></label>
		              		<input id='viewuserhidden' type='hidden' value='0' name='viewuser'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['userrule'], 1,1) == '1') echo 'checked'; ?> name="adduser" id="adduser" value="1"></label>
		            		<input id='adduserhidden' type='hidden' value='0' name='adduser'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['userrule'], 2,1) == '1') echo 'checked'; ?> name="edituser" id="edituser" value="1"></label>
		            		<input id='edituserhidden' type='hidden' value='0' name='edituser'>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Công việc</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="taskrule" id="taskrule">
	              			<option value="0">Không</option>
	              			<option value="1">Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['taskrule'], 0,1) == '1') echo 'checked'; ?> name="viewtask" id="viewtask" value="1"></label>
		              		<input id='viewtaskhidden' type='hidden' value='0' name='viewtask'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['taskrule'], 1,1) == '1') echo 'checked'; ?> name="addtask" id="addtask" value="1"></label>
		            		<input id='addtaskhidden' type='hidden' value='0' name='addtask'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['taskrule'], 2,1) == '1') echo 'checked'; ?> name="edittask" id="edittask" value="1"></label>
		            		<input id='edittaskhidden' type='hidden' value='0' name='edittask'>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Thư viện</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="knowledgerule" id="knowledgerule">
	              			<option value="0">Không</option>
	              			<option value="1">Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['knowledgerule'], 0,1) == '1') echo 'checked'; ?> name="viewknowledge" disabled="" id="viewknowledge" value="1"></label>
		              		<input id='viewknowledgehidden' type='hidden' value='1' name='viewknowledge'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['knowledgerule'], 1,1) == '1') echo 'checked'; ?> name="addknowledge" id="addknowledge" value="1"></label>
		            		<input id='addknowledgehidden' type='hidden' value='0' name='addknowledge'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" <?php if (substr($gdetail['knowledgerule'], 2,1) == '1') echo 'checked'; ?> name="editknowledge" id="editknowledge" value="1"></label>
		            		<input id='editknowledgehidden' type='hidden' value='0' name='editknowledge'>
		              	</label>
	            	</div>
	            </div>
 </div>
 			<div class="tile p-0 padding-5 margin-bot-5">
	             <div class="tile-body padding-left-10">
	             	<label class="control-label col-md-4 no-padding" style="font-size: 12px;font-weight: 500;color: rgb(118, 121, 116);"><i class="far fa-window-maximize"></i>  View </label>
	             	<div class="">
	            		<label class="control-label user-label col-md-5 no-padding">Xem tất cả phiếu</label>
	            		<label class="control-label col-md-6 no-padding-right">
		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox"
		            			<?php foreach ($groupdetail['data'] as $key) {
		            				if($key['groupid'] == $gdetail['groupid'])
		            				{
		            					echo 'checked';
		            					break;
		            				}
		            			} ?>
		            		  name="viewpermission" id="viewpermission" value="1"></label>
			              		<input id='viewpermissionhidden' type='hidden' value='0' name='viewpermission'>
			              		<?php $temp = "";
			              		 foreach ($groupdetail['data'] as $key) {
		            				if($key['groupid'] == $gdetail['groupid'])
		            				{
		            					$temp = '1';
		            					break;
		            				}else{
		            					$temp = '0';
		            				}
		            			} ?>
			              		<input type="hidden" name="oldpermission" id="oldpermission" value="<?php echo $temp ?>">
		              	</label>
	            	</div>
	             </div>
	         </div>
	            	<div class="fc-corner-right">
		          		<div class="fc-button-group" style="float:right">
							<button type="button" class="btn btn-primary float-right margin-bot-5" id="btn-uploadgu" onclick="updateGroup()"><i class="fa fa-share"></i>Lưu thông tin</button>
						</div>
		          	</div>
</form><file_sep><?php 
	defined('BASEPATH') OR exit('No direct script access allowed');
	
	class Dashboard extends CI_Controller {
		public function __construct()
		{
			parent::__construct();
			$this->load->library(array('session'));
        	$this->load->helper(array('url'));
		}
		public function index()
		{
			if($this->input->post('custid', TRUE) != '')
			{
				$this->session->set_userdata('custid', $this->input->post('custid', TRUE));
		        $this->session->set_userdata('telephone', $this->input->post('telephone', TRUE));
		        $this->session->set_userdata('custname',$this->input->post('custname',TRUE));
		        $this->session->set_userdata('groupid',$this->input->post('groupid', TRUE));
		        $this->session->set_userdata('avatar',$this->input->post('avatar', TRUE));
		        $this->session->set_userdata('roleid',$this->input->post('roleid', TRUE));
		        $this->session->set_userdata('idcard',$this->input->post('idcard', TRUE));
	        }
			if(!$this->session->userdata("custid"))//If already logged in
		        {
		            redirect(base_url('login'));
		        }

			
			$_data = [];    
			//Role Admin -> go to Setting
			if($this->input->post('roleid', TRUE) == 1){
				$_data['link'] = 'setting';
				$_data['tab_title'] = "Setting";
			}else{
				$var = $this->session->userdata;
        		$roleid = $var['roleid'];
        		if($roleid == 1)
        		{
        			$_data['link'] = 'setting';
					$_data['tab_title'] = "Setting";
        		}
        		else
        		{
				$_data['link'] = 'ticket';
				$_data['tab_title'] = "Ticket";
				}
			}
			$_data['navbar'] = $this->load->view('navbar/navbar', $_data, TRUE); 
			$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
			$_data['mainview'] = $this->load->view('dashboard', NULL , TRUE);
			$_data['script2'] = $this->load->view('script/script_call', NULL, TRUE);
			$_data['nodejs'] = $this->load->view('node/dashboard', NULL, TRUE);
			$_data['script'] = $this->load->view('script/script', NULL , TRUE);
			$this->load->view('master',$_data);
		}
		public function user()
		{
			$_data = [];    
			$_data['link'] = 'user';
			$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
			$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
			$_data['mainview'] = $this->load->view('dashboard', NULL , TRUE);
			$this->load->view('master',$_data);
		}
		public function changePassword()
		{
			$data = $this->input->post();
			$postdata = http_build_query([
            'custid' => $this->session->userdata('custid'),
            'old_pass'=> isset($data['old_pass'])?$data['old_pass']:null,
            'new_pass'=> isset($data['new_pass'])?$data['new_pass']:null
       		]);
	        $opts       = array('http' =>
	            array(
	                'method'  => 'POST',
	                'header'  => 'Content-type: application/x-www-form-urlencoded',
	                'content' => $postdata
	            )
	        );
	        $context  = stream_context_create($opts);

	        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/changepass',false,$context);
	        echo $result;
		}

	}
	
	/* End of file Dashboard.php */
	/* Location: ./application/controllers/Dashboard.php */
?><file_sep><form id="insertUserVal" method="POST" role="form">
<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phân quyền
	              		(<span style="color: red">*</span>)</label>
	              		<select name="roleid" class="control-label col-md-8 no-border no-padding margin-left-10" id="roleid" onchange="selectGroup(this)" required="">
	              			<option selected="true" disabled="true" value="">--Chọn Phân Quyền--</option>
	              			<?php
	              				foreach ($role_list as $key => $value) {
	              					?>
	              						<option value="<?php echo $key ?>" ><?php echo $value?></option>
	              					<?php
	              				}
	              			?>
	              		</select>
	            	</div>
	            	<div class="div-group flex">
	            		<label class="control-label user-label col-md-4 no-padding">Nhóm
	              		(<span style="color: red">*</span>)</label>
	              		<select name="groupid" class="control-label col-md-8 no-border no-padding margin-left-10  grouplist" id="groupid" required="">
	              			<option selected="true" disabled="true" value="">--Chọn Nhóm Quyền--</option>
	              			<?php
	              				foreach ($group_list as $value) {
	              					?>
	              						<option value="<?php echo $value['groupid'] ?>" ><?php echo $value['groupname']?></option>
	              					<?php
	              				}
	              			?>
	              		</select>
	            	</div>
	            </div>
          	</div>

          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Họ và Tên</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập họ tên" name="custname" id="custname">
		              	</label>
	            	</div>
	            	<div class="div-danhxung flex">
	            		<label class="control-label user-label col-md-4 no-padding">Danh xưng</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="gender" id="gender">
	              			<option value="M">Ông</option>
	              			<option value="F">Bà</option>
	              		</select>
	            	</div>

	            	<div class="div-cmnd flex">
	            		<label class="control-label user-label col-md-4 no-padding">CMND/Passport
	              		(<span style="color: red">*</span>):</label>
	              		<label class="control-label col-md-7 no-padding-right">
		              		<input name="idcard_modal" id="idcard_modal" required="" class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập cmnd" required minlength="8">
		              	</label>
	            	</div>
	            	<div class="div-ngaysinh flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày sinh:</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input id="fullbirthday" name="fullbirthday" placeholder="dd-mm-yy" class="col-md-12 no-padding font-size-12" value="">
		              	</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="div-phone flex">
	            		<label class="control-label user-label col-md-4 no-padding">Điện thoại</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input id="telephone" name="telephone" class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập sdt chính">
		              	</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>

	            	<div class="div-email flex">
	            		<label class="control-label user-label col-md-4 no-padding">E-mail</label> 
	            	
	            		<label class="control-label col-md-8 no-padding-right">
		              		<input id="email" name="email" type="email" class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập email chính">
		              	</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Địa chỉ</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_country" placeholder="Quốc Gia" value="Việt Nam" name="country" class="col-md-12 no-padding font-size-12">
							<datalist id="l_country">
		              				<option>Việt Nam</option>
							</datalist>
		              	</label>
	            	</div>
	            	<div class="flex">
	              		<label class="control-label user-label col-md-4 no-padding"></label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_city" placeholder="Tỉnh / Thành Phố" name="city" class="col-md-12 no-padding font-size-12">
							<datalist id="l_city">
								<?php 
		              			if(isset($city)){
		              			foreach ($city as $rows) { ?>
		              				<option id-city="<?php echo $rows->id_city?>" value="<?php echo $rows->name?>"></option>
		              			<?php }} ?>
							</datalist>
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding"></label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_distr" placeholder="Quận / Huyện" name="district" class="col-md-12 no-padding font-size-12">
							<datalist id="l_distr">
							</datalist>
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding"></label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_ward" placeholder="Phường / Xã" name="ward" class="col-md-12 no-padding font-size-12">
							<datalist id="l_ward">
							</datalist>
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding"></label>
	            		<label class="control-label col-md-8 no-padding-right">
	              			<input name="street" class="col-md-12 no-padding font-size-12" placeholder="Đường">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding"></label>
	            		<label class="control-label col-md-8 no-padding-right">
	              			<input name="address" class="col-md-12 no-padding font-size-12" placeholder="Số nhà">
		              	</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 div-ghichu">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Tags</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="tag" id="tag" class="col-md-12 no-padding font-size-12 available" value="" placeholder="Tags">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ghi chú</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="comments" id="comments" class="col-md-12 no-padding font-size-12 available" value="" placeholder="Nhập ghi chú">
		              	</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 div-bonus">
	            <div class="tile-body padding-right-10">
	            	
	            	<?php foreach ($list_ext as $value) {
	            	if($value['formid'] == 'user' && $value['status'] == '1' ){
	             ?>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">
	            			<?php echo $value['fieldname'] ?>
	            		</label>
	              			<?php if($value['fieldtype'] == 'T') {?>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input name="ext[<?php echo $value['fieldcode'] ?>]" id="<?php echo $value['fieldcode'] ?>" class="col-md-12 no-padding font-size-12 available" value="" placeholder="<?php echo $value['fieldname'] ?>">
		              	</label>
	              		<?php }else if($value['fieldtype'] == 'D'){?>
	              			<select name="ext[<?php echo $value['fieldcode'] ?>]" class="control-label col-md-8 no-border no-padding margin-left-10" id="<?php echo $value['fieldcode'] ?>">
	              			<?php foreach ($list_codic as $material) {
	              				if($material['category'] == $value['datasource'] && $material['status'] =='W'){
	              				?>
	              				<option value="<?php echo $material['code'] ?>"><?php echo $material['name'] ?></option>
	              			<?php }}?> 
	              			</select>
	              		<?php } ?>
	            	</div>
	            <?php }} ?>
	            </div>
          	</div>

          	<div class="fc-corner-right">
          		<div class="fc-button-group" style="float:right">
					<button type="submit" id="btn-save" class="btn btn-primary float-right margin-bot-5">
								<i class="fa fa-share"></i> Lưu thông tin</button>
				</div>
          	</div>
          	<div class="modal fade" id="updateIdcard" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			  <div class="modal-dialog" style="margin-top: 5%; width: 31%" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h4 class="modal-title" id="myModalLabel">CMND/ID</h4>
			        <button type="button" onclick="cancelAddress()" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			      </div>
			      <div class="modal-body">
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Loại hình: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input list="l_type" placeholder="Loại hình" id="type" name="type" class="col-md-12 no-padding font-size-12" value="">
							<datalist id="l_type">
								<option data-value="cmnd">CMND</option>
								<option data-value="passport">Passport</option>
							</datalist>
	              		</label>
					  </div>
			        <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Số: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input type="text"  placeholder="Số" name="idcard" id="idcard" class="col-md-12 no-padding font-size-12" value="" />
	              		</label>
					  </div>
					  <div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Ngày cấp: </label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input placeholder="Ngày cấp" name="issueddate" class="col-md-12 no-padding font-size-12" id="issueddate" value="">
	              		</label>
					  </div>
					  
			      	<div class="form-group">
					    <label class="control-label user-label col-md-3 no-padding">Nơi cấp: </label>
					    <label class="control-label col-md-8 no-padding-right">
					    <input list="l_city" placeholder="Nơi cấp" name="issuedplace" class="col-md-12 no-padding font-size-12" id="issuedplace" value="">
							<datalist id="l_city">
							</datalist>
						</label>
					</div>
			      </div>

			      <div class="modal-footer" style="background: #f5f5f5">
			        <button type="button" class="btn btn-gray-white float-right" onclick="cancelAddress()" data-dismiss="modal">Huỷ</button>
			        <button type="button" class="btn btn-primary float-right" onclick="valueAddress()"><i class=""></i>Lưu</button>
			      </div>
			    </div>
			  </div>
			</div>
     </form>
<file_sep><script src="<?php echo base_url('callevent/node_modules/socket.io-client/dist/socket.io.js');?>"></script>
<script>
    $(document).ready(function(){

    	var socket = io.connect( 'http://'+window.location.hostname+':3000' ),clientid;

    	socket.on('connect', function () {

        	clientid = socket.id;

	    	socket.emit('new_client', { 
		        name: getRandomName(),
		        phone: getRandomNumber(),
		        id: clientid
	        });
    	});

        $.post("http://"+window.location.hostname+":3000/call",{name: getRandomName(),phone: getRandomNumber()}, function(data){
            if(data==='yes'){
                alert("login success");
            }
        });

        socket.on('prv_event',function(data){
            console.log(data);
            $('#dropdown-btn').trigger('click');
        });

        function getRandomName() {
            const arr = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"];
            return arr[Math.floor(Math.random() * arr.length)];
        }

        function getRandomNumber() {
            const arr = ["2455","7895","1230","4587","7849","2368","7842","8953","7412","5687"];
            return arr[Math.floor(Math.random() * arr.length)];
        }
  	});
</script><file_sep><?php
error_reporting(0);
ini_set('display_errors', 0);
defined('BASEPATH') OR exit('No direct script access allowed');

class Ticket extends CI_Controller {

    private $_init = [];

    

	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url','json_output'));
        $this->load->model(array('M_api','M_user'));
        $var = $this->session->userdata;
        $groupid = $var['groupid'];
        
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $start = $time;
        $this->_init['start'] = $start;

        //Kiểm tra quyền với chức năng user
        $var = $this->session->userdata;
        $groupid = $var['groupid'];
        $group = $this->M_api->getlistgroup_array($groupid);
        $this->_init['isViewTicket'] = substr($group['ticketrule'], 0,1);
        $this->_init['isInertTicket'] = substr($group['ticketrule'], 1,1);
        $this->_init['isUpdateTicket'] = substr($group['ticketrule'], 2,1);
    }

	public function index()
	{
		$data1['error'] = 0;
		$_data = [];    
        $var = $this->session->userdata;
		$custid = $var['custid'];

        if($this->_init['isViewTicket']==0){
            $_data['mainview'] = $this->load->view('404',null , TRUE);
            $this->load->view('dashboard',$_data);
            return;
        }

        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketbycustid/'.$custid);
        
        $data['custid'] = $custid;
        $data['result'] = json_decode($json,TRUE);
        $phieuchuaxuly = 0;
        $phieudahoanthanh = 0;
        $phieulienquan = 0;
        $toanbophieu = 0;
        if(count($data['result']['data'])>0 && $data['result']['code']==1)
        {
            //&&  $value['hidden'] == '0'
            foreach ($data['result']['data'] as $value) {
                if($value['status'] ==0 && $value['agentcurrent']==$custid  && $value['status'] != 9)
                {
                    $phieuchuaxuly++;
                }
                if($value['status'] == 4 && $value['agentcurrent']==$custid && $value['status'] != 9)
                {
                    $phieudahoanthanh++;
                }
                if(($value['agentcreated']==$custid || strpos($value['ticketusers'], $custid) !== false)  && $value['status'] != 9)
                {
                    $phieulienquan++;
                }
                if($value['agentcurrent'] == $custid && $value['status'] != 9)
                {
                    $toanbophieu++;
                }
            }
        }
        $data['phieuchuaxuly'] = $phieuchuaxuly;
        $data['phieudahoanthanh'] = $phieudahoanthanh;
        $data['phieulienquan'] = $phieulienquan;
        $data['toanbophieu'] = $toanbophieu;
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/countticket/'.$this->session->userdata('groupid').'/1');
        $data['counter'] = json_decode($json,true)['data'];

        $_data['script'] = $this->load->view('script/script_ticket', NULL, TRUE);
		$_data['mainview'] = $this->load->view('ticket/ticket', $data , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function detail(){
        if($this->_init['isViewTicket']==0){
            $_data['mainview'] = $this->load->view('404',null , TRUE);
            $this->load->view('dashboard',$_data);
            return;
        }
        $var = $this->session->userdata;

        $custid = $var['custid'];
        $roleid = $var['roleid'];
        $groupid = $var['groupid'];

		$ticketid = $this->uri->segment(3);

        $json_ticket = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectByTicketid/'.$ticketid.'');
        $data['ticket'] = $ticket_detail =  json_decode($json_ticket,TRUE);
        

        $ticket_detail = $ticket_detail['data'][0];
        $ticket_users = $ticket_detail['ticketusers'];
        $agentcurrent = $ticket_detail['agentcurrent'];

        //Xử lý việc nhận phiếu
        $data['update'] = false;
        if($custid == $agentcurrent){
            $data['update'] = true;
        }

        $extinfo = json_decode($ticket_detail['extension'],true);

        $data['extinfo'] = $extinfo;
        $data['ticketdetail'] = $ticket_detail;
        $list_user_support_ticket = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/getuserbylistid?listid='.$ticket_users);
        $list_user_support_ticket = json_decode($list_user_support_ticket,true);

        $data['userssuppot'] = $list_user_support_ticket['data'];
        
        // get the stage of ticket
        $l_dtsrc = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select');
        $data['l_dtsrc'] = json_decode($l_dtsrc,true)['data'];
        //extend data
        $l_ext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/ticket');
        $data['l_ext'] = json_decode($l_ext,true)['data'];

        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getcustomerbycustid/'.$data['ticket']['data'][0]['custid']);
        $right['customer'] =  json_decode($json,TRUE)['data'];
        $script = [];
        $script['param']['idcard'] = $right['customer'][0]['idcard'];
        $script['param']['opid'] = $right['customer'][0]['opid'];

		$_body            = [];
		$_body['left']    = $this->load->view('ticket/left/t_info', $data, TRUE); 
		$_body['right']   = $this->load->view('ticket/right/t_history', $right, TRUE);
		$_body['center']  = $this->load->view('ticket/center/t_body', $data, TRUE);

        $script['update'] = $data['update'];
		$_data                = [];    
        $_data['script']      = $this->load->view('script/script_update_ticket', $script, TRUE);
        $_data['script2']     = $this->load->view('script/knowledge', NULL, TRUE);   
		$_data['mainview']    = $this->load->view('ticket/ticket_detail', $_body , TRUE);
		$this->load->view('dashboard',$_data);
	}

    public function view_ticket_log($ticketid){
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectTicketLog/'.$ticketid.'');
        $data['listticketlog'] =  json_decode($json,TRUE)['data'];
        $_data['mainview'] = $this->load->view('ticket/ticketlog/log', $data , TRUE);
        $this->load->view('dashboard',$_data);
    }

    public function view_ticket_task($ticketid){

        $data = [];

        //list agent
        $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/getcustomerbyroleid/2?pagesize=700');
        $data['l_age'] = json_decode($list_user,true)['data'];

        //group agent
        $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group');
        $data['l_agentgroup'] = json_decode($_jsongroup,true)['data'];

        $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tasktype');
        $data['l_type'] = json_decode($l_type,true)['data'];

        $l_detail = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/taskdetail');
        $data['l_detail'] = json_decode($l_detail,true)['data'];

        $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/gettask?ticketid='.$ticketid);
        $data['_task'] = json_decode($res,true)['data'];

        $_data['script'] = $this->load->view('ticket/task/script', NULL , TRUE);
        $_data['mainview'] = $this->load->view('ticket/task/task', $data , TRUE);
        $this->load->view('dashboard',$_data);
    }

    public function recent_ticket($custid='',$agentcurrent='',$idcard=''){
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectTicketLimited/'.$custid.'/'.$agentcurrent);
        $res = json_decode($json,true)['data'];
        $out = [];
        $out['data'] = [];
        for ($i=0; $i < count($res); $i++) { 
            foreach ($res[$i] as $key => $value) {
                if ($key=='ticketid') {
                    $href = base_url().'ticket/detail/'.$value.'/'.$custid.'/'.$idcard;
                    $onclick = "addTab('".$href."','#".$value."')";
                    $out['data'][$i][] = "<a onclick=".$onclick." href='#'>#".$value. "</a>";
                }elseif ($key=='title') {
                    $out['data'][$i][] = $this->limit_text($value,8);
                }
            };
        }
        json_output(200,$out);
    }

    public function recent_contract($idcard='',$opid=''){
        $macanho = '';
        $maduan = '';
        $out = [];
        $out['data'] = [];
        if($idcard !='')
        {
        $data1 = array(
            'reportcode'=>'crmContract01',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'idcard'=> $idcard
            )
        );
        $result1 = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data1);
        $_json1 = json_decode($result1,true);
        $_json3 = json_decode($_json1,true);
        $res = $_json3["result"]["data"];
        for ($i=0; $i < count($res); $i++) { 
            foreach ($res[$i] as $key => $value) {
                if ($key=='contractid') {
                    $href = base_url().'user/contract/'.$value.'?opid='.$opid;
                    $onclick = "addTab('".$href."','".$value."')";
                    $out['data'][$i][] = "<a onclick=".$onclick." href='#'>#".$value. "</a>";
                    $maduan = $value;
                }elseif ($key=='status' ||$key=='property') {
                    $out['data'][$i][] = $value;
                    if($key=='property')
                    {
                        $onclick = "fillExtTicket('".$maduan."','".$value."')";
                        $out['data'][$i][] = "<a onclick=".$onclick." href='#' data-toggle='tooltip' data-placement='left' title='Chọn vào phiếu'><i class='fas fa-cloud-upload-alt'></i></a>";
                    }
                }

            };
        }
        }
        json_output(200,$out);
    }

    public function getrecentticket()
    {
        $idcard = $this->input->post('idcard');
             $data1 = array(
                'reportcode'=>'crmContract01',
                'limit'=>3,
                'start'=>0,
                'queryFilters'=>array(
                    'idcard'=> $idcard
                )
            );

            $result1 = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data1);
            // var_dump($result);
            $_json1 = json_decode($result1,true);
            $_json3 = json_decode($_json1,true);
        $knowledge['contract'] = $_json3["result"]["data"];
        echo json_encode($knowledge);
    }

    public function test_detail(){

        $_body = [];
        $_body['left'] = $this->load->view('ticket/left/test_left', NULL, TRUE); 
        $_body['right'] = $this->load->view('ticket/right/test_right', NULL, TRUE);
        $_body['center'] = $this->load->view('ticket/center/test_center', NULL, TRUE);

        $_data = [];    
        // $_data['script'] = $this->load->view('script/script_update_ticket', null, TRUE);
        // $_data['script2'] = $this->load->view('script/knowledge', NULL, TRUE);   
        $_data['mainview'] = $this->load->view('ticket/ticket_detail', $_body , TRUE);
        $this->load->view('dashboard',$_data);
    }

    public function test_left_detail(){

        // get the stage of ticket
        $data['l_dtsrc'] = $this->_init['l_dtsrc'];
        // get the stage of ticket
        $data['l_stage'] = $this->_init['l_stage'];
        // get the type ticket
        $data['l_type'] = $this->_init['l_type'];
        //extend data
        $data['l_ext'] = $this->_init['l_ext'];

        $_data = [];
        $_data['mainview'] = $this->load->view('ticket/left/t_insert', $data , TRUE);
        
        $this->load->view('dashboard',$_data);
    }

	public function contract(){
		$_body = [];
		$_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE);
		$_body['left'] = $this->load->view('user/left/ud_contract', NULL, TRUE); 
		$_body['right'] = $this->load->view('user/right/ud_history', NULL, TRUE);
		$_body['center'] = $this->load->view('user/center/ud_contract', NULL, TRUE);

		$_data = [];    
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE);
		$this->load->view('master',$_data);
	}
    //insert ticket
    public function viewInsert()
    {
        //get list cus
        $data = [];

        $knowledge['view'] = 'insert';

        // get the stage of ticket
        $l_dtsrc = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select');
        $data['l_dtsrc'] = json_decode($l_dtsrc,true)['data'];
        //extend data
        $l_ext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/ticket');
        $data['l_ext'] = json_decode($l_ext,true)['data'];

        $_body = [];
        $_body['left'] = $this->load->view('ticket/left/t_insert', $data, TRUE); 
        $_body['right'] = $this->load->view('ticket/right/t_history', $knowledge, TRUE);
        $_body['center'] = $this->load->view('ticket/center/t_insert', null, TRUE);
        
        $_data = [];   
        $_data['script'] = $this->load->view('script/script_insert_ticket', null, TRUE);  
        $_data['script2'] = $this->load->view('script/knowledge', null, TRUE); 
        $_data['mainview'] = $this->load->view('ticket/ticket_insert', $_body , TRUE);
        $this->load->view('dashboard',$_data); 
        // $time = microtime();
        // $time = explode(' ', $time);
        // $time = $time[1] + $time[0];
        // $finish = $time;
        // $total_time = round(($finish - $this->_init['start']), 4);
        // echo 'Page generated in '.$total_time.' seconds.';
    }

    public function aj_insert_ticket(){

        $post           = $this->input->post();  
        $var            = $this->session->userdata;
        $data_ext       = isset($post['ext'])?json_encode($post['ext']):null;
        $ticket         = [];
        $ticket['log_groupid'] = $var['groupid'];
        $ticket['agentcurrent']     = isset($post['agentcurrent'])?$post['agentcurrent']:'';
        $ticket['agentgroup']       = isset($post['agentgroup'])?$post['agentgroup']:'';
        $ticket['agentcreated']     = $var['custid'];
        $ticket['custid']           = isset($post['customer'])?$post['customer']:'';
        $ticket['contractid']       = isset($post['contractid'])?$post['contractid']:'';
        $ticket['ticketchannel']    = isset($post['ticketchannel'])?$post['ticketchannel']:'';
        $ticket['priority']         = isset($post['priority'])?$post['priority']:'';
        $ticket['extension']        = $data_ext!=null?$data_ext:null;
        $ticket['status']           = 0;
        $ticket['sla']              = isset($post['sla'])?date('Y-m-d H:i:s',strtotime($post['sla'])):'';
        $ticket['status']           = isset($post['ticketstatus'])?$post['ticketstatus']:'';
        $ticket['duedate']          = isset($post['duedate'])?date('Y-m-d H:i:s',strtotime($post['duedate'])):'';
        $ticket['finishdate']       = isset($post['finishdate'])?date('Y-m-d H:i:s',strtotime($post['finishdate'])):'';
        $ticket['requestdate']      = isset($post['requestdate'])?date('Y-m-d H:i:s',strtotime($post['requestdate'])):'';
        $ticket['firstreply']       = isset($post['firstreply'])?date('Y-m-d H:i:s',strtotime($post['firstreply'])):'';
        $ticket['levelticket']      = isset($post['levelticket'])?$post['levelticket']:'';
        $ticket['categoryid']       = isset($post['categoryid'])?$post['categoryid']:'';
        $ticket['groupid']          = isset($post['groupid'])?$post['groupid']:'';
        $ticket['tickettype']       = isset($post['tickettype'])?$post['tickettype']:'';
        $ticket['ticketusers']      = $ticket['agentcurrent'].','.($ticket['agentcurrent']!=$var['custid']?$var['custid']:'');
        $ticket['title']            = isset($post['title'])?$post['title']:'';
        $ticket['transref']         = isset($post['transref'])?$post['transref']:'';

        // var_dump($ticket);
        $postdata   = http_build_query($ticket);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert',false,$context);
        echo $result;

        $_res = json_decode($result,true);
        if (isset($_res['code']) && $_res['code'] == 1 && isset($post['cmt']) && $post['cmt'] !='') {
            $log['action']           = "";
            $log['useraction']       = $var['custid'];
            $log['cmt']              = isset($post['cmt'])?$post['cmt']:'';
            $log['ticketid']         = $_res['data'];
            $_result                 = $this->aj_insert_ticket_log($log);
            // echo $_result;
        }
    }

    public function aj_update_ticket()
    {
        $post           = $this->input->post();        //var_dump($post);
        $var            = $this->session->userdata;
        $data_ext       = isset($post['ext'])?json_encode($post['ext']):null;
        $ticket         = [];

        $tid = $ticket['ticketid']  = isset($post['ticketid'])?$post['ticketid']:'-1';

        // $ticket['log_custid']       = $var['custid'];
        // $ticket['log_roleid']       = $var['roleid'];
        $ticket['log_groupid']      = $var['groupid'];
        $ticket['agentgroup']       = isset($post['agentgroup'])?$post['agentgroup']:'-1';
        $ticket['agentcurrent']     = isset($post['agentcurrent'])?$post['agentcurrent']:'-1';
        $ticket['title']            = isset($post['title'])?$post['title']:'-1';
        $ticket['ticketchannel']    = isset($post['ticketchannel'])?$post['ticketchannel']:'-1';
        $ticket['priority']         = isset($post['priority'])?$post['priority']:'-1';
        $ticket['extension']        = $data_ext!=null?$data_ext:'-1';
        $ticket['sla']              = isset($post['sla'])?date('Y-m-d H:i:s',strtotime($post['sla'])):'-1';
        $ticket['status']           = isset($post['ticketstatus'])?$post['ticketstatus']:'-1';
        $ticket['duedate']          = isset($post['duedate'])?date('Y-m-d H:i:s',strtotime($post['duedate'])):'-1';
        $ticket['finishdate']       = isset($post['finishdate'])?date('Y-m-d H:i:s',strtotime($post['finishdate'])):'-1';
        $ticket['requestdate']      = isset($post['requestdate'])?date('Y-m-d H:i:s',strtotime($post['requestdate'])):'-1';
        $ticket['firstreply']       = isset($post['firstreply'])?date('Y-m-d H:i:s',strtotime($post['firstreply'])):'-1';
        $ticket['levelticket']      = isset($post['levelticket'])?$post['levelticket']:'-1';
        $ticket['tickettype']       = isset($post['tickettype'])?$post['tickettype']:'-1';
        $ticket['categoryid']       = isset($post['categoryid'])?$post['categoryid']:'-1';
        $ticket['groupid']          = isset($post['groupid'])?$post['groupid']:'-1';
        $ticket['ticketusers']      = isset($post['ticketusers'])?$this->check_exist($post['ticketusers'],$ticket['agentcurrent']):'-1';
        $ticket['title']            = isset($post['title'])?$post['title']:'-1';
        $ticket['transref']         = isset($post['transref'])?$post['transref']:'-1';

        foreach ($ticket as $key => $value) {
            if ($value == '-1') {
                unset($ticket[$key]);
            }
        }
        // var_dump($ticket);
        $postdata   = http_build_query($ticket);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/update/'.$tid,false,$context);
        echo $result;

        $_res = json_decode($result,true);
        if (isset($_res['code']) && $_res['code'] == 1 && ((isset($post['cmt']) && $post['cmt'] !='')||(isset($post['changelog'])&&$post['changelog']!=''))) {
            if ($post['cmt']=='') {
                $log['action']           = "Cập nhật phiếu";
            }else{
                $log['action']           = "";
            }
            $log['useraction']       = $var['custid'];
            $log['cmt']              = isset($post['cmt'])?$post['cmt']:'';
            $log['changelog']        = isset($post['changelog'])?$post['changelog']:'';
            $log['ticketid']         = $tid;
            $_result                 = $this->aj_insert_ticket_log($log);
            // echo $_result;
        }
    }

    private function check_exist($string,$find){
        $result = strpos($string,$find);
        if(!$result){
            return $string.','.$find;
        }else{
            return $string;
        }
    }

    public function aj_insert_ticket_log($log){

        $postdata = http_build_query($log);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert_ticketlog/',false,$context);
        return $result;
    }

    public function updateTicketLog()
    {
        $ticketid = $this->input->post('ticketid');
        $cmt = $this->input->post('cmt');
        $action  = "";
        $postdata = http_build_query([
            'action' => $action,
            'useraction'=> $this->session->userdata('custid'),
            'cmt'=>$cmt,
            'ticketid' => $ticketid,
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert_ticketlog/'.'',false,$context);
        echo $result;
    }

    public function get_to_my_ticket($tckid){
        $var = $this->session->userdata;
        $log_groupid = $var['groupid'];
        $ticket         = [];
        $ticket['log_groupid'] = $log_groupid;
        $ticket['agentcurrent']     = $this->session->userdata['custid'];
        $ticket['agentgroup']       = $this->session->userdata['groupid'];
        $ticket['ticketid']         = $tckid;
        $ticket['status']           = 0;

        $postdata   = http_build_query($ticket);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/update/'.$tckid,false,$context);
        echo $result;

        $_res = json_decode($result,true);
        if (isset($_res['code']) && $_res['code'] == 1) {
            $log['action']           = "Tiếp nhập phiếu";
            $log['useraction']       = $this->session->userdata['custid'];
            $log['cmt']              = '';
            $log['changelog']        = 'Người phụ trách: '.$this->session->userdata['custname'];
            $log['ticketid']         = $tckid;
            $_result                 = $this->aj_insert_ticket_log($log);
            // echo $_result;
        }
    }

    public function deleteTicket()
    {
        $ticketid = $this->input->post('ticketid');
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Api/ticket/delete/'.$ticketid.'');
        header('location:../ticket');
        // var_dump($ticketid);
    }    

    public function getIdCard()
    {
        $var = $this->session->userdata;
        $custid = $var['custid'];
        $roleid = $var['roleid'];
        $telephone = $this->input->post('telephone');
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/search?action=search_customer&telephone='.$telephone.'&roleid='.$roleid);
        echo $result;
    }
    

    public function getIdCardTicket()
    {
        $ticketid = $this->input->post('ticketid');
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectByTicketid/'.$ticketid);
        echo $result;
    }

    private function limit_text($text, $limit) {
      if (str_word_count($text, 0) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }

}
<file_sep><div class="col-md-100 no-padding padding-left-5">
	    	<div class="tile height-1024">
	            <div class="table-responsive">
	              	<table class="table" id="table-1-searchticket">
	              		<thead class="no-border-top">
	              			<tr>
	              				<th width="100">ID</th>
	              				<th width="250">Tên phiếu</th>
	              				<th width="130px">Người yêu cầu</th>
	              				<th width="130px">Người phụ trách</th>
	              				<th width="75px">Nguồn phiếu</th>
	              				<th width="70px">Độ ưu tiên</th>
	              				<th width="69px">Tình trạng</th>
	              			</tr>
	              		</thead>
		                <tbody>
		                	<?php 
		                	if(count($result['data']) >0&& $result['code']==1)
		                	{
		                	foreach ($result['data'] as $rows) {
		                		
		                		?>
		                	<tr class="border-bot-1">
			                    <td>
			                    	<a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.$rows['custid'].'/'.$rows['idcard'] ?>','#<?php echo $rows['ticketid'] ?>')" href="#" title="">
			                    	<span class="id-label span-warning">P</span>  #<?php echo $rows['ticketid'] ?>
			                    	</a>
			                    </td>
			                    <td>
			                    	<?php echo $rows['title'] ?>
			                    </td>
			                    <td><?php if(isset($rows['agentcreatedname'])){ echo $rows['agentcreatedname'];} ?></td>
			                    <td><?php if(isset($rows['name'])){ echo $rows['name'];} ?></td>
			                    <td><?php 
			                    	if ($rows['ticketchannel']==2) {echo "Điện thoại";}
			                    	elseif ($rows['ticketchannel']==1) {echo "Trực tiếp";}
			                    	elseif ($rows['ticketchannel']==3) {echo "Email";}
			                    	elseif ($rows['ticketchannel']==4) {echo "Chat";}
			                    	else {echo "Không xác định";}
			                    ?></td>
			                    <td><?php 
			                    	if ($rows['priority']==1) {echo "Thường";}
			                    	elseif ($rows['priority']==2) {echo "Cao";}
			                    	elseif ($rows['priority']==3) {echo "Khẩn cấp";}
			                    	else {echo "Không xác định";}
			                    ?></td>
			                    <td><?php 
			                    	if ($rows['status']==9) {echo "Hủy";}
			                    	elseif ($rows['status']==0) {echo "Đang xử lý";}
			                    	elseif ($rows['status']==4) {echo "Hoàn thành";}
			                    	else {echo "Không xác định";}
			                    ?></td>
		                  	</tr>	
		                	<?php }} ?>				  
		                </tbody>
	              	</table>
	            </div>  
	        </div>
	    </div><file_sep><script type="text/javascript">
		$(document).ready(function(){

			$('#form-user').on('submit',function(){
				$('#form-user').validate({
			        rules: {
			            name: {
			                required: true
			            },
			            email: {
			                required: true
			            }
			        },
			        invalidHandler: function(event, validator) {
			            var errors = validator.numberOfInvalids(); // <- NUMBER OF INVALIDS
			            console.log(errors);
			        },
			        submitHandler: function(f) {
				      	// f.submit();
				    },
				    showErrors: function(errorMap, errorList) {
			            var errors = this.numberOfInvalids(); // <- NUMBER OF INVALIDS

			            console.log(errorMap);
			            $.each(errorMap, function(key, value) {
			                console.log(key);
							var parent = $('[name="' + key + '"]').parent();
							console.log(parent);
			            });

			            this.defaultShowErrors(); // <- ENABLE default MESSAGES
			        }
			    });
			    return false;
			});
		});		
</script><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 padding-left-15">
          	<?php echo isset($left)?$left:'' ?>
        </div>

        <div class="col-md-7 padding-left-1">
          	<!-- <?php echo isset($center)?$center:'' ?> -->
            <iframe class="iframeQueue" id="iframeQueue" style="min-height: 1024px;width: 100%; border: none;"  src="<?php echo base_url() ?>queue/rightFilter?queue=21114"></iframe>
        </div>
        <div class="col-md-2 col-md-18 padding-left-5">
        	
        </div>
    </div>
</main>
<file_sep><script type="text/javascript">
	$(document).ready(function(){
		$('#modalDelete').on('shown.bs.modal', function (e) {
  			var code = $(e.relatedTarget).data('code');
			$(e.currentTarget).find('input[name="codedelete"]').val(code);
			var category = $(e.relatedTarget).data('category');
			$(e.currentTarget).find('input[name="categorydelete"]').val(category);

		});
		$('#modalUpdate').on('shown.bs.modal', function (e) {
  			var code = $(e.relatedTarget).data('code');
			$(e.currentTarget).find('input[name="code"]').val(code);
			var category = $(e.relatedTarget).data('category');
			$(e.currentTarget).find('input[name="category"]').val(category);
			var name = $(e.relatedTarget).data('name');
			$(e.currentTarget).find('input[name="name"]').val(name);
      var status = $(e.relatedTarget).data('status');
      $(e.currentTarget).find('select[name="status"]').val(status);
      var comments = $(e.relatedTarget).data('comments');
      $(e.currentTarget).find('textarea[name="comments"]').val(comments);
      var ref1 = $(e.relatedTarget).data('ref1');
      $(e.currentTarget).find('select[name="ref1_update"]').val(ref1);
      if(ref1 !='')
      {
          var obj = document.getElementById("ref1_update");
          var ref2 = $(e.relatedTarget).data('ref2');
          if(ref2 !=null)
          {
          getGroupRef2(obj,'ref2_update',ref2);
          }
      }
		});
	})
	function deleteButton()
	{
		var category = $('#categorydelete').val();
		var code = $('#codedelete').val();
		var action = 'delete';
		$.ajax({
             url: '<?php echo base_url().'groupuser/updateDatasource' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {category:category,code:code,action:action},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}

	function updateButton()
	{
		var category = $('#category').val();
		var code = $('.code').val();
		var name = $('.nameField').val();
    var status = $('#status').val();
    var comments = $('#comments').val();
    var ref1 = $('#ref1_update').val();
    var ref2 = $('#ref2_update').val();
		var action = 'update';
    if(comments == '')
    {
      comments = ' ';
    }
		$.ajax({
             url: '<?php echo base_url().'groupuser/updateDatasource' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {category:category,code:code,name:name,action:action,status:status,comments:comments,ref1:ref1,ref2:ref2},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}
	function insertSelectBox()
	{
		var code = $('#code').val();
		var name = $('#name').val();
		var category = $('#category').val();
    var comments = $('#comments_insert').val();
    var ref1 = $('#ref1_insert').val();
    var ref2 = $('#ref2_insert').val();

		$.ajax({
             url: '<?php echo base_url().'groupuser/insertSelectBox' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {code:code,name:name,category:category,comments:comments,ref1:ref1,ref2:ref2},
           })
           .done(function(data) {
               if(data.code==1){
               	window.location.reload();
               }else if(data.data.indexOf("PRIMARY KEY constraint 'PK_crcodedictionary") !== -1){
                 alert("Trùng mã. Vui lòng nhập lại mã");
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}
  function changeiFrameIssueGroup()
  {
      var ref1 = $('#codictionary_issuegroup').val();
      document.getElementById('iframeIssueGroup').src = "<?php echo base_url() ?>issuegroup/rightFilter?ref1="+ref1;
  }

  function changeiFrameIssueDetail()
  {
      var ref1 = $('#codictionary_issuegroup').val();
      var ref2 = $('#codictionary_issuegrouptype').val();
      document.getElementById('iframeIssueDetail').src = "<?php echo base_url() ?>issuedetail/rightFilter?ref1="+ref1+"&ref2="+ref2;
  }

  function changeiFrameDetailWork()
  {
      var ref1 = $('#codictionary_typework').val();
      document.getElementById('iframeDetailWork').src = "<?php echo base_url() ?>detailwork/rightFilter?ref1="+ref1;
  }

  function getGroup(obj,id)
  {
    var value = obj.value;
    $.ajax({
      url: '<?php echo base_url() ?>issuedetail/getIssueGroupByType',
      type: 'POST',
      dataType: 'JSON'
    })
    .done(function(data){
      var data_html = '';
        for (var i = 0; i < data.data.length; i++) {
          if(data.data[i].ref1 == value)
          {
              data_html+='<option value="'+data.data[i].code+'">'+data.data[i].name+'</option>';
          }
        }
        $('#'+id+'').html('<option value="-1">Tất cả</option>\
          '+data_html+'');
    })
    .fail(function(){

    });
  }

  function getGroupRef2(obj,id,ref2)
  {
    var value = obj.value;
    $.ajax({
      url: '<?php echo base_url() ?>issuedetail/getIssueGroupByType',
      type: 'POST',
      dataType: 'JSON'
    })
    .done(function(data){
      var data_html = '';
        for (var i = 0; i < data.data.length; i++) {
          if(data.data[i].ref1 == value)
          {
              data_html+='<option value="'+data.data[i].code+'">'+data.data[i].name+'</option>';
          }
        }
        $('#'+id+'').html(data_html);
        $('#'+id+'').val(ref2);
    })
    .fail(function(){

    });
  }
</script><file_sep><script type="text/javascript">
$(document).ready( function () {

  $( "#idcard_modal" ).click(function() {
      $('#updateIdcard').modal('toggle');
      $('#updateIdcard').on('shown.bs.modal', function (e) {
           $('#issueddate').datetimepicker({timepicker:false,
          format:'d/m/Y'});
        })
  });

  $('#table-1-create-user').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
                }
              },
            "columns": [
              { "width": "20%" },
              { "width": "20%" },
              { "width": "20%" },
              { "width": "20%" },
              { "width": "20%" }
             ],
            "info":     false,
            "searching": false,
            "scrollY":        "100%",
            "iDisplayLength": 25,
            "scrollX":        true,
            "bLengthChange": false,
            "scrollCollapse": true
    }).columns.adjust().draw();
  $('form#insertUserVal').on('submit',function(){
      
    var formData = new FormData($(this)[0]);

    for (var [key, value] of formData.entries()) { 
          // console.log(key, value);
    }

    var name = formData.get('custname');

    $(this).find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');

    $.ajax({
      type: "POST",
      url: "<?php echo base_url().'user/aj_validate';?>",
      data:  formData,
      dataType:'json',
      contentType: false,
      cache: false,
      processData:false,
      beforeSend: function() {
      },
      success: function(data) {
      $('#btn-save').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
        if(data.code==0){
          // swal("Cảnh báo !", data.message, "warning");
          // parent.alertLog("Cảnh báo !", data.message, "warning");
          var string = "B\u1ea1n thu\u1ed9c nh\u00f3m";
          if(data.data == null)
          {
             swal("Cảnh báo !", data.message, "warning");
             return;
          }
          swal({
            title: "Cảnh báo !",
            text: data.message,
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Tiếp tục !',
            cancelButtonText: 'Huỷ',
            buttons: true,
            dangerMode: true,
          },function(willDelete){
              if (willDelete) {
                insertUser(formData,name);
              }
          });
        }else{
            insertUser(formData,name);
        }
        
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
    return false;
  });

  $('#fullbirthday').datetimepicker({timepicker:false,format:'d/m/Y'});

  $('input[name=city]').on('keyup',function(){
    var val = $(this).val();
    var opt = $('datalist#l_city').find('option[value="'+val+'"]');
    if (opt.length>0) {
      var idcity = opt.attr('id-city');
      $.ajax({
        url: '<?php echo base_url()?>user/selectCity',
        type: 'POST',
        dataType: 'JSON',
        data: {id_city : idcity},
      })
      .done(function(data) {
        var l_r = '';
        for (var i = 0; i < data.length; i++) {
          l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_district']+'"></option>';
        }
        $('datalist#l_distr').html(l_r);
      })
      .fail(function() {
        console.log("error");
      })
    }
  });

  $('input[name=district').on('keyup',function(){
    var val = $(this).val();
    var opt = $('datalist#l_distr').find('option[value="'+val+'"]');
    if (opt.length>0) {
      var id = opt.attr('id');
      $.ajax({
        url: '<?php echo base_url()?>user/selectDistrict',
        type: 'POST',
        dataType: 'JSON',
        data: {id_district : id},
      })
      .done(function(data) {
        var l_r = '';
        for (var i = 0; i < data.length; i++) {
          l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_ward']+'"></option>';
        }
        $('datalist#l_ward').html(l_r);
      })
      .fail(function() {
        console.log("error");
      })
    }
  });
});
  

    function selectDistrict(obj){
      var $id = obj.value;
      $('.gicungdc1').remove(); 
      $.ajax({
        url: '<?php echo base_url()?>user/selectDistrict',
        type: 'POST',
        dataType: 'JSON',
        data: {id_district : $id},
      })
      .done(function(data) {
                 // console.log(data.loaisp);
         for (var i = 0; i < data.length; i++) {
          $('#dodulieu1').after('<option title="'+data[i]['name']+'" class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>');
         }
            
      })
      .fail(function() {
        console.log("error");
      })
    }

    function selectGroup(obj){
      var $id = obj.value;
      $('.div-add').remove();
      $('.group_item').remove(); 
      $('.div-queue').remove();
      
                if($id != 3)
                 {
                    $('.div-ghichu').hide();
                    $('.div-bonus').hide();
                    $('.div-cmnd').hide();
                    $('.div-address').hide();
                    $('.div-danhxung').hide();
                    $('.div-ngaysinh').hide();
                    document.querySelector('#idcard_modal').required = false;
                    document.querySelector('#email').required = false;
                    if($id == 2){
                     $('.div-phone').after('<div class="div-queue">\
                   <label class="control-label user-label col-md-3 no-padding">Hàng chờ cuộc gọi</label>\
                     <select class="control-label col-md-8 no-border no-padding margin-left-10" id="queue">\
                                                <option value="21114" >Chuyển nhượng hợp đồng</option>\
                                                       <option value="21115" >Thanh toán vay</option>\<option value="21121" >Tiếng Anh</option>\
                                                       <option value="21116" >Khác</option>\
                                                      </select>\
                </div>');
                     }
                     $('.div-group').after('<div class="div-add">\
                         <label class="control-label user-label col-md-3 no-padding">ID:</label>\
                           <label class="control-label col-md-8 no-padding-right">\
                             <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập ID" minlength="5" maxlength="10" id="custid" name="custid">\
                           </label>\
                       </div>\
                       <div class="div-add">\
                         <label class="control-label user-label col-md-3 no-padding">Password:</label>\
                           <label class="control-label col-md-8 no-padding-right">\
                             <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập Password" type="password" id="password" name="password">\
                           </label>\
                       </div>\
                       ');
                 }
                 else{
                    $('.div-ghichu').show();
                    $('.div-bonus').show();
                    $('.div-cmnd').show();
                    $('.div-address').show();
                    $('.div-danhxung').show();
                    $('.div-ngaysinh').show();
                 }
    }

  function valueAddress()
  {
      var idcard = $('#idcard').val();
      $('#idcard_modal').val(idcard);
      $('#updateIdcard').modal('toggle');
  }
  function cancelAddress()
  {
      $('#idcard_modal').val('');
      $('#idcard').val('');
      $('#type').val('');
      $('#issueddate').val('');
      $('#issuedplace').val('');
      $('#updateIdcard').modal('toggle');
  }

  function insertUser(formData,name)
  {
      $.ajax({
                  type: "POST",
                  url: "<?php echo base_url().'user/aj_insert';?>",
                  data:  formData,
                  dataType:'json',
                  contentType: false,
                  cache: false,
                  processData:false,
                  beforeSend: function() {
                  },
                  success: function(data) {
                  $('#btn-save').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
                    if(data.code==0){
                      // swal("Cảnh báo !", data.message, "warning");
                      parent.alertLog("Cảnh báo !", data.message, "warning");
                    }else{
                      // swal("Thành công !", "Thêm người dùng thành công.", "success");
                      parent.alertLog("Thành công !", "Thêm người dùng thành công.", "success");
                      var tab = window.top.$('div.tab-pane.active').attr('id');
                      window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html(name);
                      $.ajax({
                        url: '<?php echo base_url() ?>user/getUserByRecodeId',
                        type: 'POST',
                        dataType: 'JSON',
                        data: {id: data.data}
                      })
                      .done(function(data1){
                          window.location.href = "<?php echo base_url()?>user/detail/?cusid="+data1.data[0].custid+"&idcard="+data1.data[0].idcard+"&roleid="+data1.data[0].roleid;
                      })
                      .fail(function(){

                      });
                    }
                  },
                  error: function(xhr, status, error) {
                    console.log(error);
                  }
                });
  }
</script><file_sep>		<form id="form-ticket">
			<div class="tile p-0 padding-5 margin-bot-5 z-index-100">
	            <div class="tile-body padding-left-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Người yêu cầu (<span style="color: red;">*</span>)</label>
		              	<select data-placeholder="Chọn người yêu cầu..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="customer">
	              			<option value="" ></option>
	              			<?php if (isset($l_cus)) {
                              	foreach ($l_cus as $cus) {
                              		if ($cus['custname']!='') {
                              			$s='';
                              			if ($this->uri->segment(4)!='' && $this->uri->segment(4)==$cus['custid']) {
                              				$s='selected';
                              			}
                              			echo('<option value="'.$cus['custid'].'">'.$cus['custname'].'</option>');
                              		}
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Người tạo(<span style="color: red;">*</span>)</label>
	              		<label class="control-label col-md-7 no-padding-right">
	              			<input type="" readonly="" name="" value="<?php echo $this->session->userdata('custname')?>">
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Nhóm phụ trách(<span style="color: blue;">*</span>)</label>
	              		<select data-placeholder="Chọn nhóm phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="agentgroup">
	              			<option value=""></option>
	              			<?php if (isset($l_agentgroup)) {
	              				foreach ($l_agentgroup as $key => $value) {
	              					echo '<option value="'.$value['groupid'].'">'.$value['groupname'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phụ trách (<span style="color: blue;">*</span>)</label>
		              	<select data-placeholder="Chọn người phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="agentcurrent">
	              			<option value=""></option>
	              			<?php if (isset($l_age)) {
                              	foreach ($l_age as $cus) {
                              		if ($cus['custname']!='') {
                              			$s='';
                              			if ($this->session->userdata('custid')!='' && $this->session->userdata('custid')==$cus['custid']) {
                              				$s='selected';
                              			}
                              			echo('<option value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>');
                              		}
                              	}
                            } ?>
	              		</select>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Nguồn phiếu</label>
	              		<select name="ticketchannel" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control">
	              			<option value="1">Trực tiếp</option>
	              			<option value="2">Điện thoại</option>
	              			<option value="3">Email</option>
	              			<option value="4">Chat</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Mức Ưu tiên</label>
	            		
	            		<select name="priority" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control">
	              			<option value="1">Thường</option>
	              			<option value="2">Cao</option>
	              			<option value="3">Khẩn cấp</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Tình trạng</label>
	            		<select readonly="" name="ticketstatus" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control">
	            			<option value="1">Tạo mới</option>
	            			<option value="0" disabled="">Đang xử lý</option>
	              			<option value="4" disabled="">Hoàn thành</option>
	              			<option value="9" disabled="">Hủy</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Giai đoạn</label>
	              		<select name="levelticket" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control">
		              		<?php if (isset($l_stage) && !empty($l_stage)) {
	              				foreach ($l_stage as $key => $value) {
	              					echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
		              	</select>
	            	</div>
	            </div>
          	</div>
          	
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phân loại</label>
	              		<select name="tickettype" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_1">
	              			<?php if (isset($l_type) && !empty($l_type)) {
	              				foreach ($l_type as $key => $value) {
	              					echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Nhóm vấn đề</label>
	            		<select name="groupid" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_2">
	              			<?php if (isset($l_group) && !empty($l_group)) {
	              				foreach ($l_group as $key => $value) {
	              					echo '<option ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Chi tiết VĐ</label>
	            		<select name="categoryid" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_3">
	              			<?php if (isset($l_cate) && !empty($l_cate)) {
	              				foreach ($l_cate as $key => $value) {
	              					echo '<option ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày yêu cầu</label>
	              		<label class="control-label col-md-7 no-padding-right">
	              			<input name="requestdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii">
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày phản hồi</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input name="firstreply" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii">
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Thời hạn SLA</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input name="sla" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii">
	              		</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày hẹn</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input name="duedate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii">
	              		</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày hoàn thành</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              		   <input name="finishdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii">
	              		</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Mã giao dịch</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              			<input name="transref" class="col-md-12 no-padding font-size-12 crm-control" placeholder="" value="<?php echo($this->uri->segment(3))?>">
	              		</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<?php 

	            		if (isset($l_ext)) {
	            			foreach ($l_ext as $key => $value) {
	            				$f = isset($value['fieldcode'])?$value['fieldcode']:'';
	            				$n = isset($value['fieldname'])?$value['fieldname']:'';
	            				$v = isset($extinfo[$value['fieldcode']])?$extinfo[$value['fieldcode']]:'';
	            				$d = '<div class="flex">
					            		<label class="control-label user-label col-md-4 no-padding">'.$n.'</label>';
					            if (isset($value['fieldtype']) && $value['fieldtype']=='T') {
					            	if($this->uri->segment(3) !=null && $value['fieldcode'] =='magd')
					            	{
					            		$d.='
					            		<label class="control-label col-md-8 no-padding-right">
						              		<input class="col-md-12 no-padding font-size-12 crm-ext" log="'.$n.'" value="'.$this->uri->segment(3).'" name="ext['.$f.']">
						              	</label>
					            	';
					            	}
					            	else{
					            	$d.='
					            		<label class="control-label col-md-8 no-padding-right">
						              		<input class="col-md-12 no-padding font-size-12 crm-ext" log="'.$n.'" value="'.$v.'" name="ext['.$f.']">
						              	</label>
					            	';
					            	}
					            }elseif(isset($value['fieldtype']) && $value['fieldtype']=='D'){
					            	$d.='<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-ext" log="'.$n.'" name="ext['.$f.']">';
					            	if (isset($value['datasource']) && isset($l_dtsrc)) {
					            		foreach ($l_dtsrc as $ky => $vl) {
					            			if ($vl['category'] == $value['datasource']) {
					            				$sel = '';
				              					if ($v==$vl['code']) {
				              						$sel = 'selected';
				              					}
				              					$d.='<option '.$sel.' value="'.$vl['code'].'">'.$vl['name'].'</option>';
					            			}
					            		}
					            	}else{
					            		$d.='<option>(Dữ liệu bị lỗi)</option>';
					            	}
					            	$d.='</select>';
					            }else{
					            	$d.='<label>Đang cập nhật</label>';
					            }
					            $d.='</div>';
	            				echo ($d);
	            			}
	            		}
	            	?>
	            </div>
          	</div><file_sep><?php
error_reporting(0);
ini_set('display_errors', 0);
// defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model('M_api');
        $this->load->model('M_user');
        $this->load->model('M_data_API');
        $this->load->driver('cache');
        $dayCompare = strtotime('2000-01-01T00:00:00');
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $start = $time;
        $this->_init['start'] = $start;

        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  


        $_jsongroup = $this->M_api->getListGroupCache();
        $this->_init['_jsongroup'] = json_decode($_jsongroup,true);
        $_jsoncity = $this->cache->memcached->get('_jsoncity');
        if(!$_jsoncity){
             $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_city',false, stream_context_create($arrContextOptions)))  ;
             $this->cache->memcached->save('_jsoncity',$_jsoncity, 86400);
        }
        $this->_init['_jsoncity'] = $_jsoncity;

        $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/user');
        $this->_init['_jsonlistext'] = json_decode($_jsonlistext,true);
        $_jsonlistcodic = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/');
        $this->_init['_jsonlistcodic'] = json_decode($_jsonlistcodic,true);
        
        //Kiểm tra quyền với chức năng user
        $var = $this->session->userdata;
        $groupid = $var['groupid'];
        $group = $this->M_api->getlistgroup_array($groupid);
        $this->_init['isViewUser'] = substr($group['userrule'], 0,1);
        $this->_init['isInserUser'] = substr($group['userrule'], 1,1);
        $this->_init['isUpdateUser'] = substr($group['userrule'], 2,1);
    }

    public function index()
    {
        $_body = [];
        $_body['left'] = $this->load->view('user/left/ud_dashboard_left',null,TRUE); 
        $_body['right'] = $this->load->view('user/right/ud_dashboard_right', null, TRUE);
        $_body['center'] = $this->load->view('user/center/ud_dashboard_center', null, TRUE);
        $_data = [];    
        $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
        $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); 
        $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE);  
        $_data['mainview'] = $this->load->view('user/user', $_body , TRUE);
        $this->load->view('dashboard',$_data);
    }
    public function testContract()
    {
        $idcard = $this->input->get('idcard');
        $opid = $this->input->get('opid');
        $this->M_data_API->getContractByIdcard($idcard,$opid);
    }
    public function detail(){
        $var = $this->session->userdata;
        $user_seassion = $this->session->userdata;
        $custid_login = $user_seassion['custid'];
        if(isset($_GET['cusid'])){
            $_cusid = $_GET['cusid']; 
        }
        else
        {
            $_cusid = '';
        }
        if($this->_init['isViewUser']==0 && $custid_login!=$_cusid){
            $_data['mainview'] = $this->load->view('404',null , TRUE);
            $this->load->view('dashboard',$_data);
            return;
        }
        $_body = [];
        $customer = [];
        

        if(isset($_GET['phone'])){
            $_phone = $_GET['phone']; 
        }
        else
        {
            $_phone = '';
        }
        if(isset($_GET['roleid'])){
            $_roleid = $_GET['roleid']; 
        }
        else
        {
            $_roleid = '';
        }
        //Get Thong tin dia chi
        $customer['city'] = $this->_init['_jsoncity'];
        //Get thông tin khách hàng dựa vào id hoặc số phone
        
        
        $roleid = $user_seassion['roleid'];
        $groupid = $user_seassion['groupid'];
        if(isset($_GET['action']))
        {
            if($_GET['action'] == 'profile')
                {
                    $roleid = '1'; 
                }
                else
                {
                    $roleid = $var['roleid'];
                }
        }
        else
        {
            $roleid = $var['roleid'];
        }
        //Data Auth, tất cả đều phải sử dụng : custid của agent đang login, roleid, groupdid
        $dataAuth = [];

        $_jsonuser = $this->M_user->getUserByCustId($_cusid,$dataAuth);
        //Kiếm tra User 
        if($_jsonuser['code']==1){
            $_dataContract['user'] = $_jsonuser['data'];
        }else{
            $data["msg"] = "Mã khách hàng không tồn tại";
            $_data['mainview'] = $this->load->view('404',$data , TRUE);
            $this->load->view('dashboard',$_data);
            return;
        }
        //Get thông tin ticket dựa vào cusid
        $_jsonticket = json_decode(file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/select/'.$_cusid.'?agentid='.$custid_login.'&groupid='.$groupid), true);
        $_dataContract['ticket'] = $_jsonticket['data'];
            $_dataContract['trade'] = array();
        //Get thông tin cuộc gọi từ SDT
        
        $roleid = $var['roleid'];
        $role_list = array();
        // if($roleid==1){
            $role_list['1']="<NAME>";
            $role_list['2']="<NAME>";
        // }
            $role_list['3']="Khách hàng";

        //Get List Địa chỉ

        //Group List
        $group_list = $this->_init['_jsongroup'];
        $customer['role_list'] = $role_list; 
        $right['role_list'] = $role_list; 
        $customer['group_list'] = $group_list['data']; 
        $right['group_list'] = $group_list['data']; 
        
        $customer['detail'] = $_jsonuser['data'];

        $list_ext = $this->_init['_jsonlistext'];
        $customer['list_ext'] = $list_ext['data']; 
        $right['list_ext'] = $list_ext['data']; 

        $list_codic = $this->_init['_jsonlistcodic'];
        $customer['list_codic'] = $list_codic['data']; 

        $_jsonaddress = json_decode(file_get_contents('http://test.tavicosoft.com/crm/index.php/api/address/'.$_cusid.''), true);

        $_jsonhistory = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.'');
        $_jsonhistory_data= json_decode($_jsonhistory,true);
        $right['history'] = $_jsonhistory_data['data'];
        $customer['address'] = $_jsonaddress['data'];

        $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE);
        $_body['left'] = $this->load->view('user/left/ud_info',$customer,TRUE); 
        $_body['right'] = $this->load->view('user/right/ud_history', $right, TRUE);
        $_body['center'] = $this->load->view('user/center/ud_body', $_dataContract, TRUE);


        $_data = [];
        $_data['link'] = 'user/detail';      
        $_data['script'] = $this->load->view('script/script_user_info', NULL, TRUE);
        $_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE);
        $this->load->view('dashboard',$_data);
    }
    public function getAddressApi()
    {
        $custid = $this->input->post('custid');
        $_jsonaddress = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/address/'.$custid.'');

        echo $_jsonaddress;

    }
    public function getHistoryUser()
    {
        $_cusid = $this->input->post('custid');
        $_jsonhistory = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.'');
        echo $_jsonhistory;
    }



    public function create(){
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_city',false, stream_context_create($arrContextOptions)))  ;
        

        $var = $this->session->userdata;
        $roleid = $var['roleid'];
        $role_list = array();
        if($roleid==1){
            $role_list['1']="<NAME>";
            $role_list['2']="Chuyên Viên";
        }
        $role_list['3']="Khách hàng";

        //Group List
        $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group');
        $group_list = json_decode($_jsongroup,true);

        $_data = [];   

        $_jsonlistcodic = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/');
        $list_codic = json_decode($_jsonlistcodic,true);
        $_data['list_codic'] = $list_codic['data']; 

        $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/user');
        $list_ext = json_decode($_jsonlistext,true);
        $_data['list_ext'] = $list_ext['data']; 

        $_data['role_list'] = $role_list; 
        $_data['group_list'] = $group_list['data']; 
        $_data['list_ext'] = $list_ext['data']; 
        $_data['city'] = $_jsoncity;
        $_body = [];
        $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE);
        $_body['left'] = $this->load->view('user/left/ud_info_create', $_data, TRUE); 
        $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
        $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
        $_data['script'] = $this->load->view('script/script_user_info_create', NULL, TRUE);
        $_data['mainview'] = $this->load->view('user/user_create', $_body , TRUE);
        $this->load->view('dashboard',$_data);
    }

    public function getCongnoThanhtoan()
    {
        $contractid = $this->uri->segment(3);
        $this->M_data_API->getCongnoThanhtoan($contractid);
    }

    public function getHistory()
    {
        $contractid = $this->uri->segment(3);
        $this->M_data_API->getHistory($contractid);
    }

    public function getGift()
    {
        $contractid = $this->uri->segment(3);
        $this->M_data_API->getGift($contractid);
    }

    public function getBussEmployee()
    {
        $contractid = $this->uri->segment(3);
        $this->M_data_API->getBussEmployee($contractid);
    }

    public function getNotes()
    {
        $contractid = $this->uri->segment(3);
        $this->M_data_API->getNotes($contractid);
    }

    public function contract(){
        $data['contractid'] = $this->uri->segment(3);
        //a
        $data = array(
            'reportcode'=>'crmContract01a',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'contractid'=> $data['contractid']
            )
        );


        $result = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data);
        $_json = json_decode($result,true);
        $_json2 = json_decode($_json,true);
        $data_left['trade'] = $_json2["result"]["data"];
        $data['ticket_bottom'] = array('data' => [] );
        $right['history'] =[];
        $_body = [];
        $_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE);
        $_body['left'] = $this->load->view('user/left/ud_contract', $data_left, TRUE); 
        //$_body['right'] = $this->load->view('user/right/ud_history', $right, TRUE);
        $_body['center'] = $this->load->view('user/center/ud_contract', $data, TRUE);

        $_data = [];    
        $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
        $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
        $_data['script'] = $this->load->view('script/script_user', NULL, TRUE);
        $_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE);
        $this->load->view('dashboard',$_data);
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $finish = $time;
        $total_time = round(($finish - $this->_init['start']), 4);
        // echo 'Page generated in '.$total_time.' seconds.';
    }
    public function loadTicketContract()
    {
        $contractid = $this->uri->segment(3);
        $seassion_user = $this->session->userdata;
        $this->M_data_API->loadTicketContract($contractid,$seassion_user);
    }
    public function insertPhoneList()
    {
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $data = $this->input->post();
        $__data = $data['ext'];
        $__data1 = parse_str($__data, $get_array);
        //$__extinfo = json_encode($get_array);
        $custid = isset($data['custid'])?$data['custid']:null;
        $phone = isset($data['phone'])?$data['phone']:null;
        $phonelist = isset($data['telephonelist'])?$data['telephonelist']:null;
        $pos = strpos($phonelist, $phone);
        $listphone = $phonelist;
        if ($pos === false) {
            if(strlen($listphone) == 0){
                $listphone = $phone;
            }else{
                $listphone .= ",".$phone;
            }
        }
        $var = $this->session->userdata;
        $log_custid = $custid;
        $log_roleid = $data['roleid'];
        $log_groupid = $data['groupid'];
        
        $postdata = http_build_query([
            'log_custid' => $log_custid,
            'log_roleid' => $log_roleid,
            'log_groupid' => $log_groupid,
            'telephonelist' => $listphone,
            //'action'        => 'deletephone',
            //'extinfo' => $__extinfo
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context);
        $dataAuth = [];
        $this->M_user->updateUser($data['custid'],$postdata,$dataAuth);
        echo $result;
        /*
        $post = $this->input->post();
        $__data = $post['ext'];
        $__data1 = parse_str($__data, $get_array);
        $__extinfo = json_encode($get_array);
        $thunhap = json_encode($__data);
        $postdata = http_build_query([
                'telephonelist' => $post['telephonelist'],
                'extinfo' => $__extinfo,
                'log_custid' => $post['custid'],
                'log_groupid' => $post['groupid'],
                'log_roleid'=> $post['roleid']
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);
        $dataAuth = [];
        $this->M_user->updateUser($post['custid'],$postdata,$dataAuth);
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/update/'.$post['custid'].'',false,$context);
        echo $result;
        */
        // var_dump($post['custid']);
    }

    public function insertEmailList()
    {
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $data = $this->input->post();
        $__data = $data['ext'];
        $__data1 = parse_str($__data, $get_array);
        //$__extinfo = json_encode($get_array);
        $custid = isset($data['custid'])?$data['custid']:null;
        $email = isset($data['email'])?$data['email']:null;
        $emaillist = isset($data['emaillist'])?$data['emaillist']:null;
        $pos = strpos($emaillist, $email);
        $listemailnew = $emaillist;
        if ($pos === false) {
            if(strlen($listemailnew) == 0){
                $listemailnew = $email;
            }else{
                $listemailnew .= ",".$email;
            }
        }
        $var = $this->session->userdata;
        $log_custid = $custid;
        $log_roleid = $data['roleid'];
        $log_groupid = $data['groupid'];

        $postdata = http_build_query([
            'log_custid' => $log_custid,
            'log_roleid' => $log_roleid,
            'log_groupid' => $log_groupid,
            'emaillist' => $listemailnew,
            //'extinfo' => $__extinfo
        ]);

        
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context);
        $dataAuth = [];
        $this->M_user->updateUser($data['custid'],$postdata,$dataAuth);
        echo $result;
        /*

        $post = $this->input->post();
        $__data = $post['ext'];
        $__data1 = parse_str($__data, $get_array);
        $__extinfo = json_encode($get_array);
        $thunhap = json_encode($__data);
        $postdata = http_build_query([
                'emaillist' => $post['emaillist'],
                'extinfo' => $__extinfo,
                'log_custid' => $post['custid'],
                'log_groupid' => $post['groupid'],
                'log_roleid'=> $post['roleid']
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/update/'.$post['custid'].'',false,$context);
        $dataAuth = [];
        $this->M_user->updateUser($post['custid'],$postdata,$dataAuth);
        echo $result;
        */
    }

    public function selectCity()
    {
        $id_city = $this->input->post('id_city');
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_district/'.$id_city.'',false, stream_context_create($arrContextOptions)))  ;
        $city = $_jsoncity;
        echo json_encode($city);
    }

    public function selectDistrict()
    {
        $id_district = $this->input->post('id_district');
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        $_jsoncity = json_decode(file_get_contents('https://hungminhits.com/api/list_ward/'.$id_district.'',false, stream_context_create($arrContextOptions)))  ;
        $city = $_jsoncity;
        echo json_encode($city);
    }

    public function getListExt()
    {
        $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/select/user');
        echo $_jsonlistext;
    }

    public function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    public function getGroupByRoleId()
    {
        $roleid = $this->input->post('roleid');
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group/'.$roleid);
        echo $_jsongroup;
    }

    public function updateUser()
    {
        $var = $this->session->userdata;
        $useraction = $var['custid'];
        $userrole = $var['roleid'];
        if($this->_init['isUpdateUser']==0 && $userrole!=1){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $data = $this->input->post();
        $__data= $this->input->post('ext');
        $__data1 = parse_str($__data, $get_array);
        $__extinfo = json_encode($get_array);
        $thunhap = json_encode($__data);
        $dataAuth = [];
        $issueddate = null;
        if(isset($data['issueddate'])){
            //$issueddate = str_replace("/", "-",$data['issueddate']);
            $issueddate = $data['issueddate'];
        }
        //$issueddate = isset($data['issueddate'])?$data['issueddate']:null;

        $postdata = http_build_query([
                'custid' => isset($data['custid'])?$data['custid']:null,
                'roleid' => isset($data['roleid'])?$data['roleid']:null,
                'groupid' => isset($data['groupid'])?$data['groupid']:null,
                'custname' =>isset($data['custname'])?$data['custname']:null,
                'gender' =>isset($data['gender'])?$data['gender']:null,
                'idcard' => isset($data['idcard'])?$data['idcard']:null,
                'fullbirthday' => isset($data['fullbirthday'])?$data['fullbirthday']:null,
                'telephone' =>isset($data['telephone'])?$data['telephone']:null,
                'email' => isset($data['email'])?$data['email']:null,
                'log_custid' =>$useraction,
                'log_roleid' =>$var['roleid'],
                'log_groupid' =>$var['groupid'],
                // 'city' => isset($data['city'])?$data['city']:null,
                // 'district' =>isset($data['district'])?$data['district']:null,
                // 'ward' =>isset($data['ward'])?$data['ward']:null,
                // 'address' => isset($data['address'])?$data['address']:null,

                'comments' =>isset($data['comments'])?$data['comments']:null,
                'queue'=> isset($data['queue'])?$data['queue']:null,
                'extinfo'=> $__extinfo,
            'issueddate' =>$issueddate,
            'issuedplace' =>isset($data['issuedplace'])?$data['issuedplace']:null
                // 'fulladdress'=> isset($data['fulladdress'])?$data['fulladdress']:null
        ]);

        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);
         $this->M_user->updateUser($data['custid'],$postdata,$dataAuth);
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/update/'.$data['custid'],false,$context);
        $queue = isset($data['queue'])?$data['queue']:null;
        if($queue !=null)
        {
            /*
            $postdata_queue = http_build_query([
                    'extension' =>$data['telephone'],
                    'queue' => $data['queue']
            ]);
            $opts_queue = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata_queue
                )
            );
            $context_queue  = stream_context_create($opts_queue);
            $result_queue_login = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/loginQueue',false,$context_queue);

            $postdata_logout = http_build_query([
                    'extension' =>$data['telephone'],
                    'queue' => $data['queueold']
            ]);
            $opts_logout = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata_logout
                )
            );
            $context_logout  = stream_context_create($opts_logout);  
            $result_queue_logout = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/logoutQueue',false,$context_logout);
            */
        }
        echo $result;

        
    }

    public function aj_insert(){
        
        $post = $this->input->post();
        //Lưu Custid Khi người dụng tạo
        //Tự tạo Custid khi người dùng để trống
        if(isset($post['custid'])){
            $custid = $post['custid'];
        }else{
            $custid = $this->M_api->gen_custid();
        }

        $var = $this->session->userdata;
        $useraction = $var['custid'];
        $userrole = $var['roleid'];
        if($this->_init['isInserUser']==0&& $userrole!=1){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng thêm người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }

        $password = isset($post['password'])?$post['password']:'';
        $password = md5($password);

        $res_data = array(
            'custid'                       =>$custid,
            'roleid'                       =>isset($post['roleid'])?$post['roleid']:'',
            'groupid'                      =>isset($post['groupid'])?$post['groupid']:'',
            'custname'                     =>isset($post['custname'])?$post['custname']:'',
            'gender'                       =>isset($post['gender'])?$post['gender']:'',
            'fullbirthday'                 =>isset($post['fullbirthday'])?$post['fullbirthday']:'',
            'comments'                     =>isset($post['comments'])?$post['comments']:'',
            'extinfo'                      =>isset($post['ext'])?json_encode($post['ext']):'',
            'password'                     =>$<PASSWORD>,
            'queue'                        =>isset($post['queue'])?$post['queue']:''
        );

        if(isset($post['email'])){
            $res_data['email']=$post['email'];
        }

        if(isset($post['telephone'])){
            $res_data['telephone']=$post['telephone'];
        }

        if(isset($post['idcard'])){
            $res_data['idcard']=$post['idcard'];
        }

        if(isset($post['issueddate'])){
            $res_data['issueddate']=$post['issueddate'];
        }

        if(isset($post['issuedplace'])){
            $res_data['issuedplace']=$post['issuedplace'];
        }
        // var_dump($res_data);
        foreach ($res_data as $key => $value) {
            if ($value=='') {
                unset($res_data[$key]);
            }
        }

        $postdata = http_build_query($res_data);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/insert',false,$context);
        echo $result;

        $res_re = json_decode($result,true);
        $address = array(
                'custid'                        => $custid,
                'country'                       =>isset($post['country'])?$post['country']:'',
                'city'                          =>isset($post['city'])?$post['city']:'',
                'district'                      =>isset($post['district'])?$post['district']:'',
                'ward'                          =>isset($post['ward'])?$post['ward']:'',
                'street'                        =>isset($post['street'])?$post['street']:'',
                'address'                       =>isset($post['address'])?$post['address']:'',
                'label'                         =>"Địa chỉ thường trú"
        );
        $address['fulladdress'] = $address['address'].', '.$address['street'].', '.$address['ward'].', '.$address['district'].', '.$address['city'].', '.$address['country'];

        if ($res_re['code']==1) {
            $addLog = array();
            $r_addr = $this->api_save_address($address,$addLog);
        }
    }

    public function aj_validate(){

        $var = $this->session->userdata;
        $useraction = $var['custid'];
        $userrole = $var['roleid'];
        if($this->_init['isInserUser']==0&& $userrole!=1){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng thêm người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $phone = "";
        $email = "";
        $idcard = "";
        $post = $this->input->post();
        if(isset($post['email'])){
            $email=$post['email'];
        }
        if(isset($post['telephone'])){
            $phone=$post['telephone'];
        }
        if(isset($post['idcard'])){
            $idcard=$post['idcard'];
        }
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/validate?phone='.$phone.'&email='.$email.'&idcard='.$idcard);
        echo $result;
    }

    public function aj_insert_bonus_address()
    {
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $post = $this->input->post();
        $address = array(
                'custid'                        => isset($post['custid'])?$post['custid']:'',
                'country'                       =>isset($post['country'])?$post['country']:'',
                'city'                          =>isset($post['city'])?$post['city']:'',
                'district'                      =>isset($post['district'])?$post['district']:'',
                'ward'                          =>isset($post['ward'])?$post['ward']:'',
                'street'                        =>isset($post['street'])?$post['street']:'',
                'address'                       =>isset($post['address'])?$post['address']:'',
                'label'                         =>isset($post['label'])?$post['label']:''
        );
        $address['fulladdress'] = $address['address'].', '.$address['street'].', '.$address['ward'].', '.$address['district'].', '.$address['city'].', '.$address['country'];

        $arrayLog = array(
            'custid'                        => $post['custid'],
            'roleid'                       =>isset($post['roleid'])?$post['roleid']:'',
            'groupid'                      =>isset($post['groupid'])?$post['groupid']:'',
            'action'                       => "Thêm địa chỉ",
            'dataaction'                   => json_encode($address)
        );

        $r_addr = $this->api_save_address($address,$arrayLog);
        echo $r_addr;
    }

    public function aj_update_bonus_address()
    {
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $post = $this->input->post();
        $address = array(
            'custid'                        => isset($post['custid'])?$post['custid']:'',
                'country'                       =>isset($post['country'])?$post['country']:'',
                'city'                          =>isset($post['city'])?$post['city']:'',
                'district'                      =>isset($post['district'])?$post['district']:'',
                'ward'                          =>isset($post['ward'])?$post['ward']:'',
                'street'                        =>isset($post['street'])?$post['street']:'',
                'address'                       =>isset($post['address'])?$post['address']:'',
                'label'                         =>isset($post['label'])?$post['label']:''
        );
        $address['fulladdress'] = $address['address'].', '.$address['street'].', '.$address['ward'].', '.$address['district'].', '.$address['city'].', '.$address['country'];
        $arrayLog = array(
            'custid'                        => $post['custid'],
            'roleid'                       =>isset($post['roleid'])?$post['roleid']:'',
            'groupid'                      =>isset($post['groupid'])?$post['groupid']:'',
            'action'                       => "Sửa địa chỉ",
            'id'                            => $post['addressid'],
            'dataaction'                    => json_encode($address)
        );
        $r_addr = $this->api_update_address($address,$post['addressid'],$arrayLog);
        echo $r_addr;
    }
    public function aj_delete_address()
    {
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $var = $this->session->userdata;
        $log_custid = $var['custid'];
        $log_roleid = $var['roleid'];
        $log_groupid = $var['groupid'];
        $post = $this->input->post('addressid');
        $data = array(
            'custid'                       => $log_custid,
            'roleid'                       =>$log_roleid,
            'groupid'                      =>$log_groupid
        );
        $data['action'] = "Xóa địa chỉ";
        $data['dataaction'] = "";
        $data['id'] = $post;

        $postdata = http_build_query($data);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert_LogAddress',false,$context);


        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/delete/'.$post,false,$context);
        echo $result;
    }
    public function api_delete_address($data,$addressid){

        $postdata = http_build_query($data);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/delete/'.$addressid,false,$context);
        return $result;
    }

    public function api_save_address($data,$dataLog){
        if(count($dataLog)>0)
        {
            $postdata1 = http_build_query($dataLog);
            $opts1 = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata1
                )
            );
            $context1  = stream_context_create($opts1);

            $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert_LogAddress',false,$context1);
        }
        $postdata = http_build_query($data);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert',false,$context);

        return $result;
    }

    public function api_update_address($data,$addressid,$dataLog){
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $postdata1 = http_build_query($dataLog);
        $opts1 = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata1
            )
        );
        $context1  = stream_context_create($opts1);

        $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/insert_LogAddress',false,$context1);

        $postdata = http_build_query($data);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/update/'.$addressid,false,$context);

        return $result1;
    }

    //
    public function updateUserEmailList()
    {
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $data = $this->input->post();
        $__data = $data['ext'];
        $__data1 = parse_str($__data, $get_array);
        //$__extinfo = json_encode($get_array);
        $custid = isset($data['custid'])?$data['custid']:null;
        $email = isset($data['email'])?$data['email']:null;
        $emaillist = isset($data['emaillist'])?$data['emaillist']:null;
        $array_email = explode(',', $emaillist);
        $listemailnew = '';
        $sizearray = count($array_email);
        for($i =0;$i< $sizearray;$i++){
            if($array_email[$i]==$email){
                unset($array_email[$i]);
            }else{
                if(strlen($listemailnew) == 0){
                    $listemailnew = $array_email[$i];
                }else{
                    $listemailnew.= ','.$array_email[$i];
                }
            }
        }
        $var = $this->session->userdata;
        $log_custid = $custid;
        $log_roleid = $data['roleid'];
        $log_groupid = $data['groupid'];
        

        $postdata = http_build_query([
            'log_custid' => $log_custid,
            'log_roleid' => $log_roleid,
            'log_groupid' => $log_groupid,
            'emaillist' => $listemailnew,
            'action'        => 'deleteemail',
            //'extinfo' => $__extinfo
        ]);

        //var_dump(expression)
        
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context);
        $dataAuth = [];
        $this->M_user->updateUser($data['custid'],$postdata,$dataAuth);
        echo $result;
        
    }

    public function updateUserPhoneList()
    {   
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $data = $this->input->post();
        $__data = $data['ext'];
        $__data1 = parse_str($__data, $get_array);
        $__extinfo = json_encode($get_array);
        $custid = isset($data['custid'])?$data['custid']:null;
        $phone = isset($data['phone'])?$data['phone']:null;
        $phonelist = isset($data['phonelist'])?$data['phonelist']:null;
        $array_phone = explode(',', $phonelist);
        $listphone = '';
        $sizearray = count($array_phone);
        for($i =0;$i< $sizearray;$i++){
            if($array_phone[$i]==$phone){
                unset($array_phone[$i]);
            }else{
                if(strlen($listphone) == 0){
                    $listphone = $array_phone[$i];
                }else{
                    $listphone.= ','.$array_phone[$i];
                }
            }
        }
        $var = $this->session->userdata;
        $log_custid = $custid;
        $log_roleid = $data['roleid'];
        $log_groupid = $data['groupid'];
        
        $postdata = http_build_query([
            'log_custid' => $log_custid,
            'log_roleid' => $log_roleid,
            'log_groupid' => $log_groupid,
            'telephonelist' => $listphone,
            'action'        => 'deletephone',
            'extinfo' => $__extinfo
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/update/'.$custid,false,$context);
        $dataAuth = [];
        $this->M_user->updateUser($data['custid'],$postdata,$dataAuth);
        echo $result;

    }

    public function updateAddress()
    {
        //Phân quyền
        if($this->_init['isUpdateUser']==0){
            $data['code'] = 0;
            $data['message'] = 'Bạn thuộc nhóm không có chức năng sửa người dùng';
            $data['data'] = null;
            echo json_encode($data);
            return;
        }
        $data = $this->input->post();
        $addressid = $data['addressid'];
        unset($data['addressid']);
        $var = $this->session->userdata;
        $log_custid = $var['custid'];
        $log_roleid = $var['roleid'];
        $log_groupid = $var['groupid'];
        //$data['log_custid'] => $log_custid;
        $postdata = http_build_query($data);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/address/update/'.$addressid,false,$context);
        echo $result;
        
    }
    public function searchUser()
    {
        $keyword1 = $this->input->post('keyword');
        $keyword = urlencode($keyword1);
        $_jsonSearch = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/search?action=search_customer&roleid=1&search='.$keyword);
        echo $_jsonSearch;
    }
    public function getUserByRecodeId()
    {
        $var = $this->session->userdata;
        $roleid = $var['roleid'];
        $post = $this->input->post("id");
        $_jsonUser = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyid?id='.$post);
        echo $_jsonUser;
    }
    public function viewUserHistory()
    {
        $_cusid = $_GET['cusid'];
        $role_list = array();
            $role_list['1']="<NAME>";
            $role_list['2']="Chuyên Viên";
            $role_list['3']="Khách hàng";

        $group_list = $this->_init['_jsongroup'];
        $right['role_list'] = $role_list; 
        $right['group_list'] = $group_list['data']; 
        $list_ext = $this->_init['_jsonlistext'];
        $right['list_ext'] = $list_ext['data']; 
        $_jsonhistory = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.'');
        /*
        echo 'http://test.tavicosoft.com/crm/index.php/api/user_history/'.$_cusid.'';
        exit;
        */
        $_jsonhistory_data= json_decode($_jsonhistory,true);
        $right['history'] = $_jsonhistory_data['data'];
        $_data['mainview'] = $this->load->view('user/right/ud_history', $right, TRUE);
        $this->load->view('dashboard',$_data);
    }
}
?><file_sep><form method="POST" id="dataInsertGroup" action="<?php echo base_url().'groupuser/groupuserinsert' ?>">
<div class="tile p-0 padding-5 margin-bot-5">
	          <div class="tile-body padding-left-10">
	          		<input type="hidden" value="" id="groupid"/>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Tên nhóm</label>
	              		<label class="control-label col-md-7 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" value="" placeholder="<NAME>" name="groupname" id="custname" required="" minlength="4">
		              		<input type="hidden" class="col-md-12 no-padding font-size-12" value="-1" placeholder="" name="roleid" id="roleid" required="" minlength="4">
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Trạng thái</label>
	              		<select class="control-label col-md-7 no-border no-padding margin-left-10" name="status" id="status">
	              			<option value="0">Không hoạt động</option>
	              			<option value="1">Đang hoạt động</option>
	              		</select>
	            	</div>
	            </div>
	        </div>
	        <div class="tile p-0 padding-5 margin-bot-5">
	             <div class="tile-body padding-left-10">
	             	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding"></label>
	            		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label2 col-md-3 no-padding">Xem</label>
		            		<label class="control-label user-label2 col-md-3 no-padding">Thêm</label>
		            		<label class="control-label user-label2 col-md-3 no-padding">Sửa</label>
		              	</label>
		            		
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Phiếu</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="ticketrule" id="ticketrule">
	              			<option value="0" >Không</option>
	              			<option value="1" >Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewticket" id="viewticket" value="1"></label>
		              		<input id='viewtickethidden' type='hidden' value='0' name='viewticket'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="addticket" id="addticket" value="1"></label>
		            		<input id='addtickethidden' type='hidden' value='0' name='addticket'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="editticket" id="editticket" value="1"></label>
		            		<input id='edittickethidden' type='hidden' value='0' name='editticket'>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Người dùng</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="userrule" id="userrule">
	              			<option value="0">Không</option>
	              			<option value="1">Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewuser" id="viewuser" value="1"></label>
		              		<input id='viewuserhidden' type='hidden' value='0' name='viewuser'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="adduser" id="adduser" value="1"></label>
		            		<input id='adduserhidden' type='hidden' value='0' name='adduser'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="edituser" id="edituser" value="1"></label>
		            		<input id='edituserhidden' type='hidden' value='0' name='edituser'>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Công việc</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="taskrule" id="taskrule">
	              			<option value="0">Không</option>
	              			<option value="1">Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewtask" id="viewtask" value="1"></label>
		              		<input id='viewtaskhidden' type='hidden' value='0' name='viewtask'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="addtask" id="addtask" value="1"></label>
		            		<input id='addtaskhidden' type='hidden' value='0' name='addtask'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="edittask" id="edittask" value="1"></label>
		            		<input id='edittaskhidden' type='hidden' value='0' name='edittask'>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Thư viện</label>
	              		<!-- <select class="control-label col-md-7 no-border no-padding margin-left-10" name="knowledgerule" id="knowledgerule">
	              			<option value="0">Không</option>
	              			<option value="1">Xem/Sửa</option>
	              		</select> -->
	              		<label class="control-label col-md-7 no-padding-right">
		              		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewknowledge" id="viewknowledge" checked="" disabled="" value="1"></label>
		              		<input id='viewknowledgehidden' type='hidden' value='1' name='viewknowledge'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="addknowledge" id="addknowledge" value="1"></label>
		            		<input id='addknowledgehidden' type='hidden' value='0' name='addknowledge'>

		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="editknowledge" id="editknowledge" value="1"></label>
		            		<input id='editknowledgehidden' type='hidden' value='0' name='editknowledge'>
		              	</label>
	            	</div>
	            </div>
 </div>
 			<div class="tile p-0 padding-5 margin-bot-5">
	             <div class="tile-body padding-left-10">
	             	<label class="control-label col-md-4 no-padding" style="font-size: 12px;font-weight: 500;color: rgb(118, 121, 116);"><i class="far fa-window-maximize"></i>  View </label>
	             	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Xem tất cả phiếu</label>
	            		<label class="control-label col-md-7 no-padding-right">
		            		<label class="control-label user-label col-md-3 no-padding"><input type="checkbox" name="viewpermission" id="viewpermission" value="1"></label>
			              		<input id='viewpermissionhidden' type='hidden' value='0' name='viewpermission'>
		              	</label>
	            	</div>
	             </div>
	         </div>
	            	<div class="fc-corner-right">
		          		<div class="fc-button-group" style="float:right">
							<button type="button" class="btn btn-primary float-right margin-bot-5 btn-creategroupuser"><i class="fa fa-share"></i>Lưu thông tin</button>

						</div>
		          	</div>
</form><file_sep><div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5>Trường dữ liệu Phiếu hỗ trợ</h5>
			        </div>
			    </div>
			    <p class="margin-top-10 no-margin-bot">Trường dữ liệu người dùng cho phép định nghĩa các trường dữ liệu(fields) bổ sung các thông tin Phiếu hỗ trợ, các trường dữ liệu này chỉ có thể dùng cho mục đích phân tích PIVOT hoặc Báo cáo quản trị được thiết kế dành riêng cho, không áp dụng cho báo cáo, bảng điều khiển (dashboard) và đồ thị mặc định của hệ thống.</p>
			    <div class="row" style="margin-top: 50px;">
			    	<div class="col-md-5">
			    		<span><b>Trường dữ liệu hiện tại (<?php echo count($list_ext) ?>)</b></span>
			    	</div>
			    	<div class="col-md-7">
						    <div style="float: right;">
								<button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal1">Thêm</button>
							</div>
			    	</div>
			    </div>
			    
				<div class="bs-component margin-top-10">
					<?php 
					if(count($list_ext) >0)
					{
					foreach ($list_ext as $value) { ?>
					<a style="cursor: pointer;" class="user-name" onclick="addTab('<?php echo base_url()?>groupuser/fielddetail/<?php echo $value['fieldcode'] ?>/<?php echo $value['fieldtype'] ?>/<?php echo $value['datasource'] ?>','<?php echo $value['fieldname'] ?>')">
					<div class="component-fields">
						<?php if($value['fieldtype'] == 'T')
				                    {
				                    	$icon = 'fas fa-font';
				                    }
				                    else{
				                    	$icon = 'far fa-caret-square-down';
				                    }
				                     ?>
				                    <i class="<?php echo $icon ?>"></i> 
				                    <span class="title_tab" style="padding-left: 6px"><?php echo $value['fieldname'] ?></span>
					</div>
					</a>
					<?php }} ?>
	            </div>
          	</div>

          		<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document" style="margin-top: 8%">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Thêm trường dữ liệu Phiếu hỗ trợ</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
      		<div class="form-group">
					    <label for="exampleInputEmail1">Kiểu dữ liệu</label>
					    <select class="form-control" id="fieldtype" name="fieldtype" onchange="selectType(this)">
	              			<option selected="" class="group_item" value="T">Text</option>
	              			<option class="group_item" value="D">Drop down list</option>
	              		</select>
			</div>

			<div class="form-group">
					    <label for="exampleInputEmail1">Mã trường</label>
					    <input type="text" class="form-control" name="fieldcode" id="fieldcode" placeholder="-Mã trường">
			</div>

			<div class="form-group extendbottom">
					    <label for="exampleInputEmail1">Tên trường</label>
					    <input type="text" class="form-control" name="fieldname" id="fieldname" placeholder="-Tên trường">
			</div>

			
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" class="btn btn-primary" onclick="insertExtUser('ticket')">Thêm</button>
      </div>
    </div>
  </div>
</div><file_sep><div class="div-info-customer">
<?php if(isset($customer)){ ?>
<div class="tile p-0 padding-5 margin-bot-5">
  <div class="content-title user-history">
    <div class="width-100per">
    	<p class="flex">
        <img onclick="addTab('<?php echo base_url()."user/detail/?cusid=".$customer[0]['custid']."&idcard=".$customer[0]['idcard']."&roleid=".$customer[0]['roleid']?>','<?php echo $customer[0]['custname'] ?>')" class="user-avatar" src="<?php echo $customer[0]['avatar']; ?>" alt="User Image"><?php echo $customer[0]['custname'];?> - <?php echo $customer[0]['groupname'];?>
      </p>
    	<p class="header-desc field-click-able">
        Ngày tạo: <?php echo date("d/m/Y", strtotime($customer[0]['createddate']));?>
      </p>
      <p class="margin-left-50">
        Số điện thoại: 
        <a href="#" onclick="parent.iframe_click('<?php echo($customer[0]['telephone'])?>','<?php echo($this->uri->segment(3))?>')" id="user_phone_number">
          <?php echo($customer[0]['telephone'])?>
        </a>
      </p>
    </div>
  </div>
</div>
<?php } ?>
</div>
<div class="div-recent-ticket <?php echo(isset($view)?'hide':'')?>">
  <div class="tile p-0 padding-5 margin-bot-5">
	 <p class="no-margin">Phiếu gần nhất</p>
      <div class="table-responsive">
        <table class="table" id="table-22">
          <thead class="hide">
            <tr>
              <th></th>
              <th></th>
            </tr>
          </thead>
        </table>
      </div>
  </div>
</div>

<div class="div-contract <?php echo(isset($view)?'hide':'')?>">
  <div class="tile p-0 padding-5 margin-bot-5">
  	<p class="no-margin">Danh sách giao dịch</p>
      <div class="table-responsive">
        <table class="table" id="table-23">
          <thead class="hide">
            <tr>
              <th></th>
              <th></th>
              <th></th>
            </tr>
          </thead>
        </table>
      </div>
  </div>
</div>
<div class="tile p-0 padding-5 margin-bot-5 toggle-up">
   <p>Thư viện kiến thức
    <i class="fa fa-angle-double-up knl-caret"></i>
    </p>
    <div class="flex margin-top-12 padding-right-5">
      <button class="btn btn_blank" id="knl-btn-back" type="button">
        <i class="fa fa-arrow-left"></i>
      </button>
      <div class="knl-input-group flex">
          <input name="knl_text" class="width-100per" type="text">
          <i class="fa fa-search search-knowledge"></i>
      </div>
    </div>
    <div class="knl-board hide margin-top-5">
      <div id="knl_list" class="padding-5">
      </div>
      <div class="knl-content hide padding-5">
      </div>
    </div>
</div><file_sep><script type="text/javascript">
  $(document).ready(function(){
    $('#login_form').on('submit',function(){
      var cur = $(this);
      var formData = new FormData($(this)[0]);

      for (var [key, value] of formData.entries()) { 
            // console.log(key, value);
      }
      cur.find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spinner fa-spin');
      $.ajax({
      type: "POST",
        url: "<?php echo base_url().'login/post_login'?>",
        data:  formData,
        dataType:'json',
        contentType: false,
        cache: false,
        processData:false,
        beforeSend: function() {
        },
        success: function(data) {
          cur.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-sign-in');
          if(data.message == "Success"){
            window.location.href = "<?php echo base_url().'login/login'?>";
          }else{
            swal("Lỗi !", "Sai tên đăng nhập hoặc mật khẩu.", "error");
          }

        },
        error: function(xhr, status, error) {
          cur.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-sign-in');
          // swal("Lỗi !", "Vui lòng kiểm tra lại mạng.", "error");
          console.log(error);
        }
      });
      return false;
      });
  });
</script><file_sep><div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5><?php echo $gdetail['groupname']?></h5>
			        </div>
			    </div>
				<div class="bs-component">
          			<div class="table-responsive" style="height: 1024px">	              
          				<table class="table" id="table">	                
          					<tbody>
                                        <?php if(count($useringroup)>0){ ?>
                                        <?php foreach ($useringroup as $user) {
                                             ?>
                                                  <tr>                     
                                                       <td width="5%">                  
                                                            <img class="user-avatar" src="<?php echo $user['avatar'];?>" alt="User Image">                 
                                                       </td>                 
                                                       <td width="50% ">                 
 <a class="user-name" style="cursor: pointer;" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$user['custid'].'&idcard='.$user['idcard'].'&roleid='.$user['roleid'] ?>','<?php echo $user['custname'];?>')"><?php echo $user['custname'];?></a>
                                                            <p class=""><!--3--></p>               
                                                       </td>                 
                                                       <td width="13%"><?php echo $user['telephone'];?></td>                 
                                                       <td width="13%"><?php echo $user['email'];?></td>            
                                                  </tr>
                                             <?php
                                        }}else{
                                             echo "Chưa có người dùng nào trong nhóm";
                                        } ?>             
          					</tbody>	              
          				</table>	            
          			</div>
	            </div>
          	</div>
               <file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Groupuser extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		//Do your magic here
		 $this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model('M_api');
	}
	public function index()
	{	
		$_body = [];
		$_data = [];    
		$group_data = $this->M_api->getlistgroup();
		$data['listgroup'] = json_decode($group_data,true)['data'];

		$__jsonCount = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/countgroupid');

		$_jsonGroupDetail = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/countgroupid');
		$data['countPeople'] = json_decode($__jsonCount,true)['data'];
		$_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); 
		$_data['script2'] = $this->load->view('script/script_group_edit', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('groupuser/center/gu_info', $data , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function fielduser()
	{
		$_data = [];    
		$_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/selectall/user');
        $list_ext = json_decode($_jsonlistext,true);
        $customer['list_ext'] = $list_ext['data']; 
		$_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('groupuser/center/gu_fielduser', $customer , TRUE);
		$this->load->view('dashboard',$_data);
	}
	public function fielddetail()
	{
		$list_extend['list_ext'] = [];
		$list_extend['detail'] =[];
		$fieldtype = $this->uri->segment(4);
		if($fieldtype == 'D')
		{
			$datasource = $this->uri->segment(5);
			$_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/'.$datasource);
	        $list_ext = json_decode($_jsonlistext,true);
	        $list_extend['list_ext'] = $list_ext['data']; 
		}
		$fieldcode  = $this->uri->segment(3);
		$_jsondetail = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/getextdatabycode/'.$fieldcode);
	        $list_field = json_decode($_jsondetail,true);
	        $list_detail['detail'] = $list_field['data']; 
	        $list_extend['detail'] = $list_field['data']; 
		$_body = [];
		$_body['left'] = $this->load->view('groupuser/left/gu_left_field',$list_detail,TRUE); 
		$_body['center'] = $this->load->view('groupuser/center/gu_center_field', $list_extend, TRUE);
		$_data = [];    
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); 
		$_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('groupuser/gu_main', $_body , TRUE);
		$this->load->view('dashboard',$_data);	
	}

	public function fieldticket()
	{
		$_data = [];    
		$_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/selectall/ticket');
        $list_ext = json_decode($_jsonlistext,true);
        $customer['list_ext'] = $list_ext['data']; 
		$_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('groupuser/center/gu_fieldticket', $customer , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function groupuserdetail()
	{
		$groupid=$this->input->get('groupid');
		$_body = [];
		$group = [];
		$group_detail = $this->M_api->getlistgroup($groupid);
		$group['gdetail'] = json_decode($group_detail,true)['data'][0];

		$_jsongrdetail = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/select_groupdetail');
		$group['groupdetail'] = json_decode($_jsongrdetail,true);
		$customerbygroup = $this->M_api->getlistcustomerbygroupid($group['gdetail']['groupid']);
		$group['useringroup'] = json_decode($customerbygroup,true)['data']; 
		$_body['left'] = $this->load->view('groupuser/left/gu_left_groupuser',$group,TRUE);
		$_body['center'] = $this->load->view('groupuser/center/gu_center_groupuser', $group, TRUE);
		$_data = [];    
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); 
		$_data['script'] = $this->load->view('script/script_group_edit', NULL, TRUE);  
		$_data['script2'] = $this->load->view('script/script_dashboard', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('groupuser/gu_main', $_body , TRUE);
		$this->load->view('dashboard',$_data);	
	}

	public function updategroup(){
		$data = $this->input->post();
		$groupid = $data['groupid'];
        $ticketrule = $this->input->post('ticketrule');
        $ticketrule = $data['viewticket'].$data['addticket'].$data['editticket'];
		$userrule = $data['viewuser'].$data['adduser'].$data['edituser'];
		$taskrule = $data['viewtask'].$data['addtask'].$data['edittask'];
		$knowledgerule = '1'.$data['addknowledge'].$data['editknowledge'];
        $postdata = http_build_query([
            'ticketrule'=>$ticketrule,
            'userrule'=>$userrule,
            'taskrule'=>$taskrule,
            'knowledgerule'=>$knowledgerule,
            'status'=>$data['status'],
            'groupname'=>$data['groupname']
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/update/'.$groupid.'',false,$context);

		$viewpermission = $data['viewpermission'];
		$viewpermissionold = $data['oldpermission'];
        if($viewpermission != $viewpermissionold)
		{
			if($viewpermission == 1)
			{

			$postdata1 = http_build_query([
						'groupid' => $groupid,
						'viewid' => '1'
					]);
			$opts1 = array('http' =>
	            array(
	                'method'  => 'POST',
	                'header'  => 'Content-type: application/x-www-form-urlencoded',
	                'content' => $postdata1
	            )
	        );
	        $context1  = stream_context_create($opts1);
	        $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/insert_groupdetail',false,$context1);
	        }
	        else{
		        $result2 = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/delete_groupdetail/'.$groupid,false);
	        }
		}
        echo $result;
		// var_dump($data);
	}

	public function groupuserinsert()
	{
		$data =$this->input->post();
		$ticketrule = $data['viewticket'].$data['addticket'].$data['editticket'];
		$userrule = $data['viewuser'].$data['adduser'].$data['edituser'];
		$taskrule = $data['viewtask'].$data['addtask'].$data['edittask'];
		$knowledgerule = '1'.$data['addknowledge'].$data['editknowledge'];
		$postdata = http_build_query(['groupname' => $data['groupname'],
						'tvcdb' => 'AGT',
						'roleid' =>$data['roleid'],
						'status' =>$data['status'],
						'userrule' =>$userrule,
						'ticketrule'=>$ticketrule,
						'taskrule'=>$taskrule,
						'knowledgerule'=>$knowledgerule]);
		$opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/GroupTest/insert',false,$context);
		$viewpermission = $data['viewpermission'];
		if($viewpermission == 1)
		{
			$arrayResult = json_decode($result,true);
			// echo $arrayResult['data'];

			$postdata1 = http_build_query([
						'groupid' => $arrayResult['data'],
						'viewid' => '1'
					]);
			$opts1 = array('http' =>
	            array(
	                'method'  => 'POST',
	                'header'  => 'Content-type: application/x-www-form-urlencoded',
	                'content' => $postdata1
	            )
	        );
	        $context1  = stream_context_create($opts1);

	        $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/insert_groupdetail',false,$context1);
		}
        echo $result;
	}

	public function viewInsertGroup()
	{
		$_body = [];
		$group = [];
		$_body['left'] = $this->load->view('groupuser/left/gu_left_creategroup',null,TRUE);
		$_data = [];    
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['script'] = $this->load->view('script/script_create_groupuser', NULL, TRUE); 
		$_data['mainview'] = $this->load->view('groupuser/gu_insert', $_body , TRUE);
		$this->load->view('dashboard',$_data);	
	}

	public function postData($array,$url)
	{
		$postdata = http_build_query([
                $array
        ]); 
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents($url,false,$context) ;
        return $result;
	}

	public function insertFieldUser()
	{
		$data= $this->input->post();
		$postdata = http_build_query([
						'tvcdb' => 'AGT',
						'status'=>'1',
						'fieldtype' => isset($data['fieldtype'])?$data['fieldtype']:'',
						'formid' => isset($data['formid'])?$data['formid']:'',
						'fieldcode' =>isset($data['fieldcode'])?$data['fieldcode']:'',
						'datasource' =>isset($data['datasource'])?$data['datasource']:'',
						'fieldname' =>isset($data['fieldname'])?$data['fieldname']:'']);
		$opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/insert',false,$context);

		 $__data1 = parse_str($data['dataExt'], $get_array);
         if($data['dataExt'] !=null)
         {
         	for ($i=0; $i <count($get_array['code']) ; $i++) { 
         				$postdata_codic = http_build_query([
										'code' => $get_array['code'][$i],
										'name' => $get_array['name'][$i],
										'status' =>'W',
										'category' =>$data['datasource'],
										'tvcdb' =>'AGT']);
						$opts_codic = array('http' =>
				            array(
				                'method'  => 'POST',
				                'header'  => 'Content-type: application/x-www-form-urlencoded',
				                'content' => $postdata_codic
				            )
				        );
				        $context_codic  = stream_context_create($opts_codic);

				        $result_codic = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/insert',false,$context_codic);
         	}
         }
        echo $result;
	}

	public function insertSelectBox()
	{
		$data = $this->input->post();
		$postdata = http_build_query([
						'code' => $data['code'],
						'name' => $data['name'],
						'status' => isset($data['status'])?$data['status']:'W',
						'category' =>$data['category'],
						'comments' =>isset($data['comments'])?$data['comments']:'',
						'ref1' => isset($data['ref1'])?$data['ref1']:'',
						'ref2' => isset($data['ref2'])?$data['ref2']:'',
						'tvcdb' =>'AGT']);
		$opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/insert',false,$context);
        echo $result;
	}

	public function updateFields()
	{
		$data = $this->input->post();
		$postdata = http_build_query([
						'fieldcode' => $data['fieldcode'],
						'fieldname' => $data['fieldname'],
						'status' =>$data['status']]);
		$opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/extdata/update/'.$data['fieldcode'],false,$context);
        echo $result;
	}

	public function updateCodictionary()
	{
		$data = $this->input->post();
		if($data['action'] == 'delete')
		{
			$status = 'C';
		}
		else
		{
			$status = 'W';
		}
		$postdata = http_build_query([
						'code' => $data['code'],
						'category' => $data['category'],
						'status' =>$status,
						'name'=> isset($data['name'])?$data['name']:null
					]);
		$opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/update/'.$data['category'].'/'.$data['code'],false,$context);
        echo $result;
	}
	public function updateDatasource()
	{
		$data = $this->input->post();
		
		$postdata = http_build_query([
						'code' => $data['code'],
						'category' => $data['category'],
						'status' =>$data['status'],
						'comments' => $data['comments'],
						'name'=> isset($data['name'])?$data['name']:'',
						'ref1' =>isset($data['ref1'])?$data['ref1']:'',
						'ref2' =>isset($data['ref2'])?$data['ref2']:''
					]);
		$opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/update/'.$data['category'].'/'.$data['code'],false,$context);
        echo $result;
	}
}

/* End of file Groupuser.php */
/* Location: ./application/controllers/Groupuser.php */
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
        //$this->load->model(array('M_data'));
    }

	public function index()
	{
		if($this->session->userdata("custid"))//If already logged in
        {
            redirect(base_url('dashboard'));
        }
		$_data = []; 
        $_data['script'] = $this->load->view('script/script_login', NULL, TRUE);
		$this->load->view('login/login',$_data);
	}

	public function login(){
		if($this->session->userdata("custid"))//If already logged in
        {
            redirect(base_url('dashboard'));
        }
        $data['error'] = 0;
        redirect(base_url('login'));
	}

    public function post_login()  
    {  

        $username = $this->input->post('username');  
        $password = $this->input->post('password');  

        $postdata = http_build_query([
                'username' => $username,
                'password' => $<PASSWORD>
            
        ]);
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Api/login',false,$context);
        $response = json_decode($result,true);
        if (isset($response['data'])) {
            $this->session->set_userdata('custid',$response['data'][0]['custid']);
            $this->session->set_userdata('groupid',$response['data'][0]['groupid']);
            $this->session->set_userdata('telephone',$response['data'][0]['telephone']);
            $this->session->set_userdata('custname',$response['data'][0]['custname']);
            $this->session->set_userdata('avatar',$response['data'][0]['avatar']);
            $this->session->set_userdata('roleid',$response['data'][0]['roleid']);
            $this->session->set_userdata('idcard',$response['data'][0]['idcard']);
        }
        echo $result;
    }

	public function logout()
    {
        $this->session->sess_destroy();
        redirect(base_url('login'));
    }
    public function connect(){
        // phpinfo();
        $otherdb = $this->load->database('sqlsvr12', TRUE);
        $query = $otherdb->select('*')->get('crcustomer')->result_array();
        var_dump($query);
    }
}<file_sep><?php
error_reporting(0);
ini_set('display_errors', 0);
defined('BASEPATH') OR exit('No direct script access allowed');

class M_data_API extends CI_Model {
	public function __construct()
	{
		parent::__construct();
        $this->dayCompare = strtotime('2000-01-01T00:00:00');
	}
	public function loadTicketContract($contractid,$user_seassion)
	{
        $custid = $user_seassion['custid'];
        $roleid = $user_seassion['roleid'];
        $groupid = $user_seassion['groupid'];
		    $json_ticket_bottom = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketbytransref/'.$contractid.'?custid='.$custid.'&groupid='.$groupid);
        $data['trade_cntt'] = json_decode($json_ticket_bottom,true)['data'];
        $text = '';
        for ($i=0; $i < count($data['trade_cntt']); $i++) { 
            $timeCreate = preg_replace('/\s/', 'T',$data['trade_cntt'][$i]['createat']);
                $timeUpdate = preg_replace('/\s/', 'T',$data['trade_cntt'][$i]['lastupdate']);
                if(strtotime($timeCreate) > $this->dayCompare)
                {
                    $createat = date("d/m/Y",strtotime($timeCreate));
                }else{$createat='';}
                if(strtotime($timeUpdate) > $this->dayCompare)
                {
                    $lastupdate = date("d/m/Y",strtotime($timeUpdate));
                }else{$lastupdate='';}
            $href = ''.base_url().'ticket/detail/'.$data['trade_cntt'][$i]['ticketid'].'/'.$data['trade_cntt'][$i]['custid'].'';
            $onclick = "addTab('".$href."','".$data['trade_cntt'][$i]['ticketid']."')";
            if($i == (count($data['trade_cntt'])-1))
            {
                
                $text .= '[
                       "<a onclick='.$onclick.' href=\'#\'><span class=\'id-label span-danger\'>O</span> #' .$data['trade_cntt'][$i]['ticketid']. '</a>",
                       "'.$data['trade_cntt'][$i]['title'].'",
                       "'.$createat.'",
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$lastupdate.'"
                      ]';
            }
            else
            {
                $text .= '[
                       "<a onclick='.$onclick.' href=\'#\'><span class=\'id-label span-danger\'>O</span> #' .$data['trade_cntt'][$i]['ticketid']. '</a>",
                       "'.$data['trade_cntt'][$i]['title'].'",
                       "'.$createat.'",
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$lastupdate.'"
                      ],
                      ';
            }
        }

        echo '{
              "data": 
                [
                    '.$text.'
                ]
            }';
	}
	public function getContractByIdcard($idcard,$opid)
	{
    $array['data'] = [];
    if($idcard != '')
    {
  		$data_contractc = array(
              'reportcode'=>'crmContract01',
              'limit'=>25,
              'start'=>0,
              'queryFilters'=>array(
                  'idcard'=> $idcard
              )
          );

          $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc);
          $_json_contractc = json_decode($result_contractc,true);
          $_json2_contractc = json_decode($_json_contractc,true);
          $data['trade_cntt'] = $_json2_contractc["result"]["data"]; 
          $text = '';
          for ($i=0; $i < count($data['trade_cntt']); $i++) { 
              if(strtotime($data['trade_cntt'][$i]['startdate']) > $this->dayCompare)
              {
                  $startdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['startdate']));
              }else{$startdate='';}
              if(strtotime($data['trade_cntt'][$i]['effectivedate']) > $this->dayCompare)
              {
                  $effectivedate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['effectivedate']));
              }else{$effectivedate='';}
              $href = ''.base_url().'user/contract/'.$data['trade_cntt'][$i]['contractid'].'?opid='.$opid.'';
              $onclick = "addTab('".$href."','".$data['trade_cntt'][$i]['contractid']."')";
              $_arr = ["<a onclick=".$onclick." href='#'>".$data['trade_cntt'][$i]['contractid']. "</a>","".$data['trade_cntt'][$i]['status']."","".$data['trade_cntt'][$i]['property']."","".$startdate."","".$effectivedate."","".$data['trade_cntt'][$i]['notes'].""];
              array_push($array['data'],$_arr);
          }
      }
        echo json_encode($array);
	}
	public function getCongnoThanhtoan($contractid)
	{
		$data_contractc = array(
            'method' => 'getReturnData',
            'reportcode'=>'crmContract01c',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'contractid'=> $contractid
            )
        );

        $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc);
        $_json_contractc = json_decode($result_contractc,true);
        $_json2_contractc = json_decode($_json_contractc,true);
        $data['trade_cntt'] = $_json2_contractc["result"]["data"];
        $text = '';
        for ($i=0; $i < count($data['trade_cntt']); $i++) { 
          $data['trade_cntt'][$i]['transdate'] = str_replace("/", "-", $data['trade_cntt'][$i]['transdate']);
          $data['trade_cntt'][$i]['duedate'] = str_replace("/", "-", $data['trade_cntt'][$i]['duedate']);
          if(strtotime($data['trade_cntt'][$i]['transdate']) > $this->dayCompare)
                {
                    $transdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['transdate']));
                }else{$transdate='';}
                if(strtotime($data['trade_cntt'][$i]['duedate']) > $this->dayCompare)
                {
                    $duedate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['duedate']));
                }else{$duedate='';}
            if($i == (count($data['trade_cntt'])-1))
            {
                
                $text .= '[
                       "'.$data['trade_cntt'][$i]['revenuetype'].'",
                       "'.$data['trade_cntt'][$i]['value0'].'",
                       "'.$data['trade_cntt'][$i]['value4'].'",
                       "'.$transdate.'",
                       "'.$duedate.'",
                       "'.number_format(abs($data['trade_cntt'][$i]['amount'])).'",
                       "'.$data['trade_cntt'][$i]['extdescription1'].'",
                       "'.$data['trade_cntt'][$i]['allocation'].'",
                       "'.$data['trade_cntt'][$i]['anal_r9'].'"
                      ]';
            }
            else
            {
                $text .= '[
                       "'.$data['trade_cntt'][$i]['revenuetype'].'",
                       "'.$data['trade_cntt'][$i]['value0'].'",
                       "'.$data['trade_cntt'][$i]['value4'].'",
                       "'.$transdate.'",
                       "'.$duedate.'",
                       "'.number_format(abs($data['trade_cntt'][$i]['amount'])).'",
                       "'.$data['trade_cntt'][$i]['extdescription1'].'",
                       "'.$data['trade_cntt'][$i]['allocation'].'",
                       "'.$data['trade_cntt'][$i]['anal_r9'].'"
                      ],
                      ';
            }
        }

        echo '{
              "data": 
                [
                    '.$text.'
                ]
            }';
	}
	public function getHistory($contractid)
	{
		$data_contractc = array(
            'method' => 'qry',
            'reportcode'=>'crmContract01b',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'contractid'=> $contractid
            )
        );
        $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc);
        $_json_contractc = json_decode($result_contractc,true);
        $_json2_contractc = json_decode($_json_contractc,true);
        $data['trade_cntt'] = $_json2_contractc["result"]["data"];
        $text = '';
        for ($i=0; $i < count($data['trade_cntt']); $i++) { 
                if(strtotime($data['trade_cntt'][$i]['statusdate']) > $this->dayCompare)
                {
                    $statusdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['statusdate']));
                }else{$statusdate='';}
            if($i == (count($data['trade_cntt'])-1))
            {
                $name = 0;
                if(isset($data['trade_cntt'][$i]['name'])){
                  $name = $data['trade_cntt'][$i]['name']; 
                }

                $name1 = 0;
                if(isset($data['trade_cntt'][$i]['name1'])){
                  $name1 = $data['trade_cntt'][$i]['name1']; 
                }

                $text .= '[
                       "'.$data['trade_cntt'][$i]['status'].'",
                       "'.$statusdate.'",
                       "'.number_format($name).'",
                       "'.number_format($name1).'",
                       "'.$data['trade_cntt'][$i]['remarks'].'"
                      ]';
            }
            else
            {
                $text .= '[
                       "'.$data['trade_cntt'][$i]['status'].'",
                       "'.$statusdate.'",
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$data['trade_cntt'][$i]['name1'].'",
                       "'.$data['trade_cntt'][$i]['remarks'].'"
                      ],
                      ';
            }
        }

        echo '{
              "data": 
                [
                    '.$text.'
                ]
            }';
	}
	public function getGift($contractid)
	{
		$data_contractc = array(
            'method' => 'qry',
            'reportcode'=>'crmContract01d',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'contractid'=> $contractid
            )
        );
        $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc);
        $_json_contractc = json_decode($result_contractc,true);
        $_json2_contractc = json_decode($_json_contractc,true);
        $data['trade_cntt'] = $_json2_contractc["result"]["data"];
        $text = '';
        for ($i=0; $i < count($data['trade_cntt']); $i++) { 
                if(strtotime($data['trade_cntt'][$i]['promotiondate']) > $this->dayCompare)
                {
                    $promotiondate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['promotiondate']));
                }else{$promotiondate='';}
            if($i == (count($data['trade_cntt'])-1))
            {
                $text .= '[
                       "'.$promotiondate.'",
                       "'.$data['trade_cntt'][$i]['description'].'",
                       "'.number_format($data['trade_cntt'][$i]['quantity']).'",
                       "'.number_format(abs($data['trade_cntt'][$i]['amount'])).'",
                       "'.$data['trade_cntt'][$i]['remarks'].'"
                      ]';
            }
            else
            {
                $text .= '[
                       "'.$promotiondate.'",
                       "'.$data['trade_cntt'][$i]['description'].'",
                       "'.$data['trade_cntt'][$i]['quantity'].'",
                       "'.$data['trade_cntt'][$i]['amount'].'",
                       "'.$data['trade_cntt'][$i]['remarks'].'"
                      ],
                      ';
            }
        }

        echo '{
              "data": 
                [
                    '.$text.'
                ]
            }';
	}
	public function getBussEmployee($contractid)
	{
		$data_contractc = array(
            'method' => 'qry',
            'reportcode'=>'crmContract01f',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'contractid'=> $contractid
            )
        );
        $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc);
        $_json_contractc = json_decode($result_contractc,true);
        $_json2_contractc = json_decode($_json_contractc,true);
        $data['trade_cntt'] = $_json2_contractc["result"]["data"];
        $text = '';
        for ($i=0; $i < count($data['trade_cntt']); $i++) { 
            if($i == (count($data['trade_cntt'])-1))
            {
                $text .= '[
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$data['trade_cntt'][$i]['name1'].'",
                       "'.number_format((float)$data['trade_cntt'][$i]['commissionrate'],5,'.','').'",
                       "'.$data['trade_cntt'][$i]['remarks'].'"
                      ]';
            }
            else
            {
                $text .= '[
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$data['trade_cntt'][$i]['name1'].'",
                       "'.number_format((float)$data['trade_cntt'][$i]['commissionrate'],5,'.','').'",
                       "'.$data['trade_cntt'][$i]['remarks'].'"
                      ],
                      ';
            }
        }

        echo '{
              "data": 
                [
                    '.$text.'
                ]
            }';
	}
	public function getNotes($contractid)
	{
		$data_contractc = array(
            'method' => 'qry',
            'reportcode'=>'crmContract01h',
            'limit'=>25,
            'start'=>0,
            'queryFilters'=>array(
                'contractid'=> $contractid
            )
        );
        $result_contractc = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/dev/api/get_list_contract",$data_contractc);
        $_json_contractc = json_decode($result_contractc,true);
        $_json2_contractc = json_decode($_json_contractc,true);
        $data['trade_cntt'] = $_json2_contractc["result"]["data"];
        $text = '';
        for ($i=0; $i < count($data['trade_cntt']); $i++) { 
                if(strtotime($data['trade_cntt'][$i]['eventdate']) > $this->dayCompare)
                {
                    $eventdate = date("d/m/Y",strtotime($data['trade_cntt'][$i]['eventdate']));
                }else{$eventdate='';}
            if($i == (count($data['trade_cntt'])-1))
            {
                $text .= '[
                       "'.$data['trade_cntt'][$i]['eventtype'].'",
                       "'.$eventdate.'",
                       "'.$data['trade_cntt'][$i]['eventstatus'].'",
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$data['trade_cntt'][$i]['notes'].'"
                      ]';
            }
            else
            {
                $text .= '[
                       "'.$data['trade_cntt'][$i]['eventtype'].'",
                       "'.$eventdate.'",
                       "'.$data['trade_cntt'][$i]['eventstatus'].'",
                       "'.$data['trade_cntt'][$i]['name'].'",
                       "'.$data['trade_cntt'][$i]['notes'].'"
                      ],
                      ';
            }
        }

        echo '{
              "data": 
                [
                    '.$text.'
                ]
            }';
	}
}

/* End of file M_data_API.php */
/* Location: ./application/models/M_data_API.php */
?><file_sep><?php $type = $this->uri->segment(4); ?>
<div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5>Danh sách dữ liệu trường: <?php echo isset($detail[0]['fieldname'])?$detail[0]['fieldname']:'' ?></h5>
			        </div>
			    </div>
				    <div style="float: right;">
						<button <?php if($type == 'T'){echo 'hidden';} ?> type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal">Thêm</button>
					</div>
			    
				<div class="bs-component" style="margin-top: 55px">
					<?php if ($type == 'T'){
						echo '<div class="component-fields">
				                    <i class="fas fa-align-justify"></i> 
				                    <span class="title_tab" style="padding-left: 6px">Text</span>
							</div>';
					} ?>
					<?php if(count($list_ext)>0){
						foreach ($list_ext as $value) { ?>
							<div class="component-fields">
				                    <i class="fas fa-align-justify"></i> 
				                    <span class="title_tab" style="padding-left: 6px"><?php echo $value['name'] ?></span>
				                    <a class="user-name" style="cursor: pointer;float: right;" data-toggle="modal" data-target="#modalDelete" data-code="<?php echo $value['code'] ?>" data-category="<?php echo $value['category'] ?>"><i class="far fa-trash-alt"></i></a>
				                     <a class="user-name" style="cursor: pointer;float: right; margin-right: 15px"  data-toggle="modal" data-target="#modalUpdate" data-code="<?php echo $value['code'] ?>" data-category="<?php echo $value['category'] ?>" data-name="<?php echo $value['name'] ?>"><i class="fas fa-edit"></i></a>
							</div>
						<?php }}?>
	            </div>
          	</div>
 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document" style="margin-top: 5%">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Dropdown Options</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
	        	<div class="form-group optionbottom">
				    <label for="exampleInputEmail1">Mã trường</label>
				    <input type="text" class="form-control" name="code" id="code" placeholder="-Mã trường">
				</div>

				<div class="form-group extendbottom">
						    <label for="exampleInputEmail1">Tên trường</label>
						    <input type="text" class="form-control" name="name" id="name" placeholder="-Tên trường">
				</div>
				<input type="hidden" name="category" id="category" value="<?php echo $this->uri->segment(5) ?>">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="insertSelectBox()" class="btn btn-primary">Thêm</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 7%" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Xoá Option</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bạn có chắc muốn xoá không?</p>
        <input type="hidden" id="categorydelete" name="categorydelete">
        <input type="hidden" id="codedelete" name="codedelete">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="deleteButton()" class="btn btn-danger">Xoá</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 7%" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Sửa Option</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
      	<div class="form-group">
		    <label for="exampleInputEmail1">Tên SelectBox:</label>
		    <input type="text" class="form-control nameField" id="nameField" name="name" placeholder="Tên SelectBox">
		</div>
        <input type="hidden" id="category" name="category">
        <input type="hidden" class="code" id="code" name="code">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="updateButton()" class="btn btn-primary">Sửa</button>
      </div>
    </div>
  </div>
</div><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
      	<div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10">
      		<?php echo isset($top) ? $top : ''; ?>
      	</div>
        <div class="col-md-2 col-md-24 no-padding padding-left-15">
          	<?php echo isset($left) ? $left : ''; ?>
        </div>
        <div class="col-md-6 no-padding padding-left-5">
          	<?php echo isset($center) ? $center : ''; ?>
        </div>
        <div class="col-md-3 no-padding padding-left-5 padding-top-10 padding-right-10">
          <?php if($this->input->get('cusid') !=''){
            ?>
                <iframe class="iframehistory" id="iframehistory" style="width: 100%;height:1000px;display: block; border: none;"  src="<?php echo base_url() ?>user/viewUserHistory?cusid=<?php echo strval($this->input->get('cusid')) ?>"></iframe>
            <?php
          } ?>
        	<!-- <?php echo isset($right) ? $right : ''; ?> -->
        </div>
    </div>
</main><file_sep><div class="tile p-0 padding-5 margin-bot-5">
	          <div class="tile-body padding-left-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Tên trường</label>
	            		<?php if (count($detail)>0) {
	            			$fieldname = $detail[0]['fieldname'];
	            			$fieldcode = $detail[0]['fieldcode'];
	            			$status = $detail[0]['status'];
	            		}else{$fieldname='';
	            				$status ='';} ?>
	              		<label class="control-label col-md-7 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" value="<?php echo $fieldname ?>" placeholder="Nhập họ tên" id="fieldname" required="" minlength="4" maxlength="30">
		              		<input type="hidden" class="col-md-12 no-padding font-size-12" value="<?php echo $fieldcode ?>" placeholder="Nhập họ tên" id="fieldcode" required="" minlength="4" maxlength="30">
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Loại nhập liệu</label>
	            		<?php $type = $this->uri->segment(4);
	            				if($type == 'T'){
	            					$typeInput = 'Text';
	            				}
	            				else{ $typeInput = 'SelectBox';} ?>
	              		<label class="control-label col-md-7 no-padding-right">
		              		<input readonly class="col-md-12 no-padding font-size-12" value="<?php echo $typeInput ?>" placeholder="Nhập họ tên" id="type" required="" minlength="4" maxlength="30">
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-4 no-padding">Trạng thái</label>
	              		<label class="control-label col-md-7 no-padding-right">
		              		<select class="control-label col-md-12 no-border no-padding" id="status">
	              			<option <?php if ($status!='1'){echo 'selected';} ?> value="0">Không hoạt động</option>
	              			<option <?php if ($status=='1'){echo 'selected';} ?> value="1">Đang hoạt động</option>
	              		</select>
		              	</label>
	            	</div>
	            </div>
 </div>
	            	<div class="fc-corner-right">
		          		<div class="fc-button-group" style="float:right">
							<button type="submit" onclick="uddateFields()" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right btn-createuser">Lưu thông tin</button>
						</div>
		          	</div><file_sep><?php

// error_reporting(0);
// ini_set('display_errors', 0);
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {

	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model(array('M_api'));
    }

	public function index()
	{
		$_data = [];
		$body = [];    
		$list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/3');
        $body['listuser'] = json_decode($list_user,true)['data'];
        $list_agent = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/2');
        $body['listagent'] = json_decode($list_agent,true)['data'];
		$_data['script'] = $this->load->view('script/script_search', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('search/search', $body , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function rightSearch()
	{
		$get = $this->input->get();
		$query = '?';
		foreach ($get as $key => $value) {
			$value = str_replace('#', '', $value);
			$value = str_replace(' .', ' ', $value);
			$query.=$key.'='.urlencode(trim($value)).'&';
		}
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/search'.$query);
        
        $data['result'] = json_decode($json,true);
		$_data['script'] = $this->load->view('script/script_search', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('search/right_search', $data , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function rightSearchTicket()
	{	
		$agent = $_GET['agentcurrent'];
		$json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketinfo/'.$agent.'/700');
		$lienquan = $_GET['lienquan'];
		$data['lienquan'] = $lienquan;
		$data['agentcurrent'] = $agent;
        $data['result'] = json_decode($json,true);
        $data['status'] = $_GET['status'];
		$_data['script'] = $this->load->view('script/script_search', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('search/right_search_ticket', $data , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function ticketByType($type){
		$data = [];
		$json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/getticketbyagentgroup/'.$this->session->userdata('groupid').'/'.$type);
		$data['result'] = json_decode($json,true)['data'];
		$_data['script'] = $this->load->view('script/script_search', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('search/ticket_by_status', $data , TRUE);
		$this->load->view('dashboard',$_data);
	}

	public function rightSearchTicketInput()
	{
		$get = $this->input->get();
		$query = '?';
		foreach ($get as $key => $value) {
			$value = str_replace('#', '', $value);
			//$value = str_replace(' .', ' ', $value);
			//$value = preg_replace('/[^a-zA-Z0-9-_\.]/','', $value);
			$query.=$key.'='.rawurlencode(trim($value)).'&';
		}

		
		$json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/search'.$query);
		$var = $this->session->userdata;
        $custidLogin = $var['custid'];
		$data['agentcurrent'] = $custidLogin;
        $data['result'] = json_decode($json,true);
        if(isset($_GET['status'])){
        	$data['status'] = $_GET['status'];
        }else{
        	$data['status'] = -1;
        }
        
		$_data['script'] = $this->load->view('script/script_search', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('search/right_search_ticket_input', $data , TRUE);

		$this->load->view('dashboard',$_data);
		// echo ('http://test.tavicosoft.com/crm/index.php/ticket/search'.$query);
	}
}<file_sep><iframe src="<?php echo(base_url('ticket/test_left_detail'))?>"></iframe><file_sep><script type="text/javascript">
  $(function () {
    $('[data-toggle="tooltip"]').tooltip()
  })
  var dayCompare = new Date("2000-01-01T00:00:00");	
  $(document).ready( function () {

    loadFirst();
  $( "#idcard" ).click(function() {
      $('#updateIdcard').modal('show');
      $('#updateIdcard').on('shown.bs.modal', function (e) {
          /*
          $('#issueddate').datetimepicker({timepicker:false,
          format:'d/m/Y'});
          */
        })
  });
      });
    function insertTicket(custCustomer,custid,groupid)
    {
      $('#btn-plus-ticket').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
      var arrayext = [];
      $.ajax({
        url: "<?php echo base_url().'ticket/aj_insert_ticket';?>",
        dataType:'json',
        type : "POST",
        data:  {agentcurrent: custid,  customer: custCustomer, groupid: groupid, agentgroup: groupid}
        })
      .done(function(data){
        if(data.code==0){
               parent.alertLog("Cảnh báo !", data.message, "warning");
              $('#btn-plus-ticket').prop('disabled',false).find('i').removeClass();
              $('#btn-plus-ticket').prop('disabled',false).find('i').addClass('fas fa-plus');
            }else{
              $('#btn-plus-ticket').prop('disabled',false).find('i').removeClass();
              $('#btn-plus-ticket').prop('disabled',false).find('i').addClass('fas fa-plus');
               // alert("thêm thành công.");
               parent.alertLog("Thành công !", "Thêm phiếu thành công.", "success");
                // var tab = window.top.$('div.tab-pane.active').attr('id');
                // window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html('#'+data.data);
               // location.href= '<?php echo base_url().'/ticket/detail/';?>'+data.data;
               parent.addTab('<?php echo base_url().'/ticket/detail/';?>'+data.data,'#'+data.data);
            }
      })
      .fail(function(){
          console.log("Error");
      });
    }
    function loadFirst()
    {
      $('#roleid').val('<?php echo $detail[0]['roleid'] ?>');
      $('#gender').val('<?php echo $detail[0]['gender'] ?>');
      var load_roleid = $('#roleid').val();
      var idcard = '<?php echo $detail[0]['idcard'] ?>';
      var opid = $('#opid').val();
      loadGroup(load_roleid);
      $('input[name=city]').on('keyup',function(){
    var val = $(this).val();
    var opt = $('datalist#l_city').find('option[value="'+val+'"]');
    if (opt.length>0) {
      var idcity = opt.attr('id-city');
      $.ajax({
        url: '<?php echo base_url()?>user/selectCity',
        type: 'POST',
        dataType: 'JSON',
        data: {id_city : idcity},
      })
      .done(function(data) {
        var l_r = '';
        for (var i = 0; i < data.length; i++) {
          l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_district']+'"></option>';
        }
        $('datalist#l_distr').html(l_r);
      })
      .fail(function() {
        console.log("error");
      })
    }
  });

  $('input[name=district').on('keyup',function(){
    var val = $(this).val();
    var opt = $('datalist#l_distr').find('option[value="'+val+'"]');
    if (opt.length>0) {
      var id = opt.attr('id');
      $.ajax({
        url: '<?php echo base_url()?>user/selectDistrict',
        type: 'POST',
        dataType: 'JSON',
        data: {id_district : id},
      })
      .done(function(data) {
        var l_r = '';
        for (var i = 0; i < data.length; i++) {
          l_r+='<option value="'+data[i]['name']+'" id="'+data[i]['id_ward']+'"></option>';
        }
        $('datalist#l_ward').html(l_r);
      })
      .fail(function() {
        console.log("error");
      })
    }
  });
    var table_contract = $('#table-1-contract').DataTable({
                    "paging":   false,
                    "info":     false,
                    "searching": false,
                    "scrollY":        "235px",
                    "scrollX":        true,
                    "scrollCollapse": true,
                    "ajax": '<?php echo base_url() ?>user/testContract?idcard='+idcard+'&opid='+opid+'',
                    dom: "Bfrtip",
                    "processing": true,
                    'language':{ 
                       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />",
                       "processing": ""
                    },
                    "initComplete": function(settings, json){ 
                        var info = this.api().page.info();
                        console.log('Total records', info.recordsTotal);
                        console.log('Displayed records', info.recordsDisplay);
                        $("#tab1").text('Giao dịch ('+info.recordsDisplay+')');
                        this.fnAdjustColumnSizing(true);
                    }
                  });
    $('.btn-update-idcard').click(function(){
      $('.btn-update-idcard').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
        var custid = '<?php echo strval($_GET['cusid']) ?>';
        var roleid = $('#roleid').val();
        var groupid = $('#groupid').val();
        var idcard = $('#idcard_modal').val();
        var issueddate = $('#issueddate').val();
        var issuedplace = $('#issuedplace').val();
        $.ajax({
        url: '<?php echo base_url()?>user/updateUser',
        type: 'POST',
        dataType: 'JSON',
        data: {roleid : roleid, groupid: groupid,custid:custid,idcard: idcard, issueddate: issueddate, issuedplace: issuedplace, ext:$('#dataExt').serialize()},
      })
        .done(function(data){
          $('.btn-update-idcard').prop('disabled',false).find('i').removeClass();
          $('#updateIdcard').modal('toggle');
          parent.notification("Lưu CMND thành công!!!");
          $('#idcard').val($('#idcard_modal').val());
          $('#idcard').attr('value', $('#idcard_modal').val());
            var iframe = document.getElementById('iframehistory');
            iframe.src = iframe.src;
        })
        .fail(function(){
            parent.notification("Lưu CMND thất bại!!!");
        })
    });
    $('.btn-update').click(function(){
      $('#updateUser').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
        var custid = '<?php echo strval($_GET['cusid']) ?>';
        var roleid = $('#roleid').val();
        var groupid = $('#groupid').val();
        var custname = $('#custname').val();
        // var idcard = $('#idcard').val();
        var fullbirthday = $('#fullbirthday').val();
        var gender = $('#gender').val();
        var telephone = $('#telephone').val();
        var email = $('#email').val();
        var country = $('#country').val();
        var city = $('#city').val();
        var district = $('#district').val();
        var ward = $('#ward').val();
        var text = '';
        var address = $('#address').val();
        var comments = $('#comments').val();
        var thunhap = $('#thunhap').val();
        var fulladdress = $('#fulladdress').val();
        // var custid = $('#custid').val();
        var password = $('#password').val();
        var queue = $('#queue').val();
        var queueold = $('#queue_old').val();
        $.ajax({
        url: '<?php echo base_url()?>user/updateUser',
        type: 'POST',
        dataType: 'JSON',
        data: {roleid : roleid, groupid: groupid, custname:custname,idcard:idcard,fullbirthday:fullbirthday,telephone:telephone,email:email,country:country,city:city,district:district,ward:ward,address:address,comments:comments,thunhap:thunhap,gender:gender,fulladdress: fulladdress,custid:custid,password:<PASSWORD>,queue:queue,queueold:queueold, ext:$('#dataExt').serialize()},
      })
      .done(function(data) {
          $('#updateUser').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
             if(data.message =='Success')
             {
                  // location.reload();
                    parent.notification("Cập nhật thành công");
                    //update
                  // loadHistory();
                  var iframe = document.getElementById('iframehistory');
                  iframe.src = iframe.src;
             }
             else{
                parent.alertLog("Cảnh báo !", data.message, "warning");
                //parent.notification(data.message);
             }
          })
      .fail(function() {
          $('#updateUser').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
          parent.notification("Sửa thông tin thất bại");
      })
    });
    $('#insertUserVal').submit(function(e){
        e.preventDefault();
        
    });
            $('#fullbirthday').datetimepicker({timepicker:false,
          format:'d/m/Y'});
            
            $('#issueddate').datetimepicker({timepicker:false,
          format:'d/m/Y'});
          
          
           $("a[data-toggle=\"tab\"]").on("shown.bs.tab", function (e) {
              $($.fn.dataTable.tables( true ) ).css('width', '100%');
              $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
          });
    }
    function keyUpAddress(obj)
    {
      text = obj.value;
      fulladdress = text;
      $('#fulladdresstemp').val(fulladdress);
    }
      function selectCity(obj){
    var $id = obj.value;
    city = obj.options[obj.selectedIndex].text;
    fulladdress = text+ ' '+ 'Thành phố '+city; 
    $('#fulladdresstemp').val(fulladdress);
    // alert(fulladdress);
      $('.gicungdc').remove(); 
    $.ajax({
      url: '<?php echo base_url()?>user/selectCity',
      type: 'POST',
      dataType: 'JSON',
      data: {id_city : $id},
    })
    .done(function(data) {
               for (var i = 0; i < data.length; i++) {
                $('#dodulieu').after('<option title="'+data[i]['name']+'" class="gicungdc" value="'+data[i]['id_district']+'">'+data[i]['name']+'</option>');
               }
                  
            })
    .fail(function() {
      console.log("error");
    })
  }

  function selectDistrict(obj){
      var $id = obj.value;
      district = obj.options[obj.selectedIndex].text;
      fulladdress =text+ ' '+ district+' '+city;
    $('#fulladdresstemp').val(fulladdress);
      // alert(fulladdress);
        $('.gicungdc1').remove(); 
      $.ajax({
        url: '<?php echo base_url()?>user/selectDistrict',
        type: 'POST',
        dataType: 'JSON',
        data: {id_district : $id},
      })
      .done(function(data) {
                 for (var i = 0; i < data.length; i++) {
                  $('#dodulieu1').after('<option title="'+data[i]['name']+'" class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>');
                 }
                    
              })
      .fail(function() {
        console.log("error");
      })
    }

    function selectWard(obj){
      var $id = obj.value;
      ward = obj.options[obj.selectedIndex].text;
      fulladdress =text+ ' '+ ward+' '+district+' '+city;
      $('#fulladdresstemp').val(fulladdress);
    }

    function updateUser(obj)
    {
      var id = obj.title;
      var data = $('#'+id+'').val();
      $.ajax({
        url: '<?php echo base_url()?>user/selectDistrict',
        type: 'POST',
        dataType: 'JSON',
        data: {id_district : $id},
      })
      .done(function(data) {
                 for (var i = 0; i < data.length; i++) {
                  $('#dodulieu1').after('<option title="'+data[i]['name']+'" selected class="gicungdc1" value="'+data[i]['id_ward']+'">'+data[i]['name']+'</option>');
                 }
                    
              })
      .fail(function() {
        console.log("error");
      })

    }
   
   function selectGroup(obj){
      var $id = obj.value;
      $('.div-add').remove();
      $('.group_item').remove(); 
      $.ajax({
        url: '<?php echo base_url()?>user/getGroupByRoleId',
        type: 'POST',
        dataType: 'JSON',
        data: {roleid : $id},
      })
      .done(function(data) {
                 data =data.data;
                 if(data[0]['roleid'] == 3)
                 {
                   for (var i = 0; i < data.length; i++) {
                    console.log(data[0]['roleid']);

                      $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>');
                   }
                 }
                 else{
                    for (var i = 0; i < data.length; i++) {
                    console.log(data[0]['roleid']);

                      $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>');
                   }
                   $('.div-group').after('<div class="div-add">\
                  <label class="control-label user-label col-md-3 no-padding">ID:</label>\
                    <label class="control-label col-md-8 no-padding-right">\
                      <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập ID" id="custid" name="custid">\
                    </label>\
                </div>\
                <div class="div-add">\
                  <label class="control-label user-label col-md-3 no-padding">Password:</label>\
                    <label class="control-label col-md-8 no-padding-right">\
                      <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập Password" type="password" id="password" name="password">\
                    </label>\
                </div>\
                ')
                 }
                      
              })
      .fail(function() {
          console.log("error");
      })
    }

    function loadGroup(roleid)
    {
      var $id = roleid;
      $('.div-add').remove();
      $('.group_item').remove(); 
      $.ajax({
        url: '<?php echo base_url()?>user/getGroupByRoleId',
        type: 'POST',
        dataType: 'JSON',
        data: {roleid : $id},
      })
      .done(function(data) {

                 data =data.data;
                 if(data[0]['roleid'] == 3)
                 {
                   for (var i = 0; i < data.length; i++) {
                    console.log(data[0]['roleid']);

                      $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>');
                   }
                 }
                 else{
                    for (var i = 0; i < data.length; i++) {

                      $('.grouplist').append('<option selected class="group_item" value="'+data[i]['groupid']+'">'+data[i]['groupname']+'</option>');
                   }
                   $('.div-group').after('<div class="div-add">\
                  <label class="control-label user-label col-md-3 no-padding">ID:</label>\
                    <label class="control-label col-md-8 no-padding-right">\
                      <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập ID" id="custid" name="custid">\
                    </label>\
                </div>\
                <div class="div-add">\
                  <label class="control-label user-label col-md-3 no-padding">Password:</label>\
                    <label class="control-label col-md-8 no-padding-right">\
                      <input class="col-md-12 no-padding font-size-12" value="" placeholder="Nhập Password" type="<PASSWORD>" id="password" name="password">\
                    </label>\
                </div>\
                ')
                 }
                  
                  $('#groupid').val('<?php echo $detail[0]['groupid'] ?>');    
              })
      .fail(function() {
          console.log("error");
      })
    }

    function removeemail($email, $emaillist,roleid,groupid){
        var custid = $('#cusit_id').attr('custid');
        $.ajax({
          url: '<?php echo base_url()?>user/updateUserEmailList',
          type: 'POST',
          dataType: 'JSON',
          data: {custid : custid,email:$email,emaillist:$emaillist,ext:$('#dataExt').serialize(),roleid:roleid,groupid:groupid},
        })
        .done(function(data) {
          if(data.code==1){
              window.location.reload();
            }else{
              parent.alertLog("Cảnh báo !", data.message, "warning");
            }
        })
        .fail(function() {
            parent.alertLog("Cảnh báo !", "Xóa Email Thất Bại", "warning");
        })
    }

    function removephone($phone, $phonelist,roleid,groupid){
        var custid = $('#cusit_id').attr('custid');
        $.ajax({
          url: '<?php echo base_url()?>user/updateUserPhoneList',
          type: 'POST',
          dataType: 'JSON',
          data: {custid : custid,phone:$phone,phonelist:$phonelist,ext:$('#dataExt').serialize(),roleid:roleid,groupid:groupid},
        })
        .done(function(data) {
            if(data.code==1){
              window.location.reload();
            }else{
              parent.alertLog("Cảnh báo !", data.message, "warning");
            }
        })
        .fail(function() {
            parent.alertLog("Cảnh báo !", "Lỗi hệ thống, vui lòng liên hệ admin : PHONE", "warning");
        })
    }

    $('.btn-addfulladdress').click(function(){
      $('.btn-addfulladdress').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
        var custid = '<?php echo strval($_GET['cusid']) ?>';
        var roleid = '<?php echo strval($_GET['roleid']) ?>';
        var groupid = $('#log_groupid').val();
        var addid = $(this).attr('addid');
        var country = $('#country').val();
        var city = $('#city').val();
        var district = $('#district').val();
        var ward = $('#ward').val();
        var street = $('#street').val();
        var address = $('#address').val();
        var label = $('#label').val();
        $.ajax({
          url: '<?php echo base_url()?>user/aj_insert_bonus_address',
          type: 'POST',
          dataType: 'JSON',
          data: {custid: custid, city:city,district:district,ward:ward,street:street,address: address,label:label,roleid:roleid,groupid:groupid},
        })
        .done(function(data) {
          if(data.code==1){
              $.ajax({
                url: '<?php echo base_url()?>user/getAddressApi',
                type: 'POST',
                dataType: 'JSON',
                data: {custid: custid},
              })
              .done(function(data){
                $('.btn-addfulladdress').prop('disabled',false).find('i').removeClass();
                parent.notification("Thêm địa chỉ thành công!!!");
                $('#updateAddress').modal('toggle');
                var data_html = '';
                var j  = 0;
                for (var i = 0; i < data.data.length; i++) {
                    
                    if(data.data[i].hidden != 1)
                    {
                      if(j==0)
                      {
                      var label_diachi = "Địa chỉ";
                      }else{
                      var label_diachi = '';}
                    var label = "'"+data.data[i].label+"'";
                    var city = "'"+data.data[i].city+"'";
                    var district = "'"+data.data[i].district+"'";
                    var ward = "'"+data.data[i].ward+"'";
                    var street = "'"+data.data[i].street+"'";
                    var address = "'"+data.data[i].address+"'";
                    var addressid = "'"+data.data[i].addressid+"'";
                    data_html +='<label class="control-label user-label col-md-3 no-padding">'+label_diachi+'</label>\
                      <label class="control-label col-md-7 no-padding-right">\
                        <input onclick="openModalEdit(\
                        '+label+',\
                        '+city+',\
                        '+district+',\
                        '+ward+',\
                        '+street+',\
                        '+address+',\
                        '+addressid+'\
                        )" class="col-md-12 no-padding font-size-12" value="'+data.data[i].label+'">\
                      </label>\
                      <a href="#" onclick="removeAddress('+addressid+')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>\
                      ';
                      j++;
                    }
                }
                $('.div-address').html(data_html);
                $('#country').val("");
                $('#city').val("");
                $('#district').val("");
                $('#ward').val("");
                $('#street').val("");
                $('#address').val("");
                $('#label').val("");
                var iframe = document.getElementById('iframehistory');
                iframe.src = iframe.src;

              }).fail(function(){
                  parent.alertLog("Cảnh báo !", "Lỗi hệ thống, vui lòng liên hệ admin", "warning");
              })
            }else{
              parent.alertLog("Cảnh báo !", data.message, "warning");
            }
        })
        .fail(function() {
            parent.alertLog("Cảnh báo !", "Lỗi hệ thống, vui lòng liên hệ admin", "warning");
        })
    });
    $('.btn-updatefulladdress').click(function(){
      $('.btn-updatefulladdress').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
        var custid = '<?php echo strval($_GET['cusid']) ?>';
        var addressid = $('#addressid').val();
        var roleid = '<?php echo strval($_GET['roleid']) ?>';
        var groupid = $('#log_groupid').val();
        // var country = $('#country_edit').val();
        var city = $('#city_edit').val();
        var district = $('#district_edit').val();
        var ward = $('#ward_edit').val();
        var street = $('#street_edit').val();
        var address = $('#address_edit').val();
        var label = $('#label_edit').val();
        $.ajax({
          url: '<?php echo base_url()?>user/aj_update_bonus_address',
          type: 'POST',
          dataType: 'JSON',
          data: {city:city,district:district,ward:ward,street:street,address: address,label:label,addressid:addressid,roleid:roleid,groupid:groupid,custid:custid},
        })
        .done(function(data) {
          if(data.code==1){
              $.ajax({
                url: '<?php echo base_url()?>user/getAddressApi',
                type: 'POST',
                dataType: 'JSON',
                data: {custid: custid},
              })
              .done(function(data){
                $('.btn-updatefulladdress').prop('disabled',false).find('i').removeClass();
                parent.notification("Thêm địa chỉ thành công!!!");
                $('#updateFullAddress').modal('toggle');
                var data_html = '';
                var j  = 0;
                for (var i = 0; i < data.data.length; i++) {
                    
                    if(data.data[i].hidden != 1)
                    {
                      if(j==0)
                      {
                      var label_diachi = "Địa chỉ";
                      }else{
                      var label_diachi = '';}
                    var label = "'"+data.data[i].label+"'";
                    var city = "'"+data.data[i].city+"'";
                    var district = "'"+data.data[i].district+"'";
                    var ward = "'"+data.data[i].ward+"'";
                    var street = "'"+data.data[i].street+"'";
                    var address = "'"+data.data[i].address+"'";
                    var addressid = "'"+data.data[i].addressid+"'";
                    data_html +='<label class="control-label user-label col-md-3 no-padding">'+label_diachi+'</label>\
                      <label class="control-label col-md-7 no-padding-right">\
                        <input onclick="openModalEdit(\
                        '+label+',\
                        '+city+',\
                        '+district+',\
                        '+ward+',\
                        '+street+',\
                        '+address+',\
                        '+addressid+'\
                        )" class="col-md-12 no-padding font-size-12" value="'+data.data[i].label+'">\
                      </label>\
                      <a href="#" onclick="removeAddress('+addressid+')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>\
                      ';
                      j++;
                    }
                }
                $('.div-address').html(data_html);
                var iframe = document.getElementById('iframehistory');
                      iframe.src = iframe.src;
                // alert(data_html);

              }).fail(function(){
                  parent.alertLog("Cảnh báo !", "Lỗi hệ thống, vui lòng liên hệ admin", "warning");
              })
            }else{
              parent.alertLog("Cảnh báo !", data.message, "warning");
            }
        })
        .fail(function() {
          parent.alertLog("Cảnh báo !", "Lỗi hệ thống, vui lòng liên hệ admin", "warning");
        })
    });

    function openModalEdit(label,city,district,ward,street,address,addressid)
    {
        $('#updateFullAddress').modal('toggle');
        $('#updateFullAddress').on('shown.bs.modal', function (e) {
            $('#label_edit').val(label);
            $('#city_edit').val(city);
            $('#district_edit').val(district);
            $('#ward_edit').val(ward);
            $('#street_edit').val(street);
            $('#address_edit').val(address);
            $('#addressid').val(addressid);
        });
    }
    
  function formatDMY(dd,mm,yyyy)
  {
      if(dd<10){
      dd='0'+dd;
      } 
      if(mm<10){
          mm='0'+mm;
      } 
      var today = dd+'/'+mm+'/'+yyyy;
      return today;
  }
  function formatHMS(hh,mm,ss)
  {
      if(hh<10){
      hh='0'+hh;
      } 
      if(mm<10){
          mm='0'+mm;
      } 
      if(ss<10){
          ss='0'+ss;
      } 
      var today = hh+':'+mm+':'+ss;
      return today;
  }
  function removeAddress(addressid)
  {
      $('#modalDeleteAddress').modal('toggle');
      $('#modalDeleteAddress').on('shown.bs.modal', function (e) {
            $('#addressid_delete').val(addressid);
        });
  }
  function deleteAddress()
  {
    var custid = '<?php echo strval($_GET['cusid']) ?>';
    $('.btn-danger').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
    var addressid = $('#addressid_delete').val();
     $.ajax({
        url: '<?php echo base_url()?>user/aj_delete_address',
                type: 'POST',
                dataType: 'JSON',
                data: {addressid: addressid},
     })
     .done(function(data){
        if(data.code == 1)
        {
            $.ajax({
                url: '<?php echo base_url()?>user/getAddressApi',
                type: 'POST',
                dataType: 'JSON',
                data: {custid: custid},
              })
              .done(function(data){
                $('.btn-danger').prop('disabled',false).find('i').removeClass();
                var iframe = document.getElementById('iframehistory');
                iframe.src = iframe.src;
                parent.notification("Đã xoá địa chỉ!!!");
                $('#modalDeleteAddress').modal('toggle');
                
                var data_html = '';
                var j  = 0;
                for (var i = 0; i < data.data.length; i++) {
                    
                    if(data.data[i].hidden != 1)
                    {
                      if(j==0)
                      {
                      var label_diachi = "Địa chỉ";
                      }else{
                      var label_diachi = '';}
                    var label = "'"+data.data[i].label+"'";
                    var city = "'"+data.data[i].city+"'";
                    var district = "'"+data.data[i].district+"'";
                    var ward = "'"+data.data[i].ward+"'";
                    var street = "'"+data.data[i].street+"'";
                    var address = "'"+data.data[i].address+"'";
                    var addressid = "'"+data.data[i].addressid+"'";
                    data_html +='<label class="control-label user-label col-md-3 no-padding">'+label_diachi+'</label>\
                      <label class="control-label col-md-7 no-padding-right">\
                        <input onclick="openModalEdit(\
                        '+label+',\
                        '+city+',\
                        '+district+',\
                        '+ward+',\
                        '+street+',\
                        '+address+',\
                        '+addressid+'\
                        )" class="col-md-12 no-padding font-size-12" value="'+data.data[i].label+'">\
                      </label>\
                      <a href="#" onclick="removeAddress('+addressid+')"><i class="fas fa-times-circle fa-md float-right margin-top-3" style="margin-right: 2px"></i></a>\
                      ';
                      j++;
                    }
                }
                $('.div-address').html(data_html);
                
                // alert(data_html);

              }).fail(function(){
                  parent.notification("Xoá địa chỉ không thành công!!!");
              })
        }

     })
     .fail(function(){

     });
  }

  /*
  $('.btn-update-idcard').click(function(){
      $('.btn-update-idcard').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
        var custid = '<?php echo strval($_GET['cusid']) ?>';
        var roleid = $('#roleid').val();
        var groupid = $('#groupid').val();
        var idcard = $('#idcard_modal').val();
        var issueddate = $('#issueddate').val();
        var issuedplace = $('#issuedplace').val();
        $.ajax({
        url: '<?php echo base_url()?>user/updateUser',
        type: 'POST',
        dataType: 'JSON',
        data: {roleid : roleid, groupid: groupid,custid:custid,idcard: idcard, issueddate: issueddate, issuedplace: issuedplace, ext:$('#dataExt').serialize()},
      })
        .done(function(data){
          $('.btn-update-idcard').prop('disabled',false).find('i').removeClass();
          $('#updateIdcard').modal('toggle');
          parent.notification("Lưu CMND thành công!!!");
          $('#idcard').val(idcard);

        })
        .fail(function(){
          parent.notification("Lưu CMND thất bại!!!");
        })
    });
  */
  function addTelephone(id,idcard,roleid,groupid)
  { 
      $('.btn-add-phone').prop('disabled',true).find('i').addClass('fa fa-spin fa-spinner');
    var listtelephone = $('#listtelephone').val();
    var phone = $('#telephonelist').val();
    /*
    if(listtelephone.length == 0)
    {
      var listphone = telephonelist;
    }
    else{
      var listphone = listtelephone+','+telephonelist;
    }
    */
     $.ajax({
        url: '<?php echo base_url()?>user/insertPhoneList',
                type: 'POST',
                dataType: 'JSON',
                data: {phone:phone, telephonelist: listtelephone,custid:id,idcard:idcard,roleid:roleid,ext:$('#dataExt').serialize(),groupid:groupid},
     })
     .done(function(data){
        $('.btn-add-phone').prop('disabled',false).find('i').removeClass();
        if(data.code==1){
              window.location.reload();
            }else{
                parent.alertLog("Cảnh báo !", data.message, "warning");
            }
     })
     .fail(function(){
          $('.btn-add-phone').prop('disabled',false).find('i').removeClass();
          parent.alertLog("Cảnh báo !", "Thêm số điện thoại phụ thất bại", "warning");
     });
  }

  function addEmail(id,idcard,roleid,groupid)
  {
    var listemail = $('#listemail').val();
    var emaillist = $('#emaillist').val();
    var email = $('#emailadd').val();
    /*
    if(listemail.length == 0)
    {
      var listmail = emaillist;
    }
    else{
      var listmail = listemail+','+emaillist;
    }
    */
     $.ajax({
        url: '<?php echo base_url()?>user/insertEmailList',
                type: 'POST',
                dataType: 'JSON',
                data: {email: email,emaillist: listemail,custid:id,idcard:idcard,roleid:roleid,ext:$('#dataExt').serialize(),groupid:groupid},
     })
     .done(function(data){
        if(data.code==1){
            window.location.reload();
        }else{
            parent.alertLog("Cảnh báo !", data.message, "warning");
        }
     })
     .fail(function(){
          parent.alertLog("Cảnh báo !", "Thêm Email Thật Bại", "warning");
     });
  }


  //Tooltip

</script><file_sep><script type="text/javascript">
	$(document).ready(function(){
		loadFirst();
	});

  function loadFirst()
  {
    $('#table-1-searchticket').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
              }
            },
            "ordering": false,
            "info":     false,
            "searching": false,
            "scrollY":        "100%",
            // "scrollX":        true,
            "bLengthChange": false,
            "iDisplayLength": 25,
            "scrollCollapse": true
    }).columns.adjust().draw();
    $('#table-1-searchuser').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
              }
            },
             "columns":[
          { "width": "20%" },
          { "width": "20%" },
          { "width": "20%" },
          { "width": "20%" },
          { "width": "20%" }
        ],
        "ordering": false,
            "info":     false,
            "searching": false,
            "scrollY":        "100%",
            // "scrollX":        true,
            "bLengthChange": false,
            "iDisplayLength": 25,
            "scrollCollapse": true
          }).columns.adjust().draw();
    keyPress('search');
    keyPress('custname');
    keyPress('custid');
    keyPress('telephone');
    keyPress('email');
    keyPress('mapping1');

    keyPressTicket('searchticket');
    keyPressTicket('answerInput');
    keyPressTicket('agentInput');
    $('#search_customer').click(function(){
      searchCustomer();
    });

    $('#search_ticket').click(function(){
      searchTicket();
    });
  }
  function searchCustomer()
  {
    var search1 = $('#search').val();
    var search = encodeURI(search1);
    var custname = $('#custname').val();
    var custid = $('#custid').val();
    var telephone = $('#telephone').val();
    var email = $('#email').val();
    var mapping1 = $('#mapping1').val();

    document.getElementById('iframesearch').src = "<?php echo base_url().'search/rightSearch/?search=' ?>"+search+"&custname="+custname+"&idcard="+custid+"&telephone="+telephone+"&email="+email+"&mapping1="+mapping1+"&roleid=<?php echo($this->session->userdata('roleid'))?>";
  }
  function searchTicket()
  {
    var searchticket  = encodeURI($('#searchticket').val());
    
    if($('#answerInput').val().length > 5){
      var customer      = $('#customer').val();
    }else{
      var customer = '';
    }
    
    if($('#agentInput').val().length > 5){
      var agentcurrent  = $('#agentcurrent').val();
    }else{
      var agentcurrent = '';
    }
    var priority      = $('#priority').val();
    var status        = $('#status').val();
    var ticketchannel = $('#ticketchannel').val();
    document.getElementById('iframesearch').src = "<?php echo base_url().'search/rightSearchTicketInput/?search='?>"+searchticket+"&customer="+customer+"&agentcurrent="+agentcurrent+"&priority="+priority+"&status="+status+"&ticketchannel="+ticketchannel+"&custid=<?php echo($this->session->userdata('custid'))?>&groupid=<?php echo($this->session->userdata('groupid'))?>";
  }
  function keyPress(id)
  {
     $('#'+id+'').keypress(function(e1){
       if(e1.keyCode==13){          // if user is hitting enter
           searchCustomer();
       }
      });
  }

  function keyPressTicket(id)
  {
    $('#'+id+'').keypress(function(e1){
       if(e1.keyCode==13){          // if user is hitting enter
           searchTicket();
       }
      });
  }

  /*
  function deleteTextboxSearch()
  {
      $('#searchticket').val('');
      $('#search').val('');
      $('#search').removeAttr('minLength');
      $('#searchticket').removeAttr('maxLength');
      $('#search').removeAttr('minLength');
      $('#searchticket').removeAttr('maxLength');
  }

  function checkKeyPressTicket(id)
  {
    if($('#ticketchannel').val() != '' || $('#priority').val() != '' || $('#status').val() != '' || $('#answerInput').val() != "" || $('#agentInput').val() != "" )
    {
      $('#'+id+'').val("");
      $('#'+id+'').prop('minLength', 0);
      $('#'+id+'').prop('maxLength', 0);
      if($('#'+id+'').val() == "")
      {
        $('#'+id+'').prop('minLength', 0);
        $('#'+id+'').prop('maxLength', 0);
      }
    }
    else
    {
      $('#'+id+'').removeAttr('minLength');
      $('#'+id+'').removeAttr('maxLength');
    }
  }
  function checkKeyPressUser(id)
  {
    if($('#custname').val() != "" || $('#custid').val() != "" || $('#telephone').val() != "" || $('#email').val() != "" || $('#mapping1').val() != "" )
    {
      $('#'+id+'').val("");
      $('#'+id+'').prop('minLength', 0);
      $('#'+id+'').prop('maxLength', 0);
      if($('#'+id+'').val() == "")
      {
        $('#'+id+'').prop('minLength', 0);
        $('#'+id+'').prop('maxLength', 0);
      }
    }
    else
    {
      $('#'+id+'').removeAttr('minLength');
      $('#'+id+'').removeAttr('maxLength');
    }
  }
  */

</script><file_sep><script type="text/javascript">
  function updateGroup()
  {
    //  var groupid = $('#groupid').val();
               // var ticketrule = $('#ticketrule').val();
               // var taskrule = $('#taskrule').val();
               // var userrule = $('#userrule').val();
               // var knowledgerule = $('#knowledgerule').val();
              //  var status = $('#status').val();
              $('#btn-uploadgu').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
              getValueCheckbox("viewticket","viewtickethidden");
               getValueCheckbox("addticket","addtickethidden");
               getValueCheckbox("editticket","edittickethidden");

               getValueCheckbox("viewuser","viewuserhidden");
               getValueCheckbox("adduser","adduserhidden");
               getValueCheckbox("edituser","edituserhidden");

               getValueCheckbox("viewtask","viewtaskhidden");
               getValueCheckbox("addtask","addtaskhidden");
               getValueCheckbox("edittask","edittaskhidden");

               getValueCheckbox("viewknowledge","viewknowledgehidden");
               getValueCheckbox("addknowledge","addknowledgehidden");
               getValueCheckbox("editknowledge","editknowledgehidden");

               getValueCheckbox("viewpermission","viewpermissionhidden");
          $.ajax({
             url: '<?php echo base_url().'groupuser/updategroup' ?>',
             type: 'POST',
             dataType: 'JSON',
             // data: {groupid:groupid,ticketrule:ticketrule,taskrule:taskrule,userrule:userrule,knowledgerule:knowledgerule,status:status},
             data : $('#dataUpdateGroup').serialize(),
           })
           .done(function(data) {
               if(data.code==1){

                $('#btn-uploadgu').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
         }
    function getValueCheckbox(name,namehidden)
    {
      if(document.getElementById(name).checked) {
          document.getElementById(namehidden).disabled = true;
        }
    }
</script><file_sep><main class="app-content padding-5 no-padding-right">
    <!-- <div class="row">
        <div class="col-md-2 col-md-18 no-padding padding-left-10">
          	
        </div>
        <div class="col-md-7 col-md-64 no-padding padding-left-1">
          	<p> Bạn không có quyền truy cập chức năng này </p>
        </div>
        <div class="col-md-2 col-md-18 no-padding padding-left-5">
        	
        </div>
    </div> -->
    <div class="sweet-alert showSweetAlert visible" data-custom-class="" data-has-cancel-button="false" data-has-confirm-button="true" data-allow-outside-click="false" data-has-done-function="false" data-animation="pop" data-timer="null" style="display: block; margin-top: -156px;"><div class="sa-icon sa-error animateErrorIcon" style="display: block;">
      <span class="sa-x-mark animateXMark">
        <span class="sa-line sa-left"></span>
        <span class="sa-line sa-right"></span>
      </span>
    </div><div class="sa-icon sa-warning" style="display: none;">
      <span class="sa-body"></span>
      <span class="sa-dot"></span>
    </div><div class="sa-icon sa-info" style="display: none;"></div><div class="sa-icon sa-success" style="display: none;">
      <span class="sa-line sa-tip"></span>
      <span class="sa-line sa-long"></span>

      <div class="sa-placeholder"></div>
      <div class="sa-fix"></div>
    </div><div class="sa-icon sa-custom" style="display: none;"></div><h2>Lỗi !</h2>
    <?php if(isset($msg)){
      ?>
        <p style="display: block;"><?php echo $msg; ?></p>
      <?php
    }else{
      ?>
        <p style="display: block;">Bạn không có quyền truy cập vào chức năng này.</p>
      <?php
    }?>
    
    <fieldset>
      <input type="text" tabindex="3" placeholder="">
      <div class="sa-input-error"></div>
    </fieldset><div class="sa-error-container">
      <div class="icon">!</div>
      <p>Not valid!</p>
    </div><div class="sa-button-container">
      <button class="cancel" tabindex="2" style="display: none; box-shadow: none;">Cancel</button>
      <div class="sa-confirm-button-container">
          <div></div>
          <div></div>
          <div></div>
        </div>
      </div>
    </div></div>
</main><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
      	<div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10">
      		<?php echo isset($top) ? $top : ''; ?>
      	</div>
        
        <div class="col-md-24 no-padding padding-left-15">
          	<?php echo isset($left) ? $left : ''; ?>
        </div>
        <div class="col-md-2 col-md-22 no-padding padding-left-5 padding-top-10 padding-right-10">
        	<?php echo isset($right) ? $right : ''; ?>
        </div>
    </div>
</main><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Node extends CI_Controller {

	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
    }

	public function index()
	{
		$_data = [];    
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['nodejs'] = $this->load->view('node/dashboard', NULL, TRUE);
		$_data['mainview'] = $this->load->view('node/view', NULL , TRUE);
		$this->load->view('master',$_data);
	}

	public function detail(){
		$_body = [];
		$_body['top'] = $this->load->view('user/top/ud_breadcrumb', NULL, TRUE);
		$_body['left'] = $this->load->view('user/left/ud_info', NULL, TRUE); 
		$_body['right'] = $this->load->view('user/right/ud_history', NULL, TRUE);
		$_body['center'] = $this->load->view('user/center/ud_body', NULL, TRUE);

		$_data = [];    
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['script'] = $this->load->view('script/script', NULL, TRUE);
		$_data['nodejs'] = $this->load->view('node/node', NULL, TRUE);
		$_data['mainview'] = $this->load->view('user/user_detail', $_body , TRUE);
		$this->load->view('master',$_data);
	}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Call extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->library(array('session'));
        $this->load->helper(array('url'));
	}
	public function getSSLPage($url) {
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_HEADER, false);
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
	    $result = curl_exec($ch);
	    curl_close($ch);
	    return $result;
	}
	public function index()
	{

		$mitek_url = 'https://api-popupcontact-02.mitek.vn/api/v1/call';
		$secret = 'ac97db2cca493ad87045946aed59eb29';
		$extension = '7101';
		$phone = '0933961912';
		// $json = $this->getSSLPage($mitek_url.'/clicktocall?secret='.$secret.'&extension='.$extension.'&phone='.$phone.'');
		// $json= $this->getSSLPage('https://api-popupcontact-02.mitek.vn/api/v1/call/getstatusagent?secret=ac97db2cca493ad87045946aed59eb29&extension=2300&phone=2300');
		// $data['result'] = json_decode($json,TRUE);
		$data['result'] = $this->getSSLPage('https://api-popupcontact-02.mitek.vn/api/v1/call/clicktocall?secret=ac97db2cca493ad87045946aed59eb29&extension=2300&phone=2300');
		$_data['mainview'] = $this->load->view('call/call', $data , TRUE);
		$this->load->view('dashboard',$_data);;
	}
	
}

/* End of file Call.php */
/* Location: ./application/controllers/Call.php */ ?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Task extends CI_Controller {
    private $_init = [];
	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model(array('M_api'));

        //get list of ticket id
        $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/selectticket');
        $this->_init['l_ticket'] = json_decode($res,true)['data'];
        // get the type ticket
        $l_type = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/tasktype');
        $this->_init['l_type'] = json_decode($l_type,true)['data'];
        //Kiểm tra quyền với chức năng user
        $var = $this->session->userdata;
        $groupid = $var['groupid'];
        $group = $this->M_api->getlistgroup_array($groupid);
        $this->_init['isViewTask'] = substr($group['taskrule'], 0,1);
        $this->_init['isInertTask'] = substr($group['taskrule'], 1,1);
        $this->_init['isUpdateTask'] = substr($group['taskrule'], 2,1);
    }

	public function index()
	{
        if($this->_init['isViewTask']==0){
            $_data['mainview'] = $this->load->view('404',null , TRUE);
            $this->load->view('dashboard',$_data);
            return;
        }
		$data = [];
		$res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/gettask?pic='.$this->session->userdata('custid').'&tic='.$this->session->userdata('groupid'));
        $data['record'] = json_decode($res,true)['data'];

		$_data = [];
		$_data['script']  = $this->load->view('task/s_task', null, TRUE);
		$_data['mainview'] = $this->load->view('task/task', $data , TRUE);

		$this->load->view('dashboard',$_data);
	}

	public function create()
	{
		$data = [];
        $data['l_ticket']       = $this->_init['l_ticket'];
        $data['l_type']         = $this->_init['l_type'];

        $l_detail = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/taskdetail');
        $data['l_detail'] = json_decode($l_detail,true)['data'];

		$list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/3');
        $data['l_cus'] = json_decode($list_user,true)['data'];

        $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/2');
        $data['l_age'] = json_decode($list_user,true)['data'];

        //group agent
        $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group');
        $data['l_agentgroup'] = json_decode($_jsongroup,true)['data'];

		$_data = [];
		$_data['script']    = $this->load->view('task/s_insert', null, TRUE);
		$_data['mainview']  = $this->load->view('task/new', $data , TRUE);

		$this->load->view('dashboard',$_data);
	}

	public function detail($taskid)
	{
        if($this->_init['isViewTask']==0){
            $_data['mainview'] = $this->load->view('404',null , TRUE);
            $this->load->view('dashboard',$_data);
            return;
        }
		$data = [];
        $data['l_ticket']       = $this->_init['l_ticket'];
        $data['l_type']         = $this->_init['l_type'];
        
        //group agent
        $_jsongroup = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group');
        $data['l_agentgroup'] = json_decode($_jsongroup,true)['data'];

        $l_detail = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/select/taskdetail');
        $data['l_detail'] = json_decode($l_detail,true)['data'];

		$list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/3');
        $data['l_cus'] = json_decode($list_user,true)['data'];

        $list_user = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/getbyroleid/2');
        $data['l_age'] = json_decode($list_user,true)['data'];

		$res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/select/'.$taskid);
        $data['record'] = json_decode($res,true)['data'];
        $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/taskdetail/select/'.$taskid);
        $data['comment'] = json_decode($res,true)['data'];
        // var_dump($data);

		$_data = [];
		$_data['script']    = $this->load->view('task/s_update', null, TRUE);
		$_data['mainview'] = $this->load->view('task/detail', $data , TRUE);

		$this->load->view('dashboard',$_data);
	}

    public function de_tail($recordid)
    {
        $data = [];
        $data['l_ticket']       = $this->_init['l_ticket'];
        $data['l_type']         = $this->_init['l_type'];
        
        $list_user = json_decode($this->M_api->getlistcustomer(0),true);
        $data['l_cus'] = $list_user['data'];
        $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/gettask?recordid='.$recordid);
        $data['record'] = json_decode($res,true)['data'];
        $res = file_get_contents('http://test.tavicosoft.com/crm/index.php/taskdetail/select/'.$data['record'][0]['taskid']);
        $data['comment'] = json_decode($res,true)['data'];
        // var_dump($data);

        $_data = [];
        $_data['script']    = $this->load->view('task/s_update', null, TRUE);
        $_data['mainview'] = $this->load->view('task/detail', $data , TRUE);

        $this->load->view('dashboard',$_data);
    }

	public function ticket()
	{
		$_data = [];
		$_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
		$_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE);  
		$_data['mainview'] = $this->load->view('task/ticket', NULL , TRUE);

		$this->load->view('master',$_data);
	}




	public function aj_api_insert(){
		$post = $this->input->post();
		//var_dump($post);

        $var            = $this->session->userdata;
        $log_groupid = $var['groupid'];
        $req_data         = [];

        $taskid = $req_data['taskid'] = $this->M_api->gen_taskid();
        //Dnah cho phân quyền
        $req_data['log_groupid']           = $log_groupid;

        $req_data['status']     	  = isset($post['status'])?$post['status']:'O';
        $req_data['taskmaster']       = isset($post['taskmaster'])?$post['taskmaster']:'';
        $req_data['pic']       		  = isset($post['pic'])?$post['pic']:'';
        $req_data['tic']              = isset($post['tic'])?$post['tic']:'';
        $req_data['ticketid']     	  = isset($post['ticketid'])?$post['ticketid']:'';
        $req_data['tasktype']     	  = isset($post['tasktype'])?$post['tasktype']:'';
        $req_data['requestdate']      = isset($post['req_date'])?date('Y-m-d H:i:s',strtotime($post['req_date'])):'';
        $req_data['sla']    		  = isset($post['ola_date'])?date('Y-m-d H:i:s',strtotime($post['ola_date'])):'';
        $req_data['duedate']          = isset($post['due_date'])?date('Y-m-d H:i:s',strtotime($post['due_date'])):'';
        $req_data['priority']         = isset($post['priority'])?$post['priority']:'';
        $req_data['severity']         = isset($post['severity'])?$post['severity']:'';
        $req_data['finishdate']       = isset($post['fns_date'])?date('Y-m-d H:i:s',strtotime($post['fns_date'])):'';
        $req_data['title']            = isset($post['title'])?$post['title']:'';
        $req_data['createdby']        = isset($var['custid'])?$var['custid']:'';
        $req_data['statusnote']       = isset($post['statusnote'])?$post['statusnote']:'';
        $req_data['taskdetail']       = isset($post['taskdetail'])?$post['taskdetail']:'';

        // var_dump($req_data);
        $postdata   = http_build_query($req_data);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/insert',false,$context);

        $_res = json_decode($result,true);
        if (isset($_res['code']) && $_res['code'] == 1 && isset($post['cmt']) && $post['cmt'] !='') {
        	$log['taskid']     		= $taskid;
        	$log['tvcdb']     		= "AGT";
        	$log['tskaction']  		= "";
        	$log['comments']   		= $post['cmt'];
            $log['avatar']          = isset($post['avatar'])?$post['avatar']:'';
        	$log['changelog']  		= '';
        	$log['createdby']  		= isset($var['custid'])?$var['custid']:'';
        	$_result 				= $this->task_log($log);
        }
        echo $result;
	}

	public function aj_api_update(){
		$post = $this->input->post();
        $var            = $this->session->userdata;
        $log_groupid = $var['groupid'];
        $req_data         = [];
        $taskid     	  			  = isset($post['taskid'])?$post['taskid']:'';
        //Dnah cho phân quyền
        $req_data['log_groupid']           = $log_groupid;

        $req_data['status']     	  = isset($post['status'])?$post['status']:'O';
        $req_data['taskmaster']       = isset($post['taskmaster'])?$post['taskmaster']:'';
        $req_data['pic']              = isset($post['pic'])?$post['pic']:'';
        $req_data['tic']              = isset($post['tic'])?$post['tic']:'';
        $req_data['ticketid']     	  = isset($post['ticketid'])?$post['ticketid']:'';
        $req_data['tasktype']         = isset($post['tasktype'])?$post['tasktype']:'';
        $req_data['requestdate']      = isset($post['req_date'])?date('Y-m-d H:i:s',strtotime($post['req_date'])):'';
        $req_data['sla']    		  = isset($post['ola_date'])?date('Y-m-d H:i:s',strtotime($post['ola_date'])):'';
        $req_data['duedate']          = isset($post['due_date'])?date('Y-m-d H:i:s',strtotime($post['due_date'])):'';
        $req_data['priority']         = isset($post['priority'])?$post['priority']:'';
        $req_data['severity']         = isset($post['severity'])?$post['severity']:'';
        $req_data['finishdate']       = isset($post['fns_date'])?date('Y-m-d H:i:s',strtotime($post['fns_date'])):'';
        $req_data['title']            = isset($post['title'])?$post['title']:'';
        $req_data['statusnote']       = isset($post['statusnote'])?$post['statusnote']:'';
        $req_data['taskdetail']       = isset($post['taskdetail'])?$post['taskdetail']:'';
        // $req_data['createdby']        = isset($var['custid'])?$var['custid']:'';

        // var_dump($req_data);
        if ($req_data['ticketid']=="") {
            $req_data['ticketid']="0";
        }
        // var_dump($req_data);
        $postdata   = http_build_query($req_data);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/update/'.$taskid,false,$context);

        $_res = json_decode($result,true);
        if (isset($_res['code']) && $_res['code'] == 1 && ( (isset($post['changelog'])&&$post['changelog']!='')||(isset($post['cmt'])&&$post['cmt']!='') ) ) {
        	$log['taskid']     		= $taskid;
        	$log['tskaction']  		= isset($post['action'])?$post['action']:"Cập nhật công việc";
        	$log['comments']   		= isset($post['cmt'])?$post['cmt']:'';
            if ($log['comments']!='') {
                $log['tskaction'] = '';
            }
            $log['avatar']          = isset($post['avatar'])?$post['avatar']:'';
        	$log['changelog']  		= isset($post['changelog'])?$post['changelog']:'';
        	$log['createdby']  		= isset($var['custid'])?$var['custid']:'';
        	$_result 				= $this->task_log($log);
        }

        echo $result;
	}

    public function get_to_my_task($taskid){

        $var            = $this->session->userdata;
        $log_groupid = $var['groupid'];
        $task            = [];
         //Danh cho phân quyền
        $task['log_groupid']           = $log_groupid;

        $task['pic']     = $this->session->userdata['custid'];
        $task['tic']     = $this->session->userdata['groupid'];
        $task['status']  = 'W';

        $postdata   = http_build_query($task);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/task/update/'.$taskid,false,$context);
        echo $result;

        $_res = json_decode($result,true);
        if (isset($_res['code']) && $_res['code'] == 1) {
            $log['taskid']          = $taskid;
            $log['tskaction']       = "Tiếp nhận công việc.";
            $log['comments']        = '';
            $log['avatar']          = $this->session->userdata('avatar');
            $log['changelog']       = 'Phụ trách: '.$this->session->userdata('custname').' | Trạng thái: Đang xử lý |';
            $log['createdby']       = $this->session->userdata('custid');;
            $_result                = $this->task_log($log);
            // echo $_result;
        }
    }

	private function task_log($log){
		$postdata   = http_build_query($log);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/taskdetail/insert',false,$context);
        return $result;
	}
}<file_sep><div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5>Nhóm Người dùng</h5>
			        </div>
			    </div>
			    <p class="margin-top-10 no-margin-bot">Nhóm người dùng giúp phân quyền về các chức năng trong hệ thống bao gồm quyền Xem hoặc Sửa, ngoài ra việc phân nhóm người dùng còn hỗ trợ cho các báo cáo về hiệu quả công việc theo nhóm. Việc phản hồi người dùng.</p>
			    <div class="row" style="margin-top: 50px;">
			    	<div class="col-md-5">
			    		<span><b>Nhóm người dùng hiện tại trong hệ thống</b></span>
			    	</div>
			    	<div class="col-md-7">
						    <div style="float: right;">
								<button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" onclick="addTab('<?php echo base_url()?>groupuser/viewInsertGroup','Thêm nhóm người dùng')">Thêm</button>
							</div>
			    	</div>
			    </div>
			    
				<div class="bs-component margin-top-10">
          			<div class="table-responsive">
		              	<table class="table" id="table-1">
		              		<thead class="no-border-top">
		              			<tr>
		              				<th><b>Nhóm</b></th>
		              				<th><b>Thành viên nhóm</b></th>
		              				<th><b>Quyền của nhóm</b></th>
		              				<th><b>Trạng thái</b></th>
		              			</tr>
		              		</thead>
			                <tbody>
			                	<?php
			                		foreach ($listgroup as $group) {
			                			?>
			                				<tr>
						                		<td><a style="cursor: pointer;" class="user-name" onclick="addTab('<?php echo base_url()?>groupuser/groupuserdetail?groupid=<?php echo $group['groupid']; ?>','<?php echo $group['groupname']; ?>')"><?php  echo $group['groupname'];?></a></td>
						                			<?php 
						                			$totalPeople = '0 Người';
						                			foreach ($countPeople as $count) {
						                				if($count['groupid'] == $group['groupid'])
						                				{
						                					$totalPeople = $count['total'].' Người';
						                					break;
						                				}
						                				else
						                				{
						                					$totalPeople = '0 Người';
						                				}
						                			} ?>
						                		<td id="countpeople">
						                			<?php echo $totalPeople ?>
						                		</td>
						                		<td>
						                			<!-- <?php if($group['ticketrule']==1){ echo 'Xem/Sửa yêu cầu phiếu<br>'; }?>
						                			<?php if($group['userrule']==1){ echo 'Xem/Sửa người dùng<br>'; }?>
						                			<?php if($group['taskrule']==1){ echo 'Xem/Sửa công việc<br>'; }?>
						                			<?php if($group['knowledgerule']==1){ echo 'Xem/Sửa thư viện kiến thức'; }?> -->
		<?php 
		if(strpos($group['ticketrule'],'1') !== false)
		{
		$ruleticket = changTitle(0,substr($group['ticketrule'], 0,1))." ".changTitle(1,substr($group['ticketrule'], 1,1))." ".changTitle(2,substr($group['ticketrule'], 2,1))." Phiếu</br>";
		}else{$ruleticket = "";}
		if(strpos($group['userrule'],'1') !== false)
		{
		$ruleuser = changTitle(0,substr($group['userrule'], 0,1))." ".changTitle(1,substr($group['userrule'], 1,1))." ".changTitle(2,substr($group['userrule'], 2,1))." Người dùng</br>";
		}else{$ruleuser = "";}
		if(strpos($group['taskrule'],'1') !== false)
		{
		$ruletask = changTitle(0,substr($group['taskrule'], 0,1))." ".changTitle(1,substr($group['taskrule'], 1,1))." ".changTitle(2,substr($group['taskrule'], 2,1))." Công việc</br>";
		}else{$ruletask = "";}
		if(strpos($group['knowledgerule'],'1') !== false)
		{
		$ruleknowledge = changTitle(0,substr($group['knowledgerule'], 0,1))." ".changTitle(1,substr($group['knowledgerule'], 1,1))." ".changTitle(2,substr($group['knowledgerule'], 2,1))." Thư viện</br>";
		}else{$ruleknowledge = "";}
		echo $ruleticket.
			 $ruleuser.
			 $ruletask.
			 $ruleknowledge;
		?>
						                		</td>
						                		<td><?php if($group['status']==1){ echo 'Đang hoạt động'; }else{echo 'Không hoạt động';}?></td>
						                	</tr>
			                			<?php
			                		}
			                	?>
			                </tbody>
		              	</table>
		            </div>
	            </div>
          	</div>
<?php 
	function changTitle($position,$rule)
	{
		if($rule == 1 && $position == 0)
		{
			return "Xem";
		}
		else if($rule ==1 && $position == 1)
		{
			return "Thêm";
		}
		else if($rule ==1 && $position == 2)
		{ 
			return "Xoá";
		}
		else{
			return "";
		}
	}
?><file_sep>#!/bin/bash

/usr/bin/pm2 start ~/callevent/server.js
<file_sep><form id="form-ticket">
	<div class="tile p-0 padding-5 margin-bot-5 z-index-100">
        <div class="tile-body padding-left-right-10">
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Người yêu cầu(<span style="color: red;">*</span>)</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input disabled class="col-md-12 no-padding font-size-12" 
          			value="<?php echo $ticket['data'][0]['custname'];?>">
          		</label>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Người tạo(<span style="color: red;">*</span>)</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input disabled="" class="col-md-12 no-padding font-size-12" 
          			value="<?php echo $ticket['data'][0]['agentcreatedname'];?>">
          		</label>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Nhóm phụ trách(<span style="color: blue;">*</span>)</label>
          		<select name="agentgroup" data-placeholder="Chọn nhóm phụ trách..." log="Nhóm phụ trách" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control my-chosen" old-value="<?php echo($ticket['data'][0]['agentgroup'])?>">
          			<option value=""></option>
              		<?php if (isset($l_agentgroup) && !empty($l_agentgroup)) {
          				foreach ($l_agentgroup as $key => $value) {
          					$sel = '';
          					if ($value['groupid']==$ticket['data'][0]['agentgroup']) {
          						$sel = 'selected';
          					}
          					echo '<option '.$sel.' value="'.$value['groupid'].'">'.$value['groupname'].'</option>';
          				}
          			} ?>
          		</select>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Phụ trách(<span style="color: blue;">*</span>)</label>
          		<select data-placeholder="Chọn người phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen crm-control" name="agentcurrent" log="Phụ trách" old-value="<?php echo($ticket['data'][0]['agentcurrent'])?>">
          			<option value=""></option>
          			<?php if (isset($l_age)) {
                      	foreach ($l_age as $cus) {
                      		if ($cus['custname']!='') {
                      			$s='';
                      			if ($ticket['data'][0]['agentcurrent']==$cus['custid']) {
                      				$s='selected';
                      			}
                      		   echo('<option '.$s.' value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>');
                      		}
                      	}
                    } ?>
          		</select>
        	</div>
        </div>
  	</div>
  	<div class="tile p-0 padding-5 margin-bot-5">
        <div class="tile-body padding-left-right-10">
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Nguồn phiếu</label>
          		<select name="ticketchannel" log="Nguồn phiếu" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="ticketchannel" old-value="<?php echo($ticket['data'][0]['ticketchannel'])?>">
          			<option value="1" <?php if($ticket['data'][0]['ticketchannel']==1){echo "selected";} ?>>Trực tiếp</option>
          			<option value="2" <?php if($ticket['data'][0]['ticketchannel']==2){echo "selected";} ?>>Điện thoại</option>
          			<option value="3" <?php if($ticket['data'][0]['ticketchannel']==3){echo "selected";} ?>>Email</option>
          			<option value="4" <?php if($ticket['data'][0]['ticketchannel']==4){echo "selected";} ?>>Chat</option>
          		</select>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Mức Ưu tiên</label>
        		<select name="priority" log="Mức ưu tiên" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="priority" old-value="<?php echo($ticket['data'][0]['priority'])?>">
          			<option value="1" <?php if($ticket['data'][0]['priority']==1){echo "selected";} ?>>Thường</option>
          			<option value="2" <?php if($ticket['data'][0]['priority']==2){echo "selected";} ?>>Cao</option>
          			<option value="3" <?php if($ticket['data'][0]['priority']==3){echo "selected";} ?>>Khẩn cấp</option>
          		</select>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Tình trạng</label>
        		<select name="ticketstatus" log="Tình trạng" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="ticketstatus" old-value="<?php echo($ticket['data'][0]['status'])?>">
        			<option value="1" <?php if($ticket['data'][0]['status']==1){echo "selected";} ?>>Tạo mới</option>
        			<option value="0" <?php if($ticket['data'][0]['status']==0){echo "selected";} ?>>Đang xử lý</option>
          			<option value="4" <?php if($ticket['data'][0]['status']==4){echo "selected";} ?>>Hoàn thành</option>
          			<option value="9" <?php if($ticket['data'][0]['status']==9){echo "selected";} ?>>Hủy</option>
          		</select>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Giai đoạn</label>
      			<select name="levelticket" log="Giai đoạn" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="levelticket" old-value="<?php echo($ticket['data'][0]['levelticket'])?>">
          		<?php if (isset($l_stage) && !empty($l_stage)) {
      				foreach ($l_stage as $key => $value) {
      					$sel = '';
      					if (isset($ticket['data'][0]['levelticket']) && $value['code']==$ticket['data'][0]['levelticket']) {
      						$sel = 'selected';
      					}
      					echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>';
      				}
      			} ?>
          		</select>
        	</div>
        </div>
  	</div>
  	<div class="tile p-0 padding-5 margin-bot-5">
        <div class="tile-body padding-left-right-10">
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Phân loại</label>
      			<select name="tickettype" log="Phân loại" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_1" old-value="<?php echo($ticket['data'][0]['tickettype'])?>">
          			<?php if (isset($l_type) && !empty($l_type)) {
          				foreach ($l_type as $key => $value) {
          					$sel = '';
          					if (isset($ticket['data'][0]['tickettype']) && $value['code']==$ticket['data'][0]['tickettype']) {
          						$sel = 'selected';
          					}
          					echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>';
          				}
          			} ?>
          		</select>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Nhóm vấn đề</label>
        		<select name="groupid" log="Nhóm vấn đề" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" id="level_2" value="" old-value="<?php echo($ticket['data'][0]['groupid'])?>">
          			<?php if (isset($l_group) && !empty($l_group)) {
          				foreach ($l_group as $key => $value) {
          					$sel = '';
          					if (isset($ticket['data'][0]['groupid']) && $value['code']==$ticket['data'][0]['groupid']) {
          						$sel = 'selected';
          					}
          					echo '<option '.$sel.' ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
          				}
          			} ?>
          		</select>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Chi tiết VĐ</label>
      			<select name="categoryid" id="level_3" log="Chi tiết VĐ" class="control-label col-md-8 no-border no-padding margin-left-10 crm-control" old-value="<?php echo($ticket['data'][0]['categoryid'])?>">
          			<?php if (isset($l_cate) && !empty($l_cate)) {
          				foreach ($l_cate as $key => $value) {
          					$sel = '';
          					if (isset($ticket['data'][0]['categoryid']) && $value['code']==$ticket['data'][0]['categoryid']) {
          						$sel = 'selected';
          					}
          					echo '<option '.$sel.' ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
          				}
          			} ?>
          		</select>
        	</div>
        	<div class="break-line margin-bot-5"></div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Ngày yêu cầu</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input name="requestdate" log="Ngày yêu cầu" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['requestdate'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['requestdate'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['requestdate']));?>">
          		</label>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Ngày phản hồi</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input name="firstreply" log="Ngày phản hồi" id="lastupdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['firstreply'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['firstreply'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['firstreply']));?>">
          		</label>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Thời hạn SLA</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input name="sla" log="Thời hạn SLA" id="sla" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['sla'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['sla'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['sla']));?>">
          		</label>
        	</div>
        	<div class="break-line margin-bot-5"></div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Ngày hẹn</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input name="duedate" log="Ngày hẹn" id="duedate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['duedate'])?date("d-m-Y H:i", strtotime($ticket['data'][0]['duedate'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['duedate']));?>">
          		</label>
        	</div>
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Ngày hoàn thành</label>
          		<label class="control-label col-md-8 no-padding-right">
          		   <input name="finishdate" log="Ngày hoàn thành" id="finishdate" class="col-md-12 no-padding font-size-12 crm-control" placeholder="dd-mm-yyyy hh:ii" value="<?php echo isset($ticket['data'][0]['finishdate'])?date("d-m-Y H:i",strtotime($ticket['data'][0]['finishdate'])):'';?>" old-value="<?php echo date("d-m-Y H:i", strtotime($ticket['data'][0]['finishdate']));?>">
          		</label>
        	</div>
        </div>
  	</div>
  	<div class="tile p-0 padding-5 margin-bot-5">
        <div class="tile-body padding-left-right-10">
        	<div class="flex">
        		<label class="control-label user-label col-md-4 no-padding">Mã giao dịch</label>
          		<label class="control-label col-md-8 no-padding-right">
          			<input name="transref" log="Mã giao dịch" class="col-md-12 no-padding font-size-12 crm-control" placeholder="" value="<?php echo $ticket['data'][0]['transref'];?>">
          		</label>
        	</div>
        	<div class="break-line margin-bot-5"></div>
        	<?php 

        		if (isset($l_ext)) {
        			foreach ($l_ext as $key => $value) {
        				$f = isset($value['fieldcode'])?$value['fieldcode']:'';
        				$n = isset($value['fieldname'])?$value['fieldname']:'';
        				$v = isset($extinfo[$value['fieldcode']])?$extinfo[$value['fieldcode']]:'';
        				$d = '<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">'.$n.'</label>';
			            if (isset($value['fieldtype']) && $value['fieldtype']=='T') {
			            	$d.='
			            		<label class="control-label col-md-8 no-padding-right">
				              		<input class="col-md-12 no-padding font-size-12 crm-ext" log="'.$n.'" value="'.$v.'" old-value="'.$v.'" name="ext['.$f.']">
				              	</label>
			            	';
			            }elseif(isset($value['fieldtype']) && $value['fieldtype']=='D'){
			            	$d.='<select class="control-label col-md-8 no-border no-padding margin-left-10 crm-ext" log="'.$n.'" old-value="'.$v.'" name="ext['.$f.']">';
			            	if (isset($value['datasource']) && isset($l_dtsrc)) {
			            		foreach ($l_dtsrc as $ky => $vl) {
			            			if ($vl['category'] == $value['datasource']) {
			            				$sel = '';
		              					if ($v==$vl['code']) {
		              						$sel = 'selected';
		              					}
		              					$d.='<option '.$sel.' value="'.$vl['code'].'">'.$vl['name'].'</option>';
			            			}
			            		}
			            	}else{
			            		$d.='<option>(Dữ liệu bị lỗi)</option>';
			            	}
			            	$d.='</select>';
			            }else{
			            	$d.='<label>Đang cập nhật</label>';
			            }
			            $d.='</div>';
        				echo ($d);
        			}
        		}

        	?>
        </div>
  	</div>
    <div class="content-title user-history user-support" style="bottom:inherit">
    	<p>Hỗ trợ cho phiếu:</p>
    	<input type="hidden" name="ticketusers" value="<?php echo $ticketdetail['ticketusers'];?>"/>
    	<div class="div margin-left-10">
    		<?php if (isset($userssuppot))foreach ($userssuppot as $item_user) {?>
    			<a class="buttonsearchiframe" onclick="addTab('<?php echo base_url()."user/detail/?cusid=".$item_user['custid']."&idcard=".$item_user['idcard']."&roleid=".$item_user['roleid']?>','<?php echo $item_user['custname'] ?>')" href="#" title=""><img class="user-avatar" src="<?php echo $item_user['avatar']?>"  alt="User Image" title="<?php echo $item_user['custname'] ?>"></a>
    		<?php } ?>
        </div>
    </div>
    <!-- <button type="button" class="btn btn-gray margin-top-5 float-right" onclick="fillExtTicket()"> Ghi nhận
          </button> --><file_sep><script type="text/javascript">
$(document).ready(function(){
	$('a.dropdown-item:first').trigger('click');

	var h = $('table.dataTable').find('tfoot');
	var _a = h.attr('status-a'); $('label#_a').html(_a);
	var _o = h.attr('status-o'); $('label#_o').html(_o);
	var _w = h.attr('status-w'); $('label#_w').html(_w);
	var _c = h.attr('status-c'); $('label#_c').html(_c);
	var _ga = h.attr('status-ga'); $('label#_ga').html(_ga);
	var _go = h.attr('status-go'); $('label#_go').html(_go);
});
	var table = 
	$('#table-1').DataTable({
	    "paging":   true,
	    "language": {
	      "paginate": {
	        "previous": "Trước",
	        "next":"Sau"
	      }
	    },
	    "columnDefs": [
            {
                "targets": 5,
                "visible": true,
                "searchable": true
            },
            {
                "targets": 6,
                "visible": true,
                "searchable": true
            }
        ],
	    "ordering": false,
	    "info":     false,
	    "searching": true,
	    "search": {regex: true},
	    "scrollY":        "100%",
	    "bLengthChange": false,
	    "iDisplayLength": 25,
	    "scrollCollapse": true
	});

	$('a.dropdown-item').click(function(){
		var type = $(this).find('label').attr('id');
		var str = $(this).find('p').text();
		// console.log(str);
		$('#_type').html(str.replace(/[0-9]/g, ''));
		// $('#_all').html($(this).find('label').html()+" Công việc");
		table.columns().search("").draw();
		switch (type){
			case '_o':
				table.columns(4).search("Chờ xác nhận").columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw();
				break;
			case '_w':
				table.columns(4).search("Đang xử lý").columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw();
				break;
			case '_c':
				table.columns(4).search("Hoàn thành").columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw();
				break;
			case '_a':
				table.columns(6).search('<?php echo($this->session->userdata('custid'))?>').draw();
				break;
			case '_ga':
				table.columns(5).search('<?php echo($this->session->userdata('groupid'))?>').draw();
				break;
			case '_go':
				table.columns(5).search('<?php echo($this->session->userdata('groupid'))?>').columns(6).search('^$',true,false).draw();
				break;
			default: break;
		}
	});
</script><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-18 no-padding padding-left-10">
          	<?php echo isset($left)?$left:'' ?>
        </div>
        <div class="col-md-7 col-md-64 no-padding padding-left-1">
          	<?php echo isset($center)?$center:'' ?>
        </div>
        <div class="col-md-2 col-md-18 no-padding padding-left-5">
        	<?php echo isset($right)?$right:'' ?>
        </div>
    </div>
</main><file_sep><script type="text/javascript">
	function showNewTab(sdt) {
		var id = window.top.$(".nav-tabs").children().length;
		var ulChildren = window.top.$(".nav-tabs").children();  
		var link = '<?php echo base_url().'user/detail' ?>+sdt';
		var title = sdt;
		var checkLink = false;
		for(var i = 0; i < id ;i++)
	      {
	      	if(ulChildren[i].children[0].nodeName.toLowerCase() === 'a'){
                  if(title == ulChildren[i].children[0].title)
                  {
                    checkLink = true;
                    var j = i+1;
                     window.top.$('.nav-tabs li:nth-child(' + j + ') a').click();
                     break;
                  }
                }
	      }
	     if(checkLink == true)
                {
                    return;
                }
              else
                {
			        window.top.$( ".nav-link" ).removeClass( "active" );
			        window.top.$( ".tab-pane" ).removeClass( "active" );
			         //think about it ;)
			        window.top.$('.nav-menu li:last-child').after('<li class="nav-item ">\
			    <a class="nav-link active show" role="tab" data-toggle="tab" href="#tab'+id+'" title="'+title+'" >\
			      <i class="fas fa-user-circle"></i> \
			      <span class="title_tab">'+title+'</span> </a><span class="fa fa-times-circle" aria-hidden="true"></span>\
			  </li>');
			        window.top.$('.tab-content').append('<div class="tab-pane active" id="tab' + id + '"><iframe id="myiframe1" class="myiframe" name="myiframe'+id+'" src="'+link+'" frameborder="0"></iframe></div>');
			        var i = id+1;
			       window.top.$('.nav-tabs li:nth-child(' + i + ') a').click(); 
					// window.top.document.getElementById("myiframe1").src = $(this).attr('title');
				}
	}
</script><file_sep><script type="text/javascript">
  $(document).ready(function(){
    $('.div-recent-ticket,.div-contract').css('display','none');

    $('input[name=sla],input[name=duedate],input[name=finishdate],input[name=firstreply],input[name=requestdate]').
    datetimepicker({format:'d-m-Y H:i'});

    var tickettype = $('select[name=tickettype]').val();
  if (tickettype!='') {
    $('select[name=groupid] option').each(function(){
      var ref1 = $(this).attr('ref1');
      if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');}
      else{$(this).addClass('hide').removeClass('show');}
    });
  }

  var groupid = $('select[name=groupid]').val();
  if (groupid!='') {
    $('select[name=categoryid] option').each(function(){
      var ref2 = $(this).attr('ref2');
      if (ref2==groupid) {$(this).removeClass('hide').addClass('show');}
      else{$(this).addClass('hide').removeClass('show');}
    });
  }

    $('select#level_1').change(function(){
        var val = $(this).val();
        if(val){
          search('',val,'','');
          $('select#level_2 option, select#level_3 option').each(function(){
            var ref1 = $(this).attr('ref1');
            if (ref1==val) {
              $(this).removeClass('hide').addClass('show');
            }else{
              $(this).addClass('hide').removeClass('show');
            }
          });
        }else{
          $('select#level_2 option, select#level_3 option').each(function(){
            $(this).removeClass('hide').addClass('show');
          });
        }
        $('select#level_2 option.show:first').prop('selected',true);
        $('select#level_3 option.show:first').prop('selected',true);
    });
    $('select#level_2').change(function(){
        var val = $(this).val();
        if(val){
          search('','',val,'');
          $('select#level_3 option').each(function(){
            var ref2 = $(this).attr('ref2');
            if (ref2==val) {
              $(this).removeClass('hide').addClass('show');
            }else{
              $(this).addClass('hide').removeClass('show');
            }
          });
        }else{
          $('select#level_3 option').each(function(){
            $(this).removeClass('hide').addClass('show');
          });
        }
        $('select#level_3 option.show:first').prop('selected',true);
    });
    $('select#level_3').change(function(){
        var val = $(this).val();
        if (val) {search('','','',val);}
    });

    $('.my-chosen').chosen({
      width:'105%',
      disable_search_threshold: 9,
      no_results_text: "Không tìm thấy: ",
      allow_single_deselect: true
    });

    $('select[name=agentgroup]').change(function(){
      var val = $(this).val();
      if(val){
        $('select[name=agentcurrent] option').each(function(){
          var group = $(this).attr('data-group');
          if (val==group) {$(this).prop('disabled',false);}
          else{$(this).prop('disabled',true);}
        });
        $('select[name=agentcurrent] option:disabled(not):first').prop('selected',true);
      }else{
        $('select[name=agentcurrent] option').each(function(){
          $(this).prop('disabled',false);
        });
      }
      $('.my-chosen').trigger('chosen:updated');
    });
  });

  $('#form-ticket').on('submit',function(){
    var formData = new FormData($(this)[0]);
    var error = [];
    for (var [key, value] of formData.entries()) { 
      // console.log(key, value);
      switch(key){
        case 'customer':
          if (value=='') {
            error[key] = "1";
            parent.alertLog('Cảnh báo','Vui lòng chọn người yêu cầu.','warning');
          }
          break;
        case 'agentgroup':
          if (value=='' && formData.get('agentcurrent') == '') {
            error[key] = '1';
            parent.alertLog('Cảnh báo','Bạn phải nhập 1 trong 2 thông tin: Nhóm phụ trách, Người phụ trách.','warning');
          }else if (value=='' && formData.get('agentcurrent') !='') {
            var agent = $('select[name=agentcurrent]').find('option:selected').attr('data-group');
            console.log(agent);
            if (agent) {formData.set('agentgroup',agent)}
          }
          break;
        default: break;
      }
    }
    if (!jQuery.isEmptyObject(error)) {
      var msg = '';
      for (let key in error){
        msg+= error[key]+"\n";
      }
      console.log(msg);
    }else{
      $('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
      $.ajax({
          type: "POST",
          url: "<?php echo base_url().'ticket/aj_insert_ticket';?>",
          data:  formData,
          dataType:'json',
          contentType: false,
          cache: false,
          processData:false,
          beforeSend: function() {
          },
          success: function(data) {
            if(data.code==0){
               $('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
               parent.alertLog("Cảnh báo !", data.message, "warning");
            }else{
               // alert("thêm thành công.");
               parent.alertLog("Thành công !", "Thêm phiếu thành công.", "success");
                var tab = window.top.$('div.tab-pane.active').attr('id');
                window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html('#'+data.data);
               location.href= '<?php echo base_url().'/ticket/detail/';?>'+data.data;
            }
          },
          error: function(xhr, status, error) {
            console.log(error);
            $(this).prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
          }
      });
    }
    return false;
  });

  function showDetailKnowledge(id){
   var show = $('.knl-caret');
   if (show.hasClass('fa-angle-double-up')) {$('.knl-caret').trigger('click');}
   $('#knl_list').css('display','none');
   $('.knl-content').html("Đang tải dữ liệu...").css('display','block');
    $.ajax({
      url: '<?php echo base_url().'knowledge/detailKnowledge' ?>',
      type: 'POST',
      dataType: 'JSON',
      data: {id:id},
    })
    .done(function(data) {
        $('.knl-content').html(data.data[0].article).css('display','block');
        
      })
    .fail(function() {
       alert('Lỗi hệ thống, vui lòng liên hệ Admin');
    });
   }
</script><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 no-padding padding-left-15">
          	<div class="tile p-0 padding-5 margin-bot-5 height-1024">
	            <div class="tile-body padding-left-right-10">
	            	<ul class="nav nav-tabs no-margin-left">
		                <li class="nav-item">
		                	<a class="user-tab active show" data-toggle="tab" href="#tab-content-1">Người dùng</a>
		                </li>
		                <?php 
		                $var = $this->session->userdata;
		                if ($var['roleid'] != '1') { ?>
		                <li class="nav-item">
		                	<a class="user-tab" data-toggle="tab" href="#tab-content-2">Phiếu</a>
		                </li>
		            	<?php } ?>
	              	</ul>
	              	<div class="tab-content" id="myTabContent">
	              		<div id="tab-content-1" class="tab-pane fade active show">
	              			<div>
			              		<input onkeyup="checkKeyPressUser('search')" class="form-control margin-top-10 margin-bot-5" type="text" id="search" name="search" placeholder="Nhập thông tin người dùng để tìm kiếm">
			              		<p class="font-size-8 field-click-able">Tìm theo bộ lọc</p>
			              	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Tên</label>
			              		<label class="control-label col-md-8 no-padding-right">
			              			<input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="custname" placeholder="-">
			              		</label>
			            	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">CMND</label>
			              		<label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="custid" placeholder="-"></label>
			            	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Điện thoại</label>
			              		<label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="telephone" placeholder="-"></label>
			            	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Email</label>
			              		<label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="email" placeholder ="-"></label></label>
			            	</div>
			            	<div class="break-line margin-bot-5"></div>
			            	
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Mã căn hộ:</label>
			              		<label class="control-label col-md-8 no-padding-right"><input onkeypress="deleteTextboxSearch()" class="col-md-12 no-padding font-size-12" id="mapping1" placeholder ="-"></label></label>
			            	</div>
			            	<div class="offset-9 margin-top-10">
			            		<button id="search_customer" class="btn btn-primary float-right" type="button">Tìm kiếm</button>
			            	</div>
	              		</div>
		              	<div id="tab-content-2" class="tab-pane fade">
			              	<div>
			              		<input onkeyup="checkKeyPressTicket('searchticket')" class="form-control margin-top-10 margin-bot-5" type="text" name="searchticket" id="searchticket" placeholder="Nhập tiêu đề phiếu để tìm kiếm">
			              		<p class="font-size-8 field-click-able">Tìm theo bộ lọc</p>
			              	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Người yêu cầu</label>
			              		<label class="control-label col-md-8 no-padding-right">
			              			<input list="suggestionList" id="answerInput" placeholder="Người yêu cầu" class="col-md-12 no-padding font-size-12">
									<datalist id="suggestionList">
										<?php
				              				foreach ($listuser as $user) {
				              					?>
				              					<option data-value="<?php echo $user['custid']?>"><?php echo $user['custname']?></option>
				              					<?php
				              				}
				              			?>
									</datalist>
									<input type="hidden" id="customer">
									<script type="text/javascript">
										document.querySelector('#answerInput').addEventListener('input', function(e) {
										    var input = e.target,
										        list = input.getAttribute('list'),
										        options = document.querySelectorAll('#' + list + ' option'),
										        hiddenInput = document.getElementById('customer'),
										        inputValue = input.value;

										    hiddenInput.value = inputValue;
										    // $('#searchticket').val('');
      								// 		$('#search').val('');
										    for(var i = 0; i < options.length; i++) {
										        var option = options[i];

										        if(option.innerText === inputValue) {
										            hiddenInput.value = option.getAttribute('data-value');
										            break;
										        }else{
										        	hiddenInput.value="";
										        }
										    }
										});
									</script>
			              		</label>
			            	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Phụ trách</label>
			              		<label class="control-label col-md-8 no-padding-right">
			              			<input list="suggestionListAgent" id="agentInput" placeholder="Người phụ trách" class="col-md-12 no-padding font-size-12">
									<datalist id="suggestionListAgent">
										<?php
				              				foreach ($listagent as $user) {
				              					?>
				              					<option data-value="<?php echo $user['custid']?>"><?php echo $user['custname']?></option>
				              					<?php
				              					
				              				}
				              			?>
									</datalist>
									<input type="hidden" id="agentcurrent">
									<script type="text/javascript">
										document.querySelector('#agentInput').addEventListener('input', function(e) {
										    var input = e.target,
										        list = input.getAttribute('list'),
										        options = document.querySelectorAll('#' + list + ' option'),
										        hiddenInput = document.getElementById('agentcurrent'),
										        inputValue = input.value;

										    hiddenInput.value = inputValue;
										    // $('#searchticket').val('');
      								// 		$('#search').val('');
										    for(var i = 0; i < options.length; i++) {
										        var option = options[i];

										        if(option.innerText === inputValue) {
										            hiddenInput.value = option.getAttribute('data-value');
										            break;
										        }else{
										        	hiddenInput.value="";
										        }
										    }
										});
									</script>
			              		</label>
			            	</div>
			            	<div class="break-line margin-bot-5"></div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Nguồn phiếu</label>
			              		<select id="ticketchannel" onchange="deleteTextboxSearch()" class="no-border control-label col-md-8 no-padding-right">
			              			<option value="" selected>Chọn nguồn phiếu</option>
			              			<option value="1">Trực tiếp</option>
			              			<option value="2">Điện thoại</option>
			              			<option value="3">Email</option>
			              			<option value="4">Chat</option>
			              		</select>
			            	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Mức ưu tiên</label>
			              		<select onchange="deleteTextboxSearch()" class="no-border control-label col-md-8 no-padding-right" id="priority" name="priority">
			              			<option value="" selected>Chọn mức ưu tiên</option>
			              			<!-- <option value="0">Thấp</option> -->
			              			<option value="1">Thường</option>
			              			<option value="2">Cao</option>
			              			<option value="3">Khẩn cấp</option>
			              		</select>
			            	</div>
			            	<div class="flex">
			            		<label class="control-label user-label col-md-4 no-padding">Tình trạng</label>
			              		<select onchange="deleteTextboxSearch()" class="no-border control-label col-md-8 no-padding-right" id="status" name="status">
			              			<option value="" selected>Chọn tình trạng</option>
			              			<option value="1">Tạo mới</option>
			              			<option value="0">Đang xử lý</option>
	              					<option value="4">Hoàn thành</option>
			              		</select>
			            	</div>
			            	<div class="offset-9 margin-top-10">
			            		<button id="search_ticket" class="btn btn-primary float-right" type="button">Tìm kiếm</button>
			            	</div>
			            </div>
			        </div>
	           	</div>
          	</div>       
	    </div>
	    <div class="frame relative" style="width: 78%;">
	    	<iframe class="iframesearch" id="iframesearch" style="width: 100%; border: none;"  src=""></iframe>
	    	<div class="absolute hide" style="width: 100%; height: 100%;">
        		<i class="fa fa-spinner fa-spin" style="font-size: 28px; position: absolute; top: 20%; left: 48%;"></i>
        	</div>
	    </div>
    </div>
</main><file_sep><header class="app-header">
    <div class="row" style="width: 100%">
          <div id="lengthmenu" class="col-md-11">
            <ul class="nav nav-tabs nav-menu main-nav nav-inline" role="tablist">
                    <?php $var = $this->session->userdata;
                        $roleid = $var['roleid'];
                        if($roleid == '1')
                        {
                            $title_first = 'Cài đặt';
                            $icon_first = 'fas fa-user-circle';
                            $link = base_url().'setting';
                        }
                        else{
                            $title_first = 'Phiếu';
                            $icon_first = 'fas fa-file-alt'; 
                            $link = base_url().'ticket';  
                        }

                         ?>
                <li class="nav-item width-170" role="presentation">
                    <a name="<?php echo $link ?>" class="nav-link active show" role="tab" data-toggle="tab" href="#1000" title="<?php echo $title_first ?>">
                        <i class="<?php echo $icon_first ?>"></i> 
                        <span class="title_tab">
                     <?php echo $title_first ?></span></a><span class="fa fas fa-times" aria-hidden="true"></span>
                </li>
            </ul>
            
            <ul class="nav-insert nav-inline">
                <li class="dropdown dropdown-left" id="li-main">
                <a class="nav-link" aria-expanded="false" href="#add" data-toggle="dropdown"><i class="fa fa-plus fa-lg"></i></a>
              <ul class="dropdown-menu settings-menu dropdown-menu-right">
                <?php if ($var['roleid'] != '1') { ?>
                    
                <li><a class="dropdown-item" alt="insert" onclick="addTab('<?php echo base_url().'ticket/viewInsert/' ?>','Thêm Phiếu',true)" href="#"><i class="fa fa-file-alt fa-fw"></i> Thêm Phiếu</a></li>
                <?php } ?>
                <li><a class="dropdown-item" alt="insert" onclick="addTab('<?php echo base_url().'user/create' ?>','Thêm KH/Người dùng',true)" href="#"><i class="fa fa-user fa-lg"></i> Thêm KH/Người dùng</a></li>
                <li><a class="dropdown-item" alt="insert" onclick="addTab('<?php echo base_url().'task/create' ?>','Thêm Công việc',true)" href="#"><i class="fa fa-tasks fa-lg"></i> Thêm Công Việc</a></li>
              </ul>
            </li>
            </ul>
          </div>
          <div class="col-md-1">
              <ul class="app-nav">
                <li class="dropdown">
                    <a class="app-nav__item" href="#" data-toggle="dropdown" aria-label="Show notifications">
                        <span class="fa-stack fa-sm"><i class="fa fa-circle fa-stack-2x text-primary"></i><i class="fa fa-bell fa-stack-1x fa-inverse"></i></span>
                    </a>
                  <ul class="app-notification dropdown-menu dropdown-menu-right">
                    <li class="app-notification__title">You have 4 new notifications.</li>
                    <div class="app-notification__content">
                      <li><a class="app-notification__item" href="javascript:;"><span class="app-notification__icon"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-primary"></i><i class="fa fa-envelope fa-stack-1x fa-inverse"></i></span></span>
                          <div>
                            <p class="app-notification__message">Lisa sent you a mail</p>
                            <p class="app-notification__meta">2 min ago</p>
                          </div></a></li>
                      <li><a class="app-notification__item" href="javascript:;"><span class="app-notification__icon"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-danger"></i><i class="fa fa-hdd-o fa-stack-1x fa-inverse"></i></span></span>
                          <div>
                            <p class="app-notification__message">Mail server not working</p>
                            <p class="app-notification__meta">5 min ago</p>
                          </div></a></li>
                      <li><a class="app-notification__item" href="javascript:;"><span class="app-notification__icon"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-success"></i><i class="fa fa-money fa-stack-1x fa-inverse"></i></span></span>
                          <div>
                            <p class="app-notification__message">Transaction complete</p>
                            <p class="app-notification__meta">2 days ago</p>
                          </div></a></li>
                      
                    </div>
                    <li class="app-notification__footer"><a href="#">See all notifications.</a></li>
                  </ul>
                </li>
                <!-- phone -->

                <li class="dropdown">
                    <a class="app-nav__item" href="#" id="dropdown-btn" aria-label="Open Profile Menu">
                        <span class="fa-stack fa-sm">
                            <i class="fa fa-circle fa-stack-2x text-primary"></i>
                            <i class="fa fa-phone fa-stack-1x fa-inverse"></i>
                        </span>
                    </a>
                  <div id="phone-chat" class="dropdown-menu settings-menu dropdown-menu-right" extension="">
                    <div id="c-chanel" class="margin-left-right-5">
                        <label id="channel" channel="" class="control-label col-md-6 no-padding">Kênh thoại</label>
                        <div id="status-selection" class="active status-online">
                            <span class="status-circle"></span> 
                            <p>Online</p>
                            <i class="fa fa-caret-down fa-md float-right"></i>
                        </div>
                        <div id="status-options" class="info-area">
                            <ul>
                                <li id="status-online" class="active margin-top-5"><span class="status-circle"></span> <p>Online</p></li>
                                <li id="status-away"><span class="status-circle"></span> <p>Away</p></li>
                                <li id="status-busy"><span class="status-circle"></span> <p>Busy</p></li>
                                <li id="status-offline"><span class="status-circle"></span> <p>Offline</p></li>
                            </ul>
                        </div>
                        <div class="break-line margin-bot-5"></div>
                    </div>
                    <div id="c-phone-option" class="margin-right-5 margin-left-5">
                        <i class="fa fa-phone fa-md col-md-1 margin-top-3 margin-left--5 font-size-18"></i>
                        <label class="col-md-4 no-padding">1900 8888</label>
                        <i class="fa fa-th fa-md float-right margin-top-3" id="key-board"></i>
                    </div>
                    <div id="c-call-header" class="div user-call-pad hide">
                        <p class="phone-name" id="u-name"><img id="u-avatar" class="user-avatar phone-avatar" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image"><NAME></p>
                        <p id="u-phone" class="phone-num header-desc field-click-able">038 8485 4949</p>
                        <p id="u-time" class="phone-time header-desc field-click-able">00 : 00 : 25</p>
                        <p id="u-ticket" class="text-center margin-top--10">Phiếu: #47748</p>
                    </div>
                    <div class="break-line margin-bot-5"></div>
                    <div id="call-search" class="hide margin-bot-3">
                        <div class="search-input-group flex">
                            <i class="fa fa-search search-icon margin-right-5"></i>
                            <input placeholder="Nhập tên hoặc số điện thoại" id="user-call-search" class="width-100per" type="text">
                            <i class="fa fa-backspace search-destroy hide"></i>
                        </div>
                    </div>
                    <div id="call-input">
                        <div class="info-area search-result">
                            <i class="fa fa-times float-right margin-right-5 margin-top-5 call-input-close icon-hover"></i>
                            <ul id="s-rst" class="no-list-style" action="call">
                                <p class="type first font-size-10 no-margin">Khách hàng</p>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281</p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">2304</p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <p class="type font-size-10 no-margin">Khách hàng</p>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">2303</p>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div id="has-call-pad" class="text-center relative">
                        <div id="call-log" class="info-area search-result">
                            <!-- <p class="type first font-size-10 no-margin hide">Cuộc gọi gần đây</p>
                            <ul id="s-rst" class="no-list-style hide" action="call">
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281
                                            <span class="float-right margin-right-40">ticket: #1234</span>
                                        </p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281
                                            <span class="float-right margin-right-40">ticket: #1234</span>
                                        </p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281
                                            <span class="float-right margin-right-40">ticket: #1234</span>
                                        </p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281
                                            <span class="float-right margin-right-40">ticket: #1234</span>
                                        </p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281</p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                <li class="s-rst-li">
                                    <div class="s-rst-user">
                                        <p class="no-margin"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg" alt="User Image">Lan Phạm</p>
                                        <p class="user-num field-click-able">01663288281</p>
                                        <span class="status"></span>
                                    </div>
                                </li>
                                
                            </ul> -->
                            <div class="num-pad absolute">
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            1
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            2 <span class="small">
                                                <p>
                                                    ABC</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            3 <span class="small">
                                                <p>
                                                    DEF</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            4 <span class="small">
                                                <p>
                                                    GHI</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            5 <span class="small">
                                                <p>
                                                    JKL</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            6 <span class="small">
                                                <p>
                                                    MNO</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            7 <span class="small">
                                                <p>
                                                    PQRS</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            8 <span class="small">
                                                <p>
                                                    TUV</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            9 <span class="small">
                                                <p>
                                                    WXYZ</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            *
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            0 <span class="small">
                                                <p>
                                                    +</p>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="span4">
                                    <div class="num">
                                        <div class="txt">
                                            #
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div id="num-pad" class="num-pad absolute hide">
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        1
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        2 <span class="small">
                                            <p>
                                                ABC</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        3 <span class="small">
                                            <p>
                                                DEF</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        4 <span class="small">
                                            <p>
                                                GHI</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        5 <span class="small">
                                            <p>
                                                JKL</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        6 <span class="small">
                                            <p>
                                                MNO</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        7 <span class="small">
                                            <p>
                                                PQRS</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        8 <span class="small">
                                            <p>
                                                TUV</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        9 <span class="small">
                                            <p>
                                                WXYZ</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        *
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        0 <span class="small">
                                            <p>
                                                +</p>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="span4">
                                <div class="num">
                                    <div class="txt">
                                        #
                                    </div>
                                </div>
                            </div>
                        </div>
                        <p id="c-title"></p>
                        <div class="loader">
                            <ul>
                              <li></li>
                              <li></li>
                              <li></li>
                              <li></li>
                              <li></li>
                              <li></li>
                              <li></li>
                            </ul>
                        </div>
                        <p id="c-avatar" class="margin-top-10">
                            <img class="user-avatar" src="" alt="User Image">
                        </p>
                        <p id="c-name" class="no-margin"><NAME></p>
                        <p id="c-number" class="field-click-able">091 234 6688</p>
                        <p id="c-time" class="field-click-able"></p>
                        <p id="c-record" class="field-click-able hide">00 : 00 : 00</p>
                        <p id="c-option-1" class="font-size-8">Mới: 5  -  Đang xử lý: 1  -  Đóng: 2  -  Liên quan: 0</p>
                        <p id="c-option-2" class="font-size-8">Cuộc gọi: 6 - Email: 0 - Chat: 0</p>
                        <p id="c-ticket">Phiếu: #47748</p>
                        <div id="c-hang-up" class="col-md-12 flex margin-top-10 margin-bot-5">
                            <div class="col-md-4">
                                <div class="call-action">
                                    <img src="<?=base_url('images/icons/1.png')?>">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="call-action">
                                    <img src="<?=base_url('images/icons/2.png')?>">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="call-action">
                                    <img id="direct-call" src="<?=base_url('images/icons/3.png')?>">
                                </div>
                            </div>
                        </div>
                        <div class="clearfix">
                        </div>
                        <div id="are-b-end" class="col-md-12 no-padding">
                            <a href="#" class="btn btn-danger btn-block flatbtn margin-top-10">Kết thúc</a>
                        </div> 
                        <div id="are-b-has" class="col-md-12 flex no-padding font-size-12">
                            <!-- <div class="col-md-6 no-padding padding-right-5">
                                <a id="accept-call" href="#" class="btn btn-primary btn-block flatbtn margin-top-10">Chấp nhận</a>
                            </div> -->
                            <div class="col-md-12 no-padding">
                                <a id="deny-call" href="#" class="btn btn-danger btn-block flatbtn margin-top-10">Từ chối</a>
                            </div>
                        </div>
                        <div id="are-b-call" class="col-md-12 no-padding">
                            <a href="#" class="btn btn-primary btn-block flatbtn margin-top-10">Gọi</a>
                        </div>
                        <div id="are-b-direct" class="col-md-12 flex no-padding font-size-12">
                            <div class="col-md-6 no-padding padding-right-5">
                                <a id="deny-direct" href="#" class="btn btn-danger btn-block flatbtn margin-top-10">Hủy chuyển</a>
                            </div>
                            <div class="col-md-6 no-padding">
                                <a id="call-direct" href="#" class="btn btn-primary btn-block flatbtn margin-top-10">Chuyển tiếp</a>
                            </div>
                        </div>
                        <div id="are-b-close" class="col-md-12 no-padding hide">
                            <a id="close-call" href="#" class="btn btn-gray btn-block flatbtn margin-top-10">Đóng</a>
                        </div>
                    </div>
                  </div>
                </li>
                <!-- User Menu-->
                <li class="dropdown">
                    <a class="app-nav__item" href="#" data-toggle="dropdown" aria-label="Open Profile Menu">
                        <?php
                            $var1 = $this->session->userdata;
                            $custid = $var1['custid'];
                            $idcard = $var1['idcard'];
                            $roleid = $var1['roleid'];
                        ?>
                        <img class="app-nav__user-avatar" src="
                        <?php $var = $this->session->userdata;
                            if($var['avatar'] != 'null')
                            {
                                echo $var['avatar'];
                            }
                            else{ echo 'https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg';} ?>" alt="User Image">
                    </a>
                  <ul class="dropdown-menu settings-menu dropdown-menu-right">
                    <li><a class="dropdown-item" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$custid.'&idcard='.$idcard.'&roleid='.$roleid.'&action=profile'?>','Profile')"><i class="fa fa-user fa-lg"></i> Hồ sơ</a></li>
                    <li><a class="dropdown-item" data-toggle="modal" data-target="#modalChangePass" href="#"><i class="fas fa-sync-alt fa-lg"></i></i> Đổi mật khẩu</a></li>
                    <li><a class="dropdown-item" href="<?=base_url('login/logout')?>"><i class="fas fa-sign-out-alt fa-lg"></i> Đăng xuất</a></li>
                  </ul>
                </li>
            </ul>
          </div>
    </div>
    </header>

    <div class="modal fade" id="modalChangePass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Đổi mật khẩu</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
        <form id="formChangePass">
                  <div class="modal-body">
                         <div class="form-group">
                                    <label class="control-label user-label col-md-3 no-padding">Mật khẩu cũ: </label>
                                    <label class="control-label col-md-8 no-padding-right">
                                        <input type="<PASSWORD>" placeholder="<PASSWORD>" id="old_pass" name="old_pass" required="" class="col-md-12 no-padding font-size-12">
                                    </label>
                        </div>
                                  
                        <div class="form-group">
                            <label class="control-label user-label col-md-3 no-padding">Mật khẩu mới: </label>
                            <label class="control-label col-md-8 no-padding-right">
                                <input type="password" required="" placeholder="<PASSWORD>" id="new_pass" name="new_pass" class="col-md-12 no-padding font-size-12">
                            </label>
                        </div>

                        <div class="form-group">
                            <label class="control-label user-label col-md-3 no-padding">Xác nhận mật khẩu mới: </label>
                            <label class="control-label col-md-8 no-padding-right">
                                <input type="password" required="" placeholder="X<PASSWORD> m<PASSWORD>" id="confirm_pass" name="confirm_pass" class="col-md-12 no-padding font-size-12">
                            </label>
                        </div>
                  </div>
                      <div class="modal-footer" style="background: #f5f5f5">
                        <button type="button" class="btn btn-gray-white float-right" data-dismiss="modal">Đóng</button>
                        <button type="submit" class="btn btn-gray-black float-right" id="btn_changepass"><i class=""></i>Đổi</button>
                      </div>
        </form>
    </div>
  </div>
</div><file_sep><div class="tile p-0 padding-5 margin-bot-5">
	          <div class="tile-body padding-left-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phân loại: </label>
	              		<select name="status" class="control-label col-md-8 no-border no-padding margin-left-10" id="codictionary_typework">
	              			<option value="-1" selected="">Tất cả</option>
	              			<?php foreach ($list_ext_type as $key) { ?>
	              				<option value="<?php echo $key['code']  ?>"><?php echo $key['name']  ?></option>
	              			<?php } ?>
	              		</select>
	            	</div>
	            </div>
 </div>
	            	<div class="fc-corner-right">
		          		<div class="fc-button-group" style="float:right">
							<button type="button" onclick="changeiFrameDetailWork()" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right btn-createuser">Lọc thông tin</button>
						</div>
		          	</div><file_sep><aside class="app-sidebar">
      <div class="app-sidebar__user"><img src="<?=base_url('images/icons/agi-logo.png')?>">
        <div>
          <p class="app-sidebar__user-name"><NAME></p>
          <p class="app-sidebar__user-designation">Frontend Developer</p>
        </div>
      </div>
      <ul class="app-menu">
        <li>
        	<a class="app-menu__item" onclick="addTab('<?= base_url('search') ?>','Tìm kiếm')" target="myiframetext" href="#" title="" alt="search">
	        	<img src="<?=base_url('images/icons/timkiem.png')?>">
	        	<span class="app-menu__label">Tìm kiếm</span>
	        </a>
	    </li>
	     <?php $var = $this->session->userdata;
                    $roleid = $var['roleid'];
                    if($roleid == '1')
                    {
                        $title_first = 'Cài đặt';
                        $alt_first = 'setting';
                        $icon_first = 'fas fa-user-circle';
                        $link = 'setting';
                    }
                    else{
                        $title_first = 'Phiếu';
                        $alt_first = 'ticket';
                        $icon_first = 'fas fa-file-alt'; 
                        $link = 'ticket';  
                    }

                     ?>
	    <?php $var = $this->session->userdata;
                    $roleid = $var['roleid'];
                    if($roleid != '1'){?> 
	    <li>
	        <a class="app-menu__item active" onclick="addTab('<?= base_url($link) ?>','<?php echo $title_first ?>')" target="myiframetext" href="#">
	        	<img src="<?=base_url('images/icons/list.png')?>">
	        	<span class="app-menu__label">Ticket</span>
	        </a>
	    </li>
	    <?php } ?>
	    <li>
        	<a class="app-menu__item click_navtab" onclick="addTab('<?= base_url('knowledge') ?>','Thư viện kiến thức')" target="myiframetext" href="#" alt="knowledge">
        		<img src="<?=base_url('images/icons/6.png')?>">
	        	<span class="app-menu__label">Thư viện kiến thức</span>
	        </a>
	    </li>

	    <li>
        	<a class="app-menu__item click_navtab" onclick="addTab('<?= base_url('task') ?>','Công việc')" target="myiframetext" href="#" alt="task">
        		<img src="<?=base_url('images/icons/7.png')?>">
	        	<span class="app-menu__label">Công việc</span>
	        </a>
	    </li>
        <!-- <li class="treeview">
            <a class="app-menu__item" href="#" data-toggle="treeview">
                <i class="app-menu__icon fa fa-edit"></i>
                <span class="app-menu__label">Datasource</span>
                <i class="treeview-indicator fa fa-angle-right"></i>
            </a>
            <ul class="treeview-menu">
                <li>
                    <a class="treeview-item" href="#" onclick="addTab('<?= base_url('datastage') ?>','Giai đoạn')">
                        <i class="icon fa fa-circle-o"></i> 
                    Giai đoạn</a>
                </li>
                <li>
                    <a class="treeview-item" href="#" onclick="addTab('<?= base_url('issuetype') ?>','Phân loại')">
                        <i class="icon fa fa-circle-o"></i> 
                    Phân loại</a>
                </li>
                <li>
                    <a class="treeview-item" href="#" onclick="addTab('<?= base_url('issuegroup') ?>','Nhóm vấn đề')">
                        <i class="icon fa fa-circle-o"></i> 
                    Nhóm vấn đề</a>
                </li>
                <li>
                    <a class="treeview-item" href="#" onclick="addTab('<?= base_url('issuedetail') ?>','Chi tiết vấn đề')">
                        <i class="icon fa fa-circle-o"></i> 
                    Chi tiết vấn đề</a>
                </li>
            </ul>
        </li> -->
	    <?php $var = $this->session->userdata;
                    $roleid = $var['roleid'];
                    if($roleid == '1'){?> 
	     <li>
        	<a class="app-menu__item active click_navtab" onclick="addTab('<?= base_url($link) ?>','<?php echo $title_first ?>')" target="myiframetext" target="myiframetext" href="#" alt="<?php echo $alt_first ?>">
	        	<img src="<?=base_url('images/icons/8.png')?>">
	        	<span class="app-menu__label">Cài đặt</span>
	        </a>
	    </li>
		<?php } ?>
      </ul>
    </aside>
<div class="app-sidebar__overlay" data-toggle="sidebar"></div><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Setting extends CI_Controller {

	public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model('M_api');
    }
    public function index()
    {
        $_body = [];
        $_body['left'] = $this->load->view('user/left/ud_dashboard_left',null,TRUE); 
        $_body['right'] = $this->load->view('user/right/ud_dashboard_right', null, TRUE);
        // $_body['center'] = $this->load->view('user/center/ud_dashboard_center', $data, TRUE);
        $_data = [];    
        $_data['navbar'] = $this->load->view('navbar/navbar', NULL, TRUE); 
        $_data['sidebar'] = $this->load->view('sidebar/sidebar', NULL, TRUE); 
        $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); 
        $_data['script2'] = $this->load->view('script/script_group_user', NULL, TRUE);  
        $_data['mainview'] = $this->load->view('user/user', $_body , TRUE);
        $this->load->view('dashboard',$_data);
    }
    public function viewUser()
    {
        $var = $this->session->userdata();
        $roleid = $var['roleid'];
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/search?roleid='.$roleid);
        $data['user'] = json_decode($json,TRUE)['data'];
        $_data = [];    
        $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); 
        $_data['script2'] = $this->load->view('script/script_group_user', NULL, TRUE);  
        $_data['mainview'] = $this->load->view('user/center/ud_dashboard_center', $data , TRUE);
        $this->load->view('dashboard',$_data);
    }
    public function viewGroupUser()
    {
        $_data = [];    
        $_data['script'] = $this->load->view('script/script_dashboard', NULL, TRUE); 
        $_data['script2'] = $this->load->view('script/script_group_user', NULL, TRUE);  
        $_data['mainview'] = $this->load->view('groupuser/center/gu_center_detail', null , TRUE);
        $this->load->view('dashboard',$_data);
    }
    public function searchUser()
    {
        $keywordPost = $this->input->post('keyword');
        $keyword = urlencode($keywordPost);
        $_jsonSearch = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/search?roleid=1&search='.$keyword);
        echo $_jsonSearch;
    }

	public function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
	}


}
?><file_sep><?php

class M_api extends CI_Model
{
	private $url_api_db = "http://test.tavicosoft.com/crm/index.php/api/";

	private $ClientId = 'API@AGT';

    private $SecurityKey = "<KEY>";

    private $TvcToken = "C49D0F74-286D-4180-ABA1-D0F37685E8C4";

    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('date'));
        $this->load->driver('cache');
    }

    public function execute_tvc_api($url,$action,$method,$data,$type="rpc",$tid="1"){

		$req_data = array(
			"action" => $action, 
			"method" => $method,
			"data" => $data,
			"type" => $type,
			"tid" => $tid
		);  

		$raw_data = json_encode($req_data);          

		$ch = curl_init($url);

		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
		curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data);                                                                  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
		    'Content-Type: application/json;charset=uft-8',                                                                                
		    'ClientId: '.$this->ClientId,
			'SecurityKey: '.$this->SecurityKey,
			'TvcToken: '.$this->TvcToken                                                                       
		));                                                                                                   

		// echo($raw_data);           

		$result = curl_exec($ch);

        return $result;

		// var_dump($data_string);
    }

    public function execute_normal_api($url,$data){

    	$raw_data = json_encode($data);          

		$ch = curl_init($url);

		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
		curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data);                                                                  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
		    'Content-Type: application/json'                                                                       
		));                                                                                                   

		// echo($raw_data);           

		$result = curl_exec($ch);

        return $result;
    }

    public function gen_custid(){
    	$datestring = '%Y%m%d%h%i%s';
        $now = time();
        $time =  mdate($datestring, $now);
        $ran = rand(100,999);
        return $time.$ran;
    }

    public function gen_taskid(){
    	$datestring = '%h%i%s';
        $now = time();
        $time =  mdate($datestring, $now);
        $ran = rand(1000,9999);
        return $time.$ran;
    }

    public function getlistcustomer($roleid=0){

    	$result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/getcustomerbyroleid/'.$roleid.'?pagesize=1000');
        return $result;
    }

    public function getlistcustomerbygroupid($groupid=0){
    	$result = file_get_contents('http://test.tavicosoft.com/crm/index.php/Customer/getcustomerbygroupid/'.$groupid.'?pagesize=1000');
        return $result;
    }

    public function getlistgroup($groupid=''){
    	$result = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/selectbygroupid/'.$groupid);
        return $result;
    }

    public function getlistgroup_array($groupid=''){
        //$result = $this->cache->memcached->get('crm_groupdetail_'.$groupid);
        $result = "";
        if (!$result){
            $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/group/selectbygroupid/'.$groupid);
            //$this->cache->memcached->save('crm_groupdetail_'.$groupid,$result, 86400);
        }
    	$result_array = json_decode($result,true);
    	if($result_array['code']==1){
    		if($groupid!=''){
    			return $result_array['data'][0];
    		}
    		return $result_array['data'];
    	}else{
    		return [];
    	}
    }


    public function getListGroupCache(){
        //$result = $this->cache->memcached->get('crm_group');
        $result = "";
        if (!$result){
            $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/group');
            //$this->cache->memcached->save('crm_group',$result, 86400);
        }
        return $result;
    }

    public function getTicketById($ticketid){
        //$result = $this->cache->memcached->get('ticket_'.$ticketid);
        if (!$result){
            $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/search?search=&ticketid='.$ticketid.'');
            $this->cache->memcached->save('ticket_'.$ticketid,$result, 86400);
        }
        return $result;
    }

}<file_sep><?php $type = "D"; ?>
<?php $ref1 = $this->input->get('ref1');
      $ref2 = $this->input->get('ref2'); ?>
<div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5>Danh sách dữ liệu trường: Nhóm chi tiết vấn đề</h5>
			        </div>
			    </div>
				    <div style="float: right;">
						<button <?php if($type == 'T'){echo 'hidden';} ?> type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal">Thêm</button>
					</div>
			    
				<div class="bs-component" style="margin-top: 55px">
					<?php if ($type == 'T'){
						echo '<div class="component-fields">
				                    <i class="fas fa-align-justify"></i> 
				                    <span class="title_tab" style="padding-left: 6px">Text</span>
							</div>';
					} ?>
					<?php if(count($list_ext)>0){
						foreach ($list_ext as $value) {
                if(($ref1 ==-1 && $ref2 == -1) || (($value['ref1'] == $ref1 && $value['ref2'] ==$ref2) || ($value['ref1'] == $ref1 && $ref2 == -1)))
                {
             ?>
							<div class="component-fields" style="<?php if($value['status'] == 'C') echo ' background-color: #d88375 !important'; ?>">
                            <i class="<?php if($value['status'] == 'W') echo 'fas fa-align-justify'; else{echo 'fas fa-ban';} ?>" style="<?php if($value['status'] == 'C') echo 'color: #FFF;'; ?>"></i> 
                            <span class="title_tab" style="padding-left: 6px;
                            <?php if($value['status'] == 'C') echo 'color: #FFF;'; ?>
                            "><?php echo $value['name'] ?></span>
                             <a class="user-name" style="cursor: pointer;float: right;<?php if($value['status'] == 'C') echo 'color: #FFF !important;'; ?>"  data-toggle="modal" data-target="#modalUpdate" data-code="<?php echo $value['code'] ?>" data-category="<?php echo $value['category'] ?>" data-name="<?php echo $value['name'] ?>" data-status="<?php echo $value['status'] ?>" data-comments="<?php echo $value['comments'] ?>" data-ref1="<?php echo $value['ref1'] ?>" data-ref2="<?php echo $value['ref2'] ?>"><i class="fas fa-edit"></i></a>
              </div>
						<?php }}}?>
	            </div>
          	</div>
 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document" style="margin-top: 5%">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Dropdown Options</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
	        	<div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Phân loại:</label>
            <select name="ref1_insert" onchange="getGroup(this,'ref2_insert')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref1_insert">
              <option value="" selected="" disabled="">Chọn phân loại</option>
              <?php foreach ($list_ext_type as $key) { ?>
                <option value="<?php echo $key['code'] ?>"><?php echo $key['name'] ?></option>
              <?php } ?>
            </select>
        </div>

        <div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Nhóm vấn đề:</label>
            <select name="ref2_insert" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref2_insert">
              <option value="" selected="" disabled="">Chọn nhóm VĐ</option>
            </select>
        </div>

            <div class="optionbottom">
            <label class="control-label user-label col-md-3 col-sm-3 no-padding">Mã Chi tiết VĐ: </label>
            <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
            <input type="text" class="col-md-12 no-padding font-size-12" name="code" id="code" placeholder="-Mã trường"></label>
            </div>

        <div class="form-group extendbottom">
                <label class="control-label user-label col-md-3 col-sm-3 no-padding">Chi tiết VĐ: </label>
                <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <input type="text" class="col-md-12 no-padding font-size-12" name="name" id="name" placeholder="-Tên trường"></label>
        </div>

        <!-- <div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hoạt động:</label>
            <select name="status_insert" class="control-label col-md-8 col-sm-8 no-border no-padding" id="status_insert">
              <option value="W">Hoạt Động</option>
              <option value="C">Không Hoạt Động</option>
            </select>
        </div> -->

        <div class="">
            <label class="control-label user-label col-md-3 col-sm-3 no-padding">Ghi chú:</label>
              <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <textarea class="col-md-12 no-padding font-size-12 control-textarea" placeholder="Nhập bất kỳ một nội dung..." id="comments_insert"></textarea>
            </label>
          </div>
				<input type="hidden" name="category" id="category" value="knwdetail">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="insertSelectBox()" class="btn btn-primary">Thêm</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 7%" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Xoá Option</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bạn có chắc muốn xoá không?</p>
        <input type="hidden" id="categorydelete" name="categorydelete">
        <input type="hidden" id="codedelete" name="codedelete">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="deleteButton()" class="btn btn-danger">Xoá</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 7%" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Sửa Option</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
      	<div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Phân loại:</label>
            <select name="ref1_update" onchange="getGroup(this,'ref2_update')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref1_update">
              <?php foreach ($list_ext_type as $key) { ?>
                <option value="<?php echo $key['code'] ?>"><?php echo $key['name'] ?></option>
              <?php } ?>
            </select>
        </div>

        <div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Nhóm vấn đề:</label>
            <select name="ref2_update" class="control-label col-md-8 col-sm-8 no-border no-padding" id="ref2_update">
            </select>
        </div>
        <div class="">
          <label class="control-label user-label col-md-3 col-sm-3 no-padding">Tên:</label>
          <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
          <input type="text" class="col-md-12 no-padding font-size-12 nameField" id="nameField" name="name" placeholder="Tên"></label>
        </div>
        <div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hoạt động:</label>
            <select name="status" class="control-label col-md-8 col-sm-8 no-border no-padding" id="status">
              <option value="W">Hoạt Động</option>
              <option value="C">Không Hoạt Động</option>
            </select>
        </div>
        <div class="">
            <label class="control-label user-label col-md-3 col-sm-3 no-padding">Ghi chú:</label>
              <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <textarea class="col-md-12 no-padding font-size-12 control-textarea" placeholder="Nhập bất kỳ một nội dung..." id="comments" name="comments"></textarea>
            </label>
          </div>
        <input type="hidden" id="category" name="category">
        <input type="hidden" class="code" id="code" name="code">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="updateButton()" class="btn btn-primary">Sửa</button>
      </div>
    </div>
  </div>
</div><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10">
          <?php echo isset($top) ? $top : ''; ?>
        </div>
        <div class="col-md-3 col-md-24 no-padding padding-left-15 height-1024">
            <?php echo isset($left) ? $left : ''; ?>
        </div>
        <div class="col-md-6 no-padding padding-left-5">
            <?php echo isset($center) ? $center : ''; ?>
        </div>
        <div class="col-md-3 no-padding padding-left-5 relative height-1024">
          <?php echo isset($right) ? $right : ''; ?>
        </div>
    </div>
</main><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Typework extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model('M_api');
	}
	public function index()
	{
		$list_extend['list_ext'] = [];
        $list_extend['detail'] =[];
        $fieldtype = 'D';
        if($fieldtype == 'D')
        {
            $datasource = 'tasktype';
            $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/selectall/'.$datasource);
            $list_ext = json_decode($_jsonlistext,true);
            $list_extend['list_ext'] = $list_ext['data']; 
        }
		$_body = [];
        $_body['center'] = $this->load->view('datasource/typework/tw_center', $list_extend, TRUE);
        $_data = [];    
        $_data['script'] = $this->load->view('script/script_datastage', NULL, TRUE); 
        $_data['mainview'] = $this->load->view('datasource/datastage/form', $_body , TRUE);
        $this->load->view('dashboard',$_data);
	}

}

/* End of file Typework.php */
/* Location: ./application/controllers/Typework.php */
?><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 padding-left-15">
          	<?php echo isset($left)?$left:'' ?>
        </div>

        <div class="col-md-7 padding-left-1">
            <iframe class="iframeIssueGroup" id="iframeIssueGroup" style="min-height: 1024px;width: 100%; border: none;"  src="<?php echo base_url() ?>issuegroup/rightFilter?ref1=-1"></iframe>
        </div>
        <div class="col-md-2 col-md-18 padding-left-5">
        	
        </div>
    </div>
</main><file_sep><div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Mã giao dịch:</label>
	              		<label class="control-label col-md-8 no-padding-right col-brk-8"><a class="a_contractid" id="a_contractid" href="#" target="_blank"><?php echo $trade[0]['contractid'] ?></a></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Tình trạng</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['status'] ?></label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Mã KH</label>
	              		<label class="control-label col-md-8 no-padding-right"><a class="a_custid" id="a_custid" href="#" target="_blank"><?php echo $trade[0]['clientcode'] ?></a></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">BĐS</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['property'] ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Sàn</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['name'] ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">NV phụ trách</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['name2'] ?></label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày bắt đầu</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php 
	              		if($trade[0]['startdate'] !=null)
	              		{
	              		echo date("d/m/Y", strtotime($trade[0]['startdate']));} ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày kết thúc</label>
	              		<label class="control-label col-md-8 no-padding-right">22/06/2018</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị HĐ</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['contractvalue']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá chưa VAT</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['value0']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Thuế VAT</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['value1']) ?></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phí bảo trì</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo number_format($trade[0]['value2']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">GT Q SDĐ</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value3']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá tính VAT</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value4']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phí tư vấn</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value5']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị CK</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value6']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị cọc</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value7']) ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá chuẩn <br> chưa VAT</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value8']) ?></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Tổng GT HĐ</label>
	              		<label class="control-label col-md-8 no-padding-righte"><?php echo number_format($trade[0]['value9']) ?></label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Loại vay</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct8'] ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngân hàng</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['name1'] ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Chứng từ NH</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị vay</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['loanvalue'] ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày vay</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['loandate'] ?></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ghi chú vay</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['loannotes'] ?></label>
	              		<label class="control-label user-label col-md-3 no-padding">Ngày ký</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct7'] ?></label>



	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Số HĐ cọc</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct8'] ?></label>
	              		<label class="control-label user-label col-md-3 no-padding">Số HĐ</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['anal_pct9'] ?></label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ghi chú</label>
	              		<label class="control-label col-md-8 no-padding-right"><?php echo $trade[0]['notes'] ?></label>
	            	</div>
	            </div>
          	</div><file_sep><div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5>Người dùng</h5>
			        </div>
			        <ul class="app-breadcrumb breadcrumb">
				        <li class="breadcrumb-item"><a style="cursor: pointer;" onclick="addTab('<?php echo base_url().'user/create' ?>','Thêm User')">Thêm</a></li>
			        </ul>
			    </div>
			    <p class="margin-top-10 no-margin-bot">Người dùng là những người tương tác với hệ thống AGI CRM, bao gồm chuyên viên của AGI và khách hàng của AGI, họ tương tác thông qua chủ thể là Phiếu hỗ trợ (Tickets). Bạn có thể tạo các trường thông tin mở rộng và phân nhóm để quản lý người dùng được tốt hơn.</p>
			    <div class="row margin-top-10">
	                <div class="form-group col-md-6 no-padding-right">
	                  <input id="keyword" class="form-control" type="text" placeholder="Nhập từ khóa...">
	                </div>
	                <div class="form-group col-md-3 align-self-end padding-left-1">
	                  <button class="btn btn-primary" onclick="search()" type="button">Tìm kiếm</button>
	                  <img src="<?php echo base_url().'images/loader.gif' ?>" style="display: none;"  id="loading">
	                </div>
	            </div>
	            <ul class="app-breadcrumb breadcrumb">
            		<p class="margin-right-10 font-size-12">Lọc nhanh:</p>
			        <!-- <li class="breadcrumb-item"><a class="user-name" style="cursor: pointer;" onclick="searchRoleid('3')">Khách hàng</a></li> -->
			        <li class="breadcrumb-item"><a class="user-name" style="cursor: pointer;" onclick="searchRoleid('2')">Chuyên viên</a></li>
			        <li class="breadcrumb-item"><a class="user-name" style="cursor: pointer;" onclick="searchRoleid('1')">Quản trị viên</a></li>
		        </ul>
		        <div class="content-search">
		        <div class="table-responsive">
	              <table class="table" id="tableUser">
	              	<thead>
	              		<tr>
				            <th></th>
				            <th>Họ tên</th>
				            <th>SĐT</th>
				            <th>Email</th>
				        </tr>
	              	</thead>
	                <tbody>
	                  	<?php foreach ($user as $value) { ?>
	                  		<tr>
	                  		<td width="40px">
		                    	<img class="user-avatar" src="<?php echo $value['avatar'] ?>" alt="User Image">
		                    </td>
		                    <td width="252px">
		                    	<a class="user-name" style="cursor: pointer;" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$value['custid'].'&idcard='.$value['idcard'].'&roleid='.$value['roleid'] ?>','<?php echo $value['custname'] ?>')"><?php echo $value['custname'] ?></a>
		                    	<p class=""><?php echo $value['groupname'] ?></p>
		                    </td>
		                    <td width="229px"><?php echo $value['telephone'] ?></td>
		                    <td width="218px"><?php echo $value['email'] ?></td>
		                  </tr>
	                  	<?php } ?>
	                    
	                </tbody>
	              </table>
	            </div>
	            </div>
          	</div><file_sep><div class="col-md-100 no-padding padding-left-5">
	    	<div class="tile height-1024">
	            <div class="table-responsive">
	              	<table class="table" id="table-1-searchuser">
	              		<thead class="no-border-top">
	              			<tr>
	              				<th>Tên</th>
	              				<th>Số CMND</th>
	              				<th>Số điện thoại</th>
	              				<th>Email</th>
	              				<th>Cập nhật lần cuối</th>
	              			</tr>
	              		</thead>
		                <tbody>
		                	<?php 
		                	if(count($result['data']) >0)
		                	{
		                	foreach ($result['data'] as $rows) { ?>
		                	<tr class="border-bot-1">
			                    <td width="250">
			                    	<a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'user/detail/?cusid='.$rows['custid'].'&idcard='.$rows['idcard'].'&roleid='.$rows['roleid'] ?>','<?php echo $rows['custname'] ?>')" href="#" title="">
			                    	<?php echo strtoupper(mb_convert_case($rows['custname'],MB_CASE_UPPER,'UTF-8')) ?>
			                    	</a>
			                    </td>
			                    <td><?php echo $rows['idcard'] ?></td>
			                    <td><?php echo $rows['telephone'] ?></td>
			                    <td><?php echo $rows['email'] ?></td>
			                    <td><?php 
			                    if($rows['lastupdate']!=null && strtotime($rows['lastupdate'])>strtotime('2000/01/01'))
			                    {
			                    echo date("d/m/Y H:i:s", strtotime($rows['lastupdate']));}
			                     ?></td>
		                  	</tr>	
		                	<?php }} ?>				  
		                </tbody>
	              	</table>
	            </div>  
	        </div>
	    </div><file_sep>	<div class="tile no-margin-bot">
        <div class="content-title">
	        <div class="div width-100per">
	          	<h5 class="flex"><i class="fa fa-lg fa-file-alt header-icon"></i>
	          		<input style="width: 80%
	          		" name="title" class="no-padding font-size-18 width-95per crm-control" log="Tiêu đề" placeholder="Nhập tiêu đề phiếu hỗ trợ" value="<?php echo $ticket['data'][0]['title'] ?>" old-value="<?php echo $ticket['data'][0]['title'] ?>">
	          	</h5>
	          	<div class="btn-group absolute" role="group" style="right: 10px;top: 15px;">
	          	  <button class="btn btn-primary" type="button" id="btn-accept" tckid="<?php echo $this->uri->segment(3) ?>">
	          	  	<i class="fa fa-share"></i>
	          	  Tiếp nhận</button>
                  <button class="btn btn-primary dropdown-toggle" id="btnGroupDrop1" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
                  <div class="dropdown-menu dropdown-menu-right" x-placement="bottom-end">
                  	<a class="dropdown-item" href="#" tck-id="<?php echo $ticket['data'][0]['ticketid'] ?>" tck-stt="<?php echo $ticket['data'][0]['status'] ?>" tck-title="<?php echo $ticket['data'][0]['title'] ?>" id="btn-ticket-merge">Ghép phiếu</a>
                  		<a class="dropdown-item" href="javascript:window.location.reload();"><i class="fa fa-sync-alt fa-md float-right margin-top-3"></i>Refresh phiếu</a>
                  </div>
                </div>
	        </div>
	    </div>
	    <div class="break-line margin-bot-5"></div>
	    <div class="row">
	    	<div class="col-md-12 comment-wrap">
				<div class="photo">
					<img class="avatar" src="<?php echo($this->session->userdata('avatar')!=''?$this->session->userdata('avatar'):'https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg')?>">
				</div>
				<div class="comment-block">
					<div class="status-upload">
						<input type="hidden" name="ticketid" value="<?php echo $this->uri->segment(3)?>">
						<input type="hidden" name="changelog">
						<textarea name="cmt" placeholder="Nhập ghi chú" ></textarea>
					</div><!-- Status Upload  -->
					<button type="<?php if($update){ echo "submit";}else{ echo "button";}?>" title="<?php echo $this->uri->segment(3) ?>" class="btn btn-gray margin-top-5 float-right <?php if($update){ echo "btn-updateAction";}else{ echo "btn-updateActionUpdate";}?>">
						<i class="fa fa-share"></i> Ghi nhận
					</button>
				</div>
			</div>
		</div>
  	</div>
</form>
<div class="comments no-padding">
	<ul class="nav nav-tabs no-margin margin-bot-5">
        <li class="nav-item">
        	<a class="user-tab active show" data-toggle="tab" href="#tab-content-1">Lịch sử phiếu</a>
        </li>
        <li class="nav-item">
        	<a class="user-tab" data-toggle="tab" href="#tab-content-2">Công việc</a>
        </li>
  	</ul>
  	<div class="tab-content" id="myTabContent">
        <div class="tab-pane fade active show" id="tab-content-1">
          	<iframe name="tck_log" class="no-border" style="width: 100%; height: 500px;" src="<?php echo(base_url('ticket/view_ticket_log/'.$this->uri->segment(3)))?>"></iframe>
        </div>
        <div class="tab-pane fade" id="tab-content-2">
          	<iframe name="tck_task" class="no-border" style="width: 100%; height: 500px;" src="<?php echo(base_url('ticket/view_ticket_task/'.$this->uri->segment(3).'/'.$ticket['data'][0]['custid']))?>"></iframe>
        </div>
  	</div>	
</div>
<file_sep><script type="text/javascript">
	var tic = $('select[name=tic]').val();
	if (tic!='') {
		$('select[name=pic] option').each(function(){
			var group = $(this).attr('data-group');
			if (tic==group) {$(this).prop('disabled',false);}
			else{$(this).prop('disabled',true);}
		});
	}
	if (tic && tic!='<?php echo($this->session->userdata('groupid'))?>') {
		$('#btn-accept').remove();
		$('.crm-control,.crm-ext,button[type=submit]').prop('disabled',true);
	}
	var pic = $('select[name=pic]').val();
	  if (pic) {
	  	if (pic!='<?php echo $this->session->userdata('custid');?>') {
	  		$('.crm-control,.crm-ext,button[type=submit]').prop('disabled',true);
	  	}
	    $('#btn-accept').remove();
	  }else{
	    $('.crm-control,.crm-ext,button[type=submit]').prop('disabled',true);
	  }

	$('input[name=req_date],input[name=ola_date],input[name=due_date],input[name=fns_date]').datetimepicker({format:'Y-m-d h:i'});

	$('.my-chosen').chosen({
		width:'105%',
		disable_search_threshold: 9,
		no_results_text: "Không tìm thấy: ",
		allow_single_deselect: true
	});

	$('select[name=tic]').change(function(){
		var val = $(this).val();
		if(val){
			$('select[name=pic] option').each(function(){
				var group = $(this).attr('data-group');
				if (val==group) {$(this).prop('disabled',false);}
				else{$(this).prop('disabled',true);}
			});
			$('select[name=pic] option:disabled(not):first').prop('selected',true);
		}else{
			$('select[name=pic] option').each(function(){
				$(this).prop('disabled',false);
			});
		}
		$('.my-chosen').trigger('chosen:updated');
	});

	$('select#level_1').change(function(){
        var val = $(this).val();
        if(val){
          $('select#level_2 option').each(function(){
            var ref1 = $(this).attr('ref1');
            if (ref1==val) {
              $(this).removeClass('hide').addClass('show');
            }else{
              $(this).addClass('hide').removeClass('show');
            }
          });
        }else{
          $('select#level_2 option').each(function(){
            $(this).removeClass('hide').addClass('show');
          });
        }

        $('select#level_2 option.show:first').prop('selected',true);
        var log = $('select#level_2').attr('log');
	    var old_value = $('select#level_2').attr('old-value');
	    var new_value = $('select#level_2').val();
	    if (log) {
	      var text = $('select#level_2').find('option:selected').text();
	      if (old_value === new_value) {deletelog(log);}else{changelog(log,text);}
	    }
    });

	$(document).on('change','.crm-control',function(){
	    var log = $(this).attr('log');
	    var old_value = $(this).attr('old-value');
	    var new_value = $(this).val();
	    if (log) {
	      var text = $(this).find('option:selected').text();
	      if (!text) {
	        text = $(this).val();
	      }
	      if (old_value === new_value) {deletelog(log);}else{changelog(log,text);}
	    }
	});

	$('#btn-accept').click(function(){
	    var cur = $(this);
	    var taskid = $(this).attr('taskid');
	    if (taskid)
	    cur.prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
	    $.ajax({
	        url: '<?php echo base_url().'task/get_to_my_task/'?>'+taskid,
	        type: 'POST',
	        dataType: 'JSON',
	      })
	      .done(function(data) {
	          if(data.code==1){
	            parent.notification('Tiếp nhận công việc thành công.');
	            window.location.reload();
	          }else{
	            parent.alertLog('Lỗi',data.message,'danger');
	            // alert(data.message);
	          }
	        })
	      .fail(function() {
	         cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
	         parent.alertLog('Lỗi',"Lỗi kết nối.",'danger');
	      });
	  });

	$('#all-in').on('submit',function(){
		var form = new FormData($(this)[0]);
		var url = '<?php echo(base_url().'task/aj_api_update');?>';
		var error = [];
	    for (var [key, value] of form.entries()) { 
	      // console.log(key, value);
	      switch(key){
	        case 'taskmaster':
	          if (value=='') {
	            error[key] = "1";
	            parent.alertLog('Cảnh báo','Vui lòng chọn người yêu cầu.','warning');
	          }
	          break;
	        case 'tic':
	          if (value=='' && form.get('pic') == '') {
	            error[key] = '1';
	            parent.alertLog('Cảnh báo','Bạn phải nhập 1 trong 2 thông tin: Nhóm phụ trách, Người phụ trách.','warning');
	          }else if (value=='' && form.get('pic') !='') {
	            var agent = $('select[name=pic]').find('option:selected').attr('data-group');
	            console.log(agent);
	            if (agent) {form.set('tic',agent)}
	          }
	          break;
	        default: break;
	      }
	    }
	    if (!jQuery.isEmptyObject(error)) {
	      var msg = '';
	      for (let key in error){
	        msg+= error[key]+"\n";
	      }
	      console.log(msg);
	    }else{
	    	var button_luu = $(this);
  			$(this).find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
	  		$.ajax({
		          type: "POST",
		          url: url,
		          data:  form,
		          dataType:'json',
		          contentType: false,
		          cache: false,
		          processData:false,
		          success: function(data) {
		          	if (data.code==1) {
		        		window.location.reload();
		        	}else{
		        		button_luu.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
		        		parent.alertLog('Cảnh báo',data.message,'warning');
		        	}
		          },
		          error: function(xhr, status, error) {
		            console.log(error);
		          }
	        });
  		}
        return false;
	});

	function changelog(log,text){
	    var oldchange = $('input[name=changelog]').val();
	    var newchange = '';
	    var arr_log = oldchange.split('|');
	    if (arr_log.length>0) {
	      for (var i = 0; i < arr_log.length; i++) {
	        // console.log(arr_log[i]);
	        if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){
	          newchange += arr_log[i].trim()+" | ";
	        }
	      }
	    }
	    newchange += log+': '+text+" | ";
	    console.log(newchange);
	    $('input[name=changelog]').val(newchange);
	    return false;
	  }
	function deletelog(log){
	    var oldchange = $('input[name=changelog]').val();
	    var newchange = '';
	    var arr_log = oldchange.split('|');
	    if (arr_log.length>0) {
	      for (var i = 0; i < arr_log.length; i++) {
	        // console.log(arr_log[i]);
	        if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){
	          newchange += arr_log[i].trim()+" | ";
	        }
	      }
	    }
	    console.log(newchange);
	    $('input[name=changelog]').val(newchange);
	    return false;
	  }
</script><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 no-padding padding-left-15">
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-10" id="search_area">
	            	<div>
	              		<input class="form-control margin-top-10 margin-bot-5" type="text" name="s_text" placeholder="Tìm kiếm bài viết">
	              		<p class="font-size-8 field-click-able">Tìm theo bộ lọc</p>
	              	</div>
	              	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phân loại</label>
	              		<select name="s_type" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_1">
	              			<option value="all" selected="" all="true">Tất cả</option>
	              			<?php if (isset($l_type) && !empty($l_type)) {
	              				foreach ($l_type as $key => $value) {
	              					echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Nhóm vấn đề</label>
	              		<select name="s_group" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_2">
	              			<option value="all" selected="" all="true">Tất cả</option>
	              			<?php if (isset($l_group) && !empty($l_group)) {
	              				foreach ($l_group as $key => $value) {
	              					echo '<option ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Chi tiết VĐ</label>
	              		<select name="s_cate" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_3">
	              			<option value="all" selected="" all="true">Tất cả</option>
	              			<?php if (isset($l_cate) && !empty($l_cate)) {
	              				foreach ($l_cate as $key => $value) {
	              					echo '<option ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Đăng bởi</label>
	              		<select name="s_createby" class="control-label col-md-8 no-border no-padding margin-left-10">
	              			<option value="" selected="">Tất cả</option>
	              			<?php if (isset($agent) && !empty($agent)) {
	              				foreach ($agent as $key => $value) {
	              					echo '<option value="'.$value['custid'].'">'.$value['custname'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label col-md-8 no-padding-right"></label>
	            		<label class="control-label col-md-8 no-padding-right"></label>
	            		<button id="btn-search" class="btn btn-primary float-right" type="button">Tìm kiếm</button>
	            		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	           	</div>
          	</div>       
	    </div>
        <div class="col-md-6 col-md-78 no-padding padding-left-5">
          	<iframe class="iframesearch" id="iframesearch" src="<?php echo base_url() ?>knowledge/search/?search="></iframe>     
        </div>
    </div>
</main><file_sep><div class="tile no-margin-bot">
	            <div class="content-title">
	            	<?php $contractid = $this->uri->segment(3);
	            		$custidCustomer = $this->uri->segment(4) ;
	            	 ?>
			        <button class="btn btn-blank insert-manual" alt="insert" onclick="addTab('<?php echo base_url().'ticket/viewInsert/'.$contractid.'/'.$custidCustomer ?>','Thêm Ticket',true)" type="button">+ Phiếu hỗ trợ  </button>
			    </div>
			    <div class="bs-component margin-top-10 tab-table-contract">
	              	<ul class="nav nav-tabs nav-user" role="tablist">
		                <li class="nav-item" role="presentation">
		                	<a class="user-tab active show" alt="crmContract01e"  data-toggle="tab" href="#tab-content-1">Thành viên</a>
		                </li>
		                <li class="nav-item" role="presentation">
		                	<a class="user-tab" data-toggle="tab" alt="crmContract01b" href="#tab-content-2">Lịch sử trạng thái</a>
		                </li>
		                <li class="nav-item" role="presentation"> 
		                	<a class="user-tab" data-toggle="tab" alt="crmContract01c" href="#tab-content-3">Công nợ/Thanh toán</a>
		                </li>
		                <li class="nav-item" role="presentation">
		                	<a class="user-tab" data-toggle="tab" alt="crmContract01d" href="#tab-content-4">KM/Quà tặng</a>
		                </li>
		                <li class="nav-item" role="presentation">
		                	<a class="user-tab" data-toggle="tab" alt="crmContract01f" href="#tab-content-5">NV Kinh doanh</a>
		                </li>
		                <li class="nav-item" role="presentation">
		                	<a class="user-tab" alt="crmContract01g"  data-toggle="tab" href="#tab-content-6">Điều chỉnh hợp đồng</a>
		                </li>
		                <li class="nav-item" role="presentation">
		                	<a class="user-tab" data-toggle="tab" alt="crmContract01h" href="#tab-content-7">Ghi chú</a>
		                </li>
	              	</ul>
	              	<div class="tab-content" id="myTabContent">
		                <div class="tab-pane fade active show" id="tab-content-1">
		                  	<div class="table-responsive" id="div-content-1" style="height: 294px;background:url(<?php echo base_url() ?>/images/ajax-loading.gif) center center no-repeat">
		                  		
				            </div>
		                </div>
		                <div class="tab-pane fade" id="tab-content-2">
		                  	<div class="table-responsive" id="div-content-2" style="height: 294px;">
		                  		<table class="table table-striped table-bordered" id="table-1-history">
                           <thead class="no-border-top">
                             <tr>
                               <th width="71px">HH/DV</th>
                         <th width="123px">Ngày</th>
                         <th width="67px">Số lượng</th>
                         <th width="65px">Giá trị</th>
                         <th width="323px">Ghi chú</th>
                             </tr>
                           </thead>
                           <tbody>
                         </table>
				            </div>
		                </div>
		                <div class="tab-pane fade" id="tab-content-3">
				              	<table class="table table-striped table-bordered" id="table-1-congno">
				              		<thead class="no-border-top">
				              			<tr>
				              				<th width="46px">Loại NK</th>
				              				<th width="19px">HĐC</th>
				              				<th width="38px">HĐMB</th>
				              				<th width="50px">Ngày NV</th>
				              				<th width="50px">Ngày ĐH</th>
				              				<th width="55px">S.tiền</th>
				              				<th width="220px">Diễn Giải</th>
				              				<th width="18px">PB</th>
				              				<th width="450px">Tiến Độ</th>
				              			</tr>
				              		</thead>
					                <tbody>
					                	
					                </tbody>
				              	</table>
		                </div>
		                <div class="tab-pane fade" id="tab-content-4">
		                  	<div class="table-responsive" id="div-content-4" style="height: 294px;">
		                  		<table class="table table-striped table-bordered" id="table-1-gift">
                           <thead class="no-border-top">
                             <tr>
                               <th width="71px">Ngày</th>
                         <th width="123px">HH/DV</th>
                         <th width="67px">Số lượng</th>
                         <th width="85px">Giá trị</th>
                               <th width="323px">Ghi chú</th>
                             </tr>
                           </thead>
                           <tbody>
                           </tbody>
                         </table>
				            </div>
		                </div>
		                <div class="tab-pane fade" id="tab-content-5">
		                  	<div class="table-responsive" id="div-content-5" style="height: 294px;">
		                  		<table class="table table-striped table-bordered" id="table-1-buss">
                           <thead class="no-border-top">
                             <tr>
                               <th width="195px">Nhân viên</th>
                               <th width="117px">Sàn</th>
                               <th width="83px">Tỉ lệ thưởng</th>
                               <th width="255px">Ghi chú</th>
                             </tr>
                           </thead>
                           <tbody>
                           </tbody>
                         </table>
				            </div>
		                </div>
		                <div class="tab-pane fade" id="tab-content-6">
				              	<div class="table-responsive" id="div-content-6" style="height: 294px;background:url(<?php echo base_url() ?>/images/ajax-loading.gif) center center no-repeat">
				              		
				              	</div>
		                </div>
		                <div class="tab-pane fade" id="tab-content-7">
		                  	<div class="table-responsive" class="div-content-7" id="div-content-7" style="height: 294px;">
				              	<table class="table table-striped table-bordered" id="table-1-notes">
                           <thead class="no-border-top">
                             <tr>
                               <th width="81px">Loại ghi chú</th>
                               <th width="93px">Ngày ghi chú</th>
                         <th width="71px">Tình trạng</th>
                         <th width="169px">Nhân viên</th>
                               <th width="235px">Nội dung</th>
                             </tr>
                           </thead>
                           <tbody>
                           </tbody>
                         </table>
				            </div>
		                </div>
	              	</div>
	            </div>
          	</div>
<div class="tile height-429 margin-top-7">
	<div>
	<button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right">Ticket</button>
			    </div>
			    <div class="bs-component margin-top-10">
          			<div class="table-responsive" style="height: 396px;" id="div-table-ticket">
		              	<table class="table table-striped table-bordered" id="table-1-ticketcontract">
                      <thead class="no-border-top">
                        <tr>
                          <th width="60px">ID</th>
                          <th width="160px">Tựa đề</th>
                          <th width="100px">Ngày yêu cầu</th>
                          <th width="112px">Người phụ trách</th>
                          <th width="110px">Cập nhật lần cuối</th>
                        </tr>
                      </thead>
                      <tbody>

                      </tbody>
                    </table>
		            </div>
	            </div>
          	</div><file_sep>
<div class="tile no-margin-bot">
        <div class="content-title">
	        <div class="div width-100per">
	          	<h5 class="flex">
	          		<i class="fa fa-lg fa-file-alt header-icon"></i>
	          		<input name="title" class="no-padding font-size-18 width-95per" placeholder="Nhập tiêu đề phiếu hỗ trợ" required="">
	          	</h5>
	        </div>
	    </div>
	    <div class="break-line margin-bot-5"></div>
	    <div class="row">
	    	<div class="col-md-12 comment-wrap">
				<div class="photo">
                    <img class="avatar" src="<?php echo($this->session->userdata('avatar')!=''?$this->session->userdata('avatar'):'https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg')?>">
				</div>
				<div class="comment-block">
					<div class="status-upload">
						<input type="hidden" name="ticketid" value="<?php echo $this->uri->segment(3)?>">
						<input type="hidden" name="contractid" value="<?php echo $this->uri->segment(4)?>">
						<textarea name="cmt" placeholder="Để lại thông tin ghi chú cho phiếu"></textarea>
					</div><!-- Status Upload  -->
					<button type="submit" class="btn btn-gray float-right margin-top-5">
						<i class="fa fa-share"></i> Ghi nhận
					</button>
				</div>
			</div>
		</div>
  	</div>
  </form><file_sep><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Customer Relationship Managerment</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Main CSS-->
    <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/main.css">
    <!-- Font-icon css-->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="<KEY>" crossorigin="anonymous">
    <!-- Customer CSS-->
    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap.min.css">
    
    <link rel="stylesheet" href="<?php echo base_url() ?>css/jquery.scrolling-tabs.css">
    <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/chosen.css">
    <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer.css">
    <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer2.css">
  </head>
  <body class="app sidebar-mini rtl sidenav-toggled">
    <!-- <?php $dayCompare = strtotime('2000-01-01T00:00:00');?> -->
    <?php echo isset($mainview) ? $mainview : ''; ?>
    

    <!-- Essential javascripts for application to work-->
    <script src="<?=base_url()?>js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

    <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.3/js/responsive.bootstrap.min.js"></script>
    <script type="text/javascript" src="http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
    <script type="text/javascript" src="//cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
    <script src="<?=base_url()?>js/popper.min.js"></script>
    <script src="<?=base_url()?>js/bootstrap.min.js"></script>
    <script src="<?=base_url()?>js/main.js"></script>
    <script src="<?=base_url()?>js/main2.js"></script>
    <script src="<?=base_url()?>js/plugins/pace.min.js"></script>
    <script src="<?=base_url()?>js/plugins/chosen.jquery.js"></script>
    <script type="text/javascript" src="<?=base_url()?>js/plugins/chart.js"></script>
    <script type="text/javascript" src="<?=base_url()?>js/plugins/sweetalert.min.js"></script>
    <script src="<?php echo base_url() ?>datetimepicker-master/build/jquery.datetimepicker.full.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>datetimepicker-master/jquery.datetimepicker.css"/>
    <script src="<?php echo base_url() ?>js/jquery.scrolling-tabs.js"></script>
    <script type="text/javascript" src="<?=base_url()?>js/plugins/jquery.validate.min.js"></script>
    <script type="text/javascript" src="<?=base_url()?>ckeditor/ckeditor.js"></script>
    <script type="text/javascript" src="<?=base_url()?>ckfinder/ckfinder.js"></script>

    <?php echo isset($script) ? $script : ''; ?>
    <?php echo isset($script2) ? $script2 : ''; ?>
    
  </body>
</html><file_sep><main class="app-content padding-5 no-padding-right">
	<form id="all-in">
    <div class="row">
        <div class="col-md-3 no-padding padding-left-15 height-1024">
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-103">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Người yêu cầu</label>
		              	<select data-placeholder="Chọn người yêu cầu..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="taskmaster">
	              			<option value="" ></option>
	              			<?php if (isset($l_cus)) {
                              	foreach ($l_cus as $cus) {
                              		if ($cus['custname']!='') {
                              			echo('<option value="'.$cus['custid'].'">'.$cus['custname'].'</option>');
                              		}
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Nhóm phụ trách</label>
	              		<select data-placeholder="Chọn nhóm phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="tic">
	              			<option value=""></option>
	              			<?php if (isset($l_agentgroup)) {
	              				foreach ($l_agentgroup as $key => $value) {
	              					echo '<option value="'.$value['groupid'].'">'.$value['groupname'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phụ trách</label>
		              	<select data-placeholder="Chọn người phụ trách..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="pic">
	              			<option value=""></option>
	              			<?php if (isset($l_age)) {
                              	foreach ($l_age as $cus) {
                              		if ($cus['custname']!='') {
                              			echo('<option value="'.$cus['custid'].'" data-group="'.$cus['groupid'].'">'.$cus['custname'].'</option>');
                              		}
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phiếu liên quan</label>
		              	<select data-placeholder="Chọn phiếu liên quan..." class="control-label col-md-8 no-border no-padding margin-left-10 my-chosen" name="ticketid">
	              			<option value=""></option>
	              			<?php if (isset($l_ticket)) {
                              	foreach ($l_ticket as $cus) {
                              		echo('<option value="'.$cus['ticketid'].'">'.$cus['ticketid'].'</option>');
                              	}
                            } ?>
	              		</select>
	            	</div>
	            	<div class="hide">
	            		<label class="control-label user-label col-md-4 no-padding">CCs</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="ccs">
	              			<option value="1">ccs</option>
	              		</select>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-102">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Độ ưu tiên</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="priority">
	              			<option value="1">Thường</option>
	              			<option value="2">Cao</option>
	              			<option value="3">Khẩn cấp</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Độ nghiêm trọng</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="severity">
	              			<option value="1">Thường</option>
	              			<option value="2">Cao</option>
	              			<option value="3">Khẩn cấp</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Trạng thái</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="status">
	              			<option value="O" selected="">Mở</option>
	              			<option value="W" disabled="">Đang xử lý</option>
	              			<option value="C" disabled="">Hoàn thành</option>
	              			<option value="X" disabled="">Hủy</option>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ghi chú T.thái</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="Nhập ghi chú..." name="statusnote">
		              	</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-101">
	            <div class="tile-body padding-right-10">
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Phân loại</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="tasktype" id="level_1">
	              			<?php if (isset($l_type)) {
	              				foreach ($l_type as $key => $value) {
	              					echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Chi tiết CV</label>
	              		<select class="control-label col-md-8 no-border no-padding margin-left-10" name="taskdetail" id="level_2">
	              			<?php if (isset($l_detail)) {
	              				foreach ($l_detail as $key => $value) {
	              					$c='';
	              					if (isset($l_type[0]['code']) && $value['ref1']!=$l_type[0]['code']) {
	              						$c="hide";
	              					}
	              					echo '<option class="'.$c.'" ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày yêu cầu</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="req_date">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Thời hạn OLA</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="ola_date">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Ngày hẹn</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="due_date">
		              	</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class=" hide">
	            		<label class="control-label user-label col-md-4 no-padding">Đếm ngược</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="số ngày">
		              	</label>
	            	</div>
	            	<div class="flex">
	            		<label class="control-label user-label col-md-4 no-padding">Hoàn thành</label>
	              		<label class="control-label col-md-8 no-padding-right">
		              		<input class="col-md-12 no-padding font-size-12" placeholder="dd-mm-yy hh:ii" name="fns_date">
		              	</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5 z-index-100 hide">
	            <div class="tile-body padding-left-right-10">
	              	<div class="row margin-top-5 height-100">
	            		<label class="control-label user-label col-md-4 no-padding">File đính kèm</label>
	              		<label class="control-label col-md-8 no-padding-right">
	              		</label>
	            	</div>
	            </div>
          	</div>
		</div>
		<div class="col-md-7 no-padding padding-left-5">
		    <div class="tile no-margin-bot">
		        <div class="content-title">
			        <div class="div  margin-bot-10 width-100per">
			          	<h5 class="flex">
			          		<i class="fa fa-lg fa-file-alt header-icon"></i>
			          		<input class="font-size-18 width-100per" type="text" required="" name="title" placeholder="Tiêu đề Công việc">
			          	</h5>
			          	<p class="header-desc field-click-able">
			          		<!-- <input class="font-size-12" type="text" name="explain" placeholder="Diễn giải"> -->
			          	</p>
			        </div>
			        <!-- <button class="btn btn-blank header-btn btn-caret" type="button"><i class="fa fa-caret-down fa-md float-right"></i></button> -->
			    </div>
			    <div class="break-line margin-bot-5"></div>
			    <div class="row">
			    	<div class="col-md-12 comment-wrap">
						<div class="photo">
							<img class="avatar" src="<?php echo($this->session->userdata('avatar'));?>">
							<input type="hidden" name="avatar" value="<?php echo($this->session->userdata('avatar'));?>">
						</div>
						<div class="comment-block">
			              	<!-- <p class="no-margin">Trả lời</p> -->
							<div class="status-upload">
								<!-- <ul class="hide">
									<li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="Text"><i class="fa fa-font"></i></a></li>
									<li><a title="" data-toggle="tooltip" data-placement="bottom" data-original-title="File"><i class="fa fa-paperclip"></i></a></li>
								</ul> -->
								<textarea name="cmt" placeholder="Nhập bất kỳ một nội dung?"></textarea>
							</div><!-- Status Upload  -->
							<button type="submit" class="btn btn-gray float-right margin-top-5 margin-bot-5">
								<i class="fa fa-share"></i> 
								Lưu
							</button>
						</div>
					</div>
				</div>
		  	</div>
		<div class="comments">
			<p>Lịch sử công việc</p>	
		</div>
	</div>
	</form>
</main><file_sep><?php var_dump($token) ?>
			<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Loại hình</label>
	              		<label class="control-label col-md-8 no-padding-right col-brk-8">Giao dịch dự án An Gia Garden</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Tình trạng</label>
	              		<label class="control-label col-md-8 no-padding-right">TLY_HDMB</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">BĐS</label>
	              		<label class="control-label col-md-8 no-padding-right">AAG-A11-12</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Sàn</label>
	              		<label class="control-label col-md-8 no-padding-right">Danh Khôi V</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày bắt đầu</label>
	              		<label class="control-label col-md-8 no-padding-right">22/05/2018</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày kết thúc</label>
	              		<label class="control-label col-md-8 no-padding-right">22/06/2018</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị HĐ</label>
	              		<label class="control-label col-md-8 no-padding-right">996,911,000</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá chưa VAT</label>
	              		<label class="control-label col-md-8 no-padding-right">910,000,235</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Thuế VAT</label>
	              		<label class="control-label col-md-8 no-padding-right">90,000,000</label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phí bảo trì</label>
	              		<label class="control-label col-md-8 no-padding-right">18,000,210</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">GT Q SDĐ</label>
	              		<label class="control-label col-md-8 no-padding-righte"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá tính VAT</label>
	              		<label class="control-label col-md-8 no-padding-righte"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phí tư vấn</label>
	              		<label class="control-label col-md-8 no-padding-righte"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị CK</label>
	              		<label class="control-label col-md-8 no-padding-righte"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị cọc</label>
	              		<label class="control-label col-md-8 no-padding-righte">30,000,000</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá chuẩn <br> chưa VAT</label>
	              		<label class="control-label col-md-8 no-padding-righte"></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Tổng GT HĐ</label>
	              		<label class="control-label col-md-8 no-padding-righte">1,017,000,000</label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Loại vay</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngân hàng</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Chứng từ NH</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Giá trị vay</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày vay</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ghi chú vay</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            	<div class="break-line margin-bot-5"></div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Số HĐ vay</label>
	              		<label class="control-label col-md-8 no-padding-right">33/HĐ-AGG-DKS</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ngày ký</label>
	              		<label class="control-label col-md-8 no-padding-right"></label>
	            	</div>
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-right-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Ghi chú</label>
	              		<label class="control-label col-md-8 no-padding-right">L/v qua email, không gửi bất cứ thư gì về nhà</label>
	            	</div>
	            </div>
          	</div><file_sep><script type="text/javascript">
	$('input[name=req_date],input[name=ola_date],input[name=due_date],input[name=fns_date]').datetimepicker({format:'Y-m-d h:i'});
	$('.my-chosen').chosen({
		width:'105%',
		disable_search_threshold: 9,
		no_results_text: "Không tìm thấy: ",
		allow_single_deselect: true
	});

	$('select[name=tic]').change(function(){
		var val = $(this).val();
		if(val){
			$('select[name=pic] option').each(function(){
				var group = $(this).attr('data-group');
				if (val==group) {$(this).prop('disabled',false);}
				else{$(this).prop('disabled',true);}
			});
			$('select[name=pic] option:disabled(not):first').prop('selected',true);
		}else{
			$('select[name=pic] option').each(function(){
				$(this).prop('disabled',false);
			});
		}
		$('.my-chosen').trigger('chosen:updated');
	});

	$('select#level_1').change(function(){
        var val = $(this).val();
        if(val){
          $('select#level_2 option').each(function(){
            var ref1 = $(this).attr('ref1');
            if (ref1==val) {
              $(this).removeClass('hide').addClass('show');
            }else{
              $(this).addClass('hide').removeClass('show');
            }
          });
        }else{
          $('select#level_2 option').each(function(){
            $(this).removeClass('hide').addClass('show');
          });
        }
        $('select#level_2 option.show:first').prop('selected',true);
    });
	
	$('#all-in').on('submit',function(){
		var form = new FormData($(this)[0]);
		var url = '<?php echo(base_url().'task/aj_api_insert');?>';
  		var error = [];
	    for (var [key, value] of form.entries()) { 
	      // console.log(key, value);
	      switch(key){
	        case 'taskmaster':
	          if (value=='') {
	            error[key] = "1";
	            parent.alertLog('Cảnh báo','Vui lòng chọn người yêu cầu.','warning');
	          }
	          break;
	        case 'tic':
	          if (value=='' && form.get('pic') == '') {
	            error[key] = '1';
	            parent.alertLog('Cảnh báo','Bạn phải nhập 1 trong 2 thông tin: Nhóm phụ trách, Người phụ trách.','warning');
	          }else if (value=='' && form.get('pic') !='') {
	            var agent = $('select[name=pic]').find('option:selected').attr('data-group');
	            console.log(agent);
	            if (agent) {form.set('tic',agent)}
	          }
	          break;
	        default: break;
	      }
	    }
	    if (!jQuery.isEmptyObject(error)) {
	      var msg = '';
	      for (let key in error){
	        msg+= error[key]+"\n";
	      }
	      console.log(msg);
	    }else{
	    	var button_insert = $(this);
	  		$(this).find('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
	  		$.ajax({
		          type: "POST",
		          url: url,
		          data:  form,
		          dataType:'json',
		          contentType: false,
		          cache: false,
		          processData:false,
		          success: function(data) {
		          	if (data.code==1) {
		        		window.location.reload();
		        		parent.alertLog('Thành công',"Đã tạo công việc",'success');
		        	}else{
		        		button_insert.find('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
		        		parent.alertLog('Cảnh báo',data.message,'warning');
		        	}
		          },
		          error: function(xhr, status, error) {
		          	parent.alertLog('Cảnh báo',"Lỗi kết nối.",'warning');
		            console.log(error);
		          }
	        });
	    }

	        return false;
	});
</script><file_sep><div class="col-md-100 no-padding padding-left-5">
	    	<div class="tile height-1024">
	            <div class="table-responsive">
	              	<table class="table" id="table-1-searchticket">
	              		<thead class="no-border-top">
	              			<tr>
	              				<th width="100">ID</th>
	              				<th width="250">Tên phiếu</th>
	              				<th width="130px">Người yêu cầu</th>
	              				<th width="130px">Người phụ trách</th>
	              				<th width="60px">Độ ưu tiên</th>
	              				<th width="50">Đến hạn</th>
	              				<th width="50">Ngày tạo</th>
	              				<!-- <th width="50">Cập nhật</th> -->
	              			</tr>
	              		</thead>
		                <tbody>
		                	<?php 
		                	if(count($result) == 0)
		                	{
		                		$result = [];
		                	}
		                	foreach ($result as $rows) { ?>
		                	<tr class="border-bot-1">
			                    <td>
			                    	<a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.$rows['custid'].'/'.$rows['idcard'] ?>','#<?php echo $rows['ticketid'] ?>')" href="#">
			                    	<span class="id-label span-warning">P</span>  #<?php echo $rows['ticketid'] ?>
			                    	</a>
			                    </td>
			                    <td>
			                    	<?php echo $rows['title'] ?>
			                    </td>
			                    <td><?php if(isset($rows['custname'])){ echo $rows['custname'];} ?></td>
			                    <td><?php if(isset($rows['agentcurrentname'])){ echo $rows['agentcurrentname'];} ?></td>
			                    <td><?php 
			                    	if ($rows['priority']==1) {echo "Thường";}
			                    	elseif ($rows['priority']==2) {echo "Cao";}
			                    	elseif ($rows['priority']==3) {echo "Khẩn cấp";}
			                    	else {echo "Không xác định";}
			                    ?></td>
			                    <td><?php echo date("d/m/Y H:i:s", strtotime($rows['duedate']));?></td>
			                    <td><?php echo date("d/m/Y H:i:s", strtotime($rows['createat']));?></td>
		                  	</tr>	
		                	<?php } ?>				  
		                </tbody>
	              	</table>
	            </div>  
	        </div>
	    </div><file_sep><main class="app-content padding-5 no-padding-right">
      <div class="row">
        <div class="col-md-3 no-padding padding-left-10 col-md-22">
          	<div class="padding-5 margin-bot-5">
	        	<div class="clearfix">
	        		<div>
		          		<h5 class="tile-title folder-head font-size-12 font-weight-500">Phân chia Công việc <a href=""><i class="fa fa-sync-alt fa-md float-right margin-top-3"></i></a></h5>
		          	</div>
	          		<ul class="nav nav-pills flex-column margin-left-5 margin-right-5">
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Công việc chưa xử lý của tôi
		                		<label class="float-right" id="_o"></label></p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Công việc đang xử lý của tôi
		                		<label class="float-right" id="_w"></label></p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Công việc đã hoàn thành
		                		<label class="float-right" id="_c"></label></p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Toàn bộ Công việc của tôi
		                		<label class="float-right" id="_a"></label></p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Toàn bộ công việc của nhóm
		                		<label class="float-right" id="_ga"></label></p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Công việc của nhóm chưa xử lý
		                		<label class="float-right" id="_go"></label></p>
		                	</a>
		                </li>
	              	</ul>
	        	</div>
	        </div>
        </div>
        <div class="col-md-8 no-padding padding-left-1 col-md-78">
          	<div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5 id="_type">Toàn bộ Công việc của tôi</h5>
			        </div>
			    </div>
		        <div class="table-responsive">
	              	<table class="table" id="table-1">
	              		<thead class="no-border">
	              			<tr>
	              				<th>ID Task</th>
	              				<th>Tựa đề</th>
	              				<th>Ngày yêu cầu</th>
	              				<th>Mức độ ưu tiên</th>
	              				<th>Trạng thái công việc</th>
	              				<th>Nhóm</th>
	              				<th>Phụ trách</th>
	              				<th>Ngày đến hạn</th>
	              			</tr>
	              		</thead>
		                <tbody>
		                	<?php
		                		$_a=0;$_o=0;$_w=0;$_c=0;$_ga=0;$_go=0;
		                		if (isset($record)) {
		                			foreach ($record as $key => $value) {
		                	?>
		                	<tr class="border-bot-1">
			                    <td width="150">
			                    	<span class="id-label span-warning">T</span> 
			                    	<a class="new_tab" onclick="addTab('<?php echo(base_url('task/detail/'.$value['taskid']));?>','<?php echo('#'.$value['taskid']);?>')" href="#">#<?php echo($value['taskid']);?></a>
			                    </td>
			                    <td width="250">
			                    	<?php echo($value['title']);?>
			                    </td>
			                    <td><?php echo date('d-m-Y',strtotime($value['requestdate']));?></td>
			                    <td>
			                    	<?php 
			                    		switch ($value['priority']) {
			                    			case '1':
			                    				echo("Thường");
			                    				break;
			                    			case '2':
			                    				echo("Cao");
			                    				break;
			                    			case '3':
			                    				echo("Khẩn cấp");
			                    				break;
			                    			default:
			                    				echo("Không xác định");
			                    				break;
			                    		}
			                    	?>
			                    </td>
			                    <td>
			                    	<?php 
			                    		if ($value['pic']==$this->session->userdata('custid')) {$_a++;}
			                    		switch ($value['status']) {
			                    			case 'O':
			                    				echo("Chờ xác nhận");
			                    				if ($value['pic']==$this->session->userdata('custid')) {$_o++;}
			                    				break;
			                    			case 'W':
			                    				echo("Đang xử lý");
			                    				if ($value['pic']==$this->session->userdata('custid')) {$_w++;}
			                    				break;
			                    			case 'C':
			                    				echo("Hoàn thành");
			                    				if ($value['pic']==$this->session->userdata('custid')) {$_c++;}
			                    				break;
			                    			case 'X':
			                    				echo("Hủy");
			                    				break;
			                    			default:
			                    				echo("Không xác định");
			                    				break;
			                    		}
			                    	?>
			                    </td>
			                    <td>
			                    	<?php 
			                    		switch ($value['tic']) {
			                    			case $this->session->userdata('groupid'):
			                    				$_ga++;
			                    				if ($value['pic']=='') {
			                    					$_go++;
			                    				}
			                    				echo $value['tic'];
			                    				break;
			                    				
			                    			default:
			                   					echo $value['tic'];
			                    				break;
			                    		}
			                    	?>
			                    </td>
			                    <td>
			                    	<?php 
			                    		echo $value['pic'];
			                    	?>
			                    </td>
			                    <td><?php echo date('d-m-Y',strtotime($value['duedate']));?></td>
		                  	</tr>					  
		                  <?php }} ?>
		                </tbody>
		                <tfoot class="no-border" status-o="<?php echo($_o);?>" status-w="<?php echo($_w);?>" status-c="<?php echo($_c);?>" status-ga="<?php echo($_ga);?>" status-go="<?php echo($_go);?>" status-a="<?php echo($_a);?>">
	              			
	              		</tfoot>
	              	</table>
	            </div>
          	</div>
        </div>
    </div>
</main><file_sep><?php

class M_data extends CI_Model
{
    var $otherdb;
    public function __construct()
    {
        parent::__construct();
        $this->otherdb = $this->load->database('sqlsvr12', TRUE);
    }
    function record_exists($record,$table)
    {
        $this->db->where($record);
        $query = $this->db->get($table);
        if ($query->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }
    }

    function key_record_exists($key,$record,$table)
    {
        $this->db->where($key,$record);
        $query = $this->db->get($table);
        if ($query->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }
    }

    function null_key($match,$key,$table)
    {
        $this->db->select($key);
        $this->db->where($match);
        $this->db->where($key.'!=','');
        $query = $this->db->get($table);
        if ($query->num_rows() > 0){
            return false;
        }
        else{
            return true;
        }
    }

    function load_field_table($table){
        return $this->db->list_fields($table);
    }

    function select_option($select,$match,$table){
        $this->db->select($select)
            ->from($table)
            ->where($match);
        $query = $this->db->get();
        return $query->result_array();
    }

    function select_row_limit($select,$match,$table,$start,$numrow){
        $this->db->select($select)
            ->from($table)
            ->where($match)
            ->limit($numrow,$start);
        $query = $this->db->get();
        return $query->result_array();
    }

    function update($match,$data,$table){
        $result = $this->db->where($match)
            ->update($table,$data);
        return $result;
    }

    function insert($data,$table)
    {
        $this->db->insert($table, $data);
        return $this->db->insert_id();
    }

    function get_all_row($table){
        $this->db->select()
            ->from($table);
        $query = $this->db->get();
        return $query->result_array();
    }
    
    function get_row($match,$table){
        $this->db->select()
            ->from($table)
            ->where($match);
        $query = $this->db->get();
        return $query->result_array();
    }

    function select_row($where,$orwhere,$table){
        $this->db->select();
        $this->db->from($table);
        $this->db->where($where);
        if(!empty($orwhere))$this->db->or_where($orwhere);
        $query = $this->db->get();
        return $query->result_array();
    }

    function user_login($username, $password, $table)
    {
        $pass = md5($<PASSWORD>);
        $sql = "SELECT * FROM $table WHERE (custid = '$username' OR email = '$username' OR telephone = '$username') AND password = <PASSWORD>'";
        $query = $this->otherdb->query($sql);
        if (!$query) {
            return $this->otherdb->error();
        }
        return $query->result_array();
    }

    public function uploadfile($file,$name){
        // var_dump($file);
        $config['upload_path'] = '../upload/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['file_name'] = $file[$name]['name'];

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

        if ($this->upload->do_upload($name)) {
          $uploadData = $this->upload->data();
          var_dump($uploadData);
          return $this->config->item('file_upload_url').$uploadData['file_name'];
          echo "file upload success!! ";
        } else{
          var_dump($this->upload->display_errors());
          return false;
        }
    }
    public function array_to_string($array,$index_key,$index_value){
        $string = '';
        // var_dump($array);
        foreach ($array as $key => $value) {
            $string.=$value[$index_key].':'.$value[$index_value].';';
        }
        return substr($string, 0, strlen($string)-1);
    }

    public function count_row($select,$where,$table,$join,$order_by,$like,$or_like){
        $this->db->select($select);
        $this->db->from($table);
        if(!empty($join)){
            foreach ($join as $key => $value) {
                $this->db->join($value['table'],$value['match']);       
            }
        }
        $this->db->where($where);
        if(!empty($like))$this->db->like($like);
        if(!empty($or_like))$this->db->or_like($or_like);
        $this->db->order_by($order_by['colname'],$order_by['typesort']);
        $query = $this->db->get();
        return $query->num_rows();
    }

    function select_row_option($select,$where,$table,$join,$limit,$order_by,$like,$or_like){
        $this->db->select($select);
        $this->db->from($table);
        if(!empty($join)){
            foreach ($join as $key => $value) {
                $this->db->join($value['table'],$value['match']);       
            }
        }
        $this->db->where($where);
        if(!empty($like))$this->db->like($like);
        if(!empty($or_like))$this->db->or_like($or_like);
        if(!empty($order_by))$this->db->order_by($order_by['colname'],$order_by['typesort']);
        if(!empty($limit))$this->db->limit($limit['numrow'],$limit['start']);
        $query = $this->db->get();
        return $query->result_array();
    }

    function toPermission($array){
        $arr = [];
        if (!empty($array)) {
            for ($i=0; $i < count($array); $i++) { 
                $arr[$array[$i]['to_table']][$array[$i]['id_rights']] = $array[$i]['active'];
            }
        }
        return $arr;
    }

    function trans_insert_baohiem($data1,$data2){
        $this->db->trans_start();

            $id = $this->insert($data2,'customer');
            var_dump($id);
            $data1['id_customer'] = $id;
            $this->insert($data1,'pre_traff');

        if($this->db->trans_status() === FALSE){
           $this->db->trans_rollback();
           return false;
        }else{
           $this->db->trans_complete();
           return true;
        }
    }

    function trans_insert_user($user_acc,$user_info){
        $this->db->trans_start();
            $id = $this->insert($user_info,'user_info');
            $user_acc['user_info'] = $id;
           $this->insert($user_acc,'users');
        if($this->db->trans_status() === FALSE){
           $this->db->trans_rollback();
           return false;
        }else{
           $this->db->trans_complete();
           return true;
        }
    }

    public function send_sms($phone,$text){
        try {
            
            $client = new SoapClient('http://g3g4.vn:8008/smsws/services/SendMT?wsdl');
            $content = array(
                'username' => 'globalsafe1', 
                'password' => '<PASSWORD>', 
                'receiver' => $phone, 
                'content' => $text, 
                'loaisp' => '2', 
                'brandname' => 'GLOBALSAFE', 
                'target' => '123456', 
            );
            $quote = $client->sendSMS($content);
            return $quote->return;
        
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

<file_sep><div class="tile height-1024 p-0 padding-5">
	          	<div>
	          		<h5 class="tile-title folder-head"><i class="fa fa-user fa-fw"></i> Người dùng</h5>
	          	</div>
	            <div class="tile-body padding-left-right-10 fon-size-14">
	              	<ul class="nav nav-pills flex-column mail-nav">
		                <li>
		                	<a style="cursor: pointer;" class="dropdown-item no-padding margin-top-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>setting/viewUser')">
		                		<p class="no-padding no-margin padding-left-right-10"> Người dùng</p>
		                	</a>
		                </li>
			            <li>
		                	<a style="cursor: pointer;" class="dropdown-item no-padding margin-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>groupuser')">
		                		<p class="no-padding no-margin padding-left-right-10"> Nhóm người dùng</p>
		                	</a>
		                </li>
		                <li>
		                	<a style="cursor: pointer;" class="dropdown-item no-padding margin-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>groupuser/fielduser')">
		                		<p class="no-padding no-margin padding-left-right-10"> Trường dữ liệu người dùng</p>
		                	</a>
		                </li>
	              	</ul>
	            </div>
	            <div>
	          		<h5 class="tile-title folder-head"><i class="fa fa-file-alt fa-fw"></i> Phiếu hỗ trợ</h5>
	          	</div>
	            <div class="tile-body padding-left-right-10 fon-size-14">
	              	<ul class="nav nav-pills flex-column mail-nav">
		                <li>
		                	<a  style="cursor: pointer;" class="dropdown-item no-padding margin-bot-10 border-radius-3" onclick="clickChangeIframe('<?php echo base_url()?>groupuser/fieldticket')">
		                		<p class="no-padding no-margin padding-left-right-10"> Trường dữ liệu Phiếu hỗ trợ</p>
		                	</a>
		                </li>
			            <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Mẫu phiếu hỗ trợ</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Thẻ (Tags)</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Macros</p>
		                	</a>
		                </li>
	              	</ul>
	            </div>

	            <div>
	          		<h5 class="tile-title folder-head"><i class="fas fa-database"></i> DataSource</h5>
	          	</div>
	            <div class="tile-body padding-left-right-10 fon-size-14">
	              	<ul class="nav nav-pills flex-column mail-nav">
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>typework','Loại công việc')">
		                		<p class="no-padding no-margin padding-left-right-10"> Loại công việc</p>
		                	</a>
		                </li>
			            <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>detailwork','Chi tiết công việc')">
		                		<p class="no-padding no-margin padding-left-right-10"> Chi tiết công việc</p>
		                	</a>
		                </li>

		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>datastage','Giai đoạn')">
		                		<p class="no-padding no-margin padding-left-right-10"> Giai đoạn</p>
		                	</a>
		                </li>

		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>issuetype','Phân loại')">
		                		<p class="no-padding no-margin padding-left-right-10"> Phân loại</p>
		                	</a>
		                </li>

		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>issuegroup','Nhóm vấn đề')">
		                		<p class="no-padding no-margin padding-left-right-10"> Nhóm vấn đề</p>
		                	</a>
		                </li>

		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>issuedetail','Chi tiết vấn đề')">
		                		<p class="no-padding no-margin padding-left-right-10"> Chi tiết vấn đề</p>
		                	</a>
		                </li>


	              	</ul>
	            </div>

	            <div>
	          		<h5 class="tile-title folder-head"><i class="fa fa-signal fa-fw"></i> Kênh tương tác</h5>
	          	</div>
	            <div class="tile-body padding-left-right-10 fon-size-14">
	              	<ul class="nav nav-pills flex-column mail-nav">
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> E-mail</p>
		                	</a>
		                </li>
			            <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Phone</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10"> Chat</p>
		                	</a>
		                </li>
	              	</ul>
	            </div>
	            <div>
	          		<h5 class="tile-title folder-head"><i class="fa fa-briefcase fa-fw"></i>Nghiệp vụ</h5>
	          	</div>
	            <div class="tile-body padding-left-right-10 fon-size-14">
	              	<ul class="nav nav-pills flex-column mail-nav">
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Cam kết dịch vụ (SLA)</p>
		                	</a>
		                </li>
			            <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Phân chia phiếu</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Triggers</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Automations</p>
		                	</a>
		                </li>
	              	</ul>
	            </div>
	            <div>
	          		<h5 class="tile-title folder-head"><i class="fa fa-sliders-h fa-fw"></i>Cài đặt</h5>
	          	</div>
	            <div class="tile-body padding-left-right-10 fon-size-14">
	              	<ul class="nav nav-pills flex-column mail-nav">
		                <li>
		                	<a class="dropdown-item no-padding margin-top-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Tài khoản</p>
		                	</a>
		                </li>
			            <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Bảo mật</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">Phiếu hỗ trợ</p>
		                	</a>
		                </li>
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#">
		                		<p class="no-padding no-margin padding-left-right-10">CV CSKH</p>
		                	</a>
		                </li>
		                
		                <li>
		                	<a class="dropdown-item no-padding margin-bot-10 border-radius-3" href="#" onclick="addTab('<?php echo base_url() ?>queue','Hàng chờ')">
		                		<p class="no-padding no-margin padding-left-right-10"> Hàng chờ</p>
		                	</a>
		                </li>
	              	</ul>
	            </div>
          	</div><file_sep><script type="text/javascript">
	$(document).ready(function(){
		$('#table-1-knowledge').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
              }
            },
            "columns": [
              { "width": "18%" },
              { "width": "17%" },
              { "width": "10%" },
              { "width": "15%" },
              { "width": "10%" },
              { "width": "10%" },
              { "width": "10%" }
            ],
            "info":     false,
            "ordering": false,
            "searching": false,
            "scrollY":        "100%",
            "iDisplayLength": 15,
            "scrollX":        true,
            "bLengthChange": false,
            "scrollCollapse": true
          }).columns.adjust().draw();

    var tickettype = $('select#level_1').val();
    if (tickettype!='') {
      $('select#level_2 option').each(function(){
        var ref1 = $(this).attr('ref1');
        if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');}
        else{$(this).addClass('hide').removeClass('show');}
      });
      $('select#level_2 option.show:first').prop('selected',true);
    }

    var groupid = $('select#level_2').val();
    if (groupid!='') {
      $('select#level_3 option').each(function(){
        var ref2 = $(this).attr('ref2');
        if (ref2==groupid) {$(this).removeClass('hide').addClass('show');}
        else{$(this).addClass('hide').removeClass('show');}
      });
      $('select#level_3 option.show:first').prop('selected',true);
    }
      
    $('select#level_1').change(function(){
        var val = $(this).val();
        $('select#level_2 option:first').prop('selected',true);
        $('select#level_3 option:first').prop('selected',true);
        if(val){
          $('select#level_2 option, select#level_3 option').each(function(){
            var ref1 = $(this).attr('ref1');
            var all = $(this).attr('all');
            if (ref1==val || all || val=="all") {
              $(this).removeClass('hide');
            }else{
              $(this).addClass('hide');
            }
          });
        }else{
          $('select#level_2 option, select#level_3 option').each(function(){
            var all = $(this).attr('all');
            if (!all) {
              $(this).removeClass('hide');
            }
          });
        }
    });
    $('select#level_2').change(function(){
        var val = $(this).val();
        var all = $(this).find('option:selected').attr('all');
        var ref1 = $('select#level_1').val();
        $('select#level_3 option:first').prop('selected',true);
        if(val){
          $('select#level_3 option').each(function(){
            var ref2 = $(this).attr('ref2');
            var all = $(this).attr('all');
            if (ref2==val || all || val=="all") {
              $(this).removeClass('hide');
            }else{
              $(this).addClass('hide');
            }
          });
        }else if(all){
            $('select#level_3 option').each(function(){
            var val1 = $(this).attr('ref1');
            var all = $(this).attr('all');
            if (ref1==val1 || all || val=='all') {
              $(this).removeClass('hide');
            }else{
              $(this).addClass('hide');
            }
          });
        }else{
          $(this).removeClass('hide');
        }
    });
	});

	$('#btn-search').click(function(){
		// alert($(this).attr('id'));
		var text = $('#search_area input[name="s_text"]').val();
		var group = $('#search_area select[name="s_group"]').val();
		var cate = $('#search_area select[name="s_cate"]').val();
		var type = $('#search_area select[name="s_type"]').val();
		var createby = $('#search_area select[name="s_createby"]').val();
		if (text.length>50) {
			alert('Không được nhập quá 50 ký tự.');
		}else{
		document.getElementById('iframesearch').src = "<?php echo base_url().'knowledge/search/?groupid='?>"+group+"&categoryid="+cate+"&tickettype="+type+"&createby="+createby+"&search="+text;
		}
	});
</script><file_sep><script type="text/javascript">
	$(document).ready(function(){
    $('#tableUser').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
              }
            },
             "order": false,
            "info":     false,
            "searching": false,
            "scrollY":        "100%",
            "scrollX":        true,
            "bLengthChange": false,
            "scrollCollapse": true
          }).columns.adjust().draw();

		$('#keyword').keypress(function(e1){
		   if(e1.keyCode==13){          // if user is hitting enter
		       search();
		   }
		  });
		
	});
	function search() {
		$('#loading').attr('style', 'display: initial;width: 30px; height: 30px;');
		var keyword = $('#keyword').val();
		$.ajax({
          url: '<?php echo base_url()?>setting/searchUser',
          type: 'POST',
          dataType: 'JSON',
          data: {keyword : keyword},
        })
        .done(function(data) {
        	$('#loading').attr('style', 'display:none');
        	var data_html = '';
        	for(var i = 0;i<data.data.length;i++)
        	{
        		var custid = data.data[i].custid;
        		var idcard = data.data[i].idcard;
        		var roleid = data.data[i].roleid;
        		var url1 = '<?php echo base_url() ?>user/detail/?cusid='+custid+'&idcard='+idcard+'&roleid='+roleid;
        		var url = "'"+url1+"'";
        		var custname = "'"+data.data[i].custname+"'";
        		data_html+=
        		'<tr>\
	      			<td width="40px">\
	            	<img class="user-avatar" src="'+data.data[i].avatar+'" alt="User Image">\
	            </td>\
	            <td width="252px">\
	            	<a class="user-name" style="cursor: pointer;" onclick="addTab('+url+','+custname+')">'+data.data[i].custname+'</a>\
	            	<p class="">'+data.data[i].groupname+'</p>\
	            </td>\
	            <td width="229px">'+data.data[i].telephone+'</td>\
	            <td  width="218px">'+data.data[i].email+'</td>\
	          </tr>';
        	}
          $('.content-search').html('<div class="table-responsive">\
	              <table class="table" id="tableUser">\
                <thead>\
                    <tr>\
                    <th></th>\
                    <th>Họ tên</th>\
                    <th>SĐT</th>\
                    <th>Email</th>\
                </tr>\
                  </thead>\
	                <tbody>'+data_html+'\
	                </tbody>\
	              </table>\
	            </div>');

           $('#tableUser').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
              }
            },
             "order": false,
            "info":     false,
            "searching": false,
            "scrollY":        "100%",
            "scrollX":        true,
            "bLengthChange": false,
            "scrollCollapse": true
          }).columns.adjust().draw();
        })
        .fail(function() {
            console.log('error');
            $('#loading').attr('style', 'display:none');
        })	
	}

	function searchRoleid(roleid) {
		$('#loading').attr('style', 'display: initial;width: 30px; height: 30px;');
		var keyword = '';
		$.ajax({
          url: '<?php echo base_url()?>setting/searchUser',
          type: 'POST',
          dataType: 'JSON',
          data: {keyword : keyword},
        })
        .done(function(data) {
        	$('#loading').attr('style', 'display:none');
        	var data_html = '';
        	for(var i = 0;i<data.data.length;i++)
        	{

        		if(data.data[i].roleid == roleid)
        		{
        			var custid = data.data[i].custid;
	        		var idcard = data.data[i].idcard;
	        		var url1 = '<?php echo base_url() ?>user/detail/?cusid='+custid+'&idcard='+idcard+'&roleid='+roleid;
	        		var url = "'"+url1+"'";
	        		var custname = "'"+data.data[i].custname+"'";
        		data_html+=
        		'<tr>\
	      			<td width="40px">\
	            	<img class="user-avatar" src="'+data.data[i].avatar+'" alt="User Image">\
	            </td>\
	            <td width="252px">\
	            	<a class="user-name" style="cursor: pointer;" onclick="addTab('+url+','+custname+')">'+data.data[i].custname+'</a>\
	            	<p class="">'+data.data[i].groupname+'</p>\
	            </td>\
	            <td width="229px">'+data.data[i].telephone+'</td>\
	            <td width="218px">'+data.data[i].email+'</td>\
	          </tr>';
	          	}
        	}
          $('.content-search').html('<div class="table-responsive">\
	              <table class="table" id="tableUser">\
                <thead>\
                    <tr>\
                    <th></th>\
                    <th>Họ tên</th>\
                    <th>SĐT</th>\
                    <th>Email</th>\
                </tr>\
                  </thead>\
	                <tbody>'+data_html+'\
	                </tbody>\
	              </table>\
	            </div>');
          $('#tableUser').DataTable({
             "paging":   true,
             "language": {
              "paginate": {
                "previous": "Trước",
                "next":"Sau"
              }
            },
             "order": false,
            "info":     false,
            "searching": false,
            "scrollY":        "100%",
            "bLengthChange": false,
            "scrollX":        true,
            "scrollCollapse": true
          }).columns.adjust().draw();
        })
        .fail(function() {
            alert("Lỗi hệ thống, vui lòng liên hệ admin");
        })	
	}
    function clickChangeIframe(src)
    {
        document.getElementById('iframesetting').src = src;
    }
	
</script><file_sep><div class="timeline">
				<?php 
				$array = array("gray","red","green","yellow");
				$i = 0;
				if(count($history)>0)
				{
				foreach ($history as $value) { 
					if($i >3)
					{
						$i=0;
					}
					?>
			  	<div class="entry">
				    <div class="title <?php echo $array[$i] ?>">
				      	<p class="time-detail"><?php 
				      	if($value['createdat'] !=null)
				      	{
				      	echo date("G:i:s", strtotime($value['createdat']));} ?></p>
				      	<p class="date-detail"><?php 
				      	if($value['createdat'] !=null)
				      	{
				      		echo date("d/m/Y", strtotime($value['createdat']));} ?></p>
				    </div>
				    <div class="body">
				      	<p class="margin-bot-3"><?php echo $value['action'] ?></p>
				        <p class="no-margin-bot">
				        	<?php 
					        	$log_type = $value['typelog'];
					        	if($log_type=='T'){
					        		$link = base_url()."ticket/detail/".$value['ticketid'];
					        ?>
					        		<a href="#" onclick="parent.addTab('<?php echo $link;?>','#<?php echo $value['ticketid'] ?>')">#<?php echo $value['ticketid'] ?></a><br>
					        <?php
					        		echo $value['changelog'];
					        	}
				        	

				        	$data = json_decode($value['changelog'],true);
				        	if(count($data)>0)
				        	{

				        	$labelaction = '';
				        foreach ($data as $key => $value) {
				        	if($key == "custname")
				        	{
				        		echo "Họ và tên: ".$value."<br />";
				        	}
				        	if($key == "gender")
				        	{
				        		echo "Giới tính: ".switchGender($value)."<br />";
				        	}
				        	if($key == "telephone")
				        	{
				        		echo "Số điện thoại: ".$value."<br />";
				        	}
				        	if($key == "fullbirthday")
				        	{
				        		echo "Ngày Sinh: ".$value."<br />";
				        	}
				        	if($key == "email")
				        	{
				        		echo "Email: ".$value."<br />";
				        	}
				        	if($key == "comments")
				        	{
				        		echo "Ghi chú: ".$value."<br />";
				        	}
				        	if($key == "roleid")
				        	{
				        		echo "Phân quyền: ".switchRoleId($value,$role_list)."<br />";
				        	}
				        	if($key == "groupid")
				        	{
				        		echo "Nhóm: ".switchGroupId($value,$group_list)."<br />";
				        	}
				        	if($key == "extinfo")
				        	{
				        		echo switchExtField($value,$list_ext);
				        	}
				        	if($key == "idcard")
				        	{
				        		echo "CMND: ".$value."<br />";
				        	}
				        	if($key == "issueddate")
				        	{
				        		echo "Ngày cấp: ".$value."<br />";
				        	}

				        	if($key == "issuedplace")
				        	{
				        		echo "Nơi cấp: ".$value."<br />";
				        	}

				        	if($key == "action")
				        	{
				        		if($value == "deletephone")
				        		{
				        			$labelaction = "Xoá SĐT: ";
				        		}
				        		else
				        		{
				        			$labelaction = "Xoá Email: ";
				        		}
				        	}
				        	if($key == "telephonelist")
				        	{
				        		foreach ($value as $key1 => $data1) {
				        			if(count($data) == 2)
					        		{
					        			echo "Xóa SĐT: ".$data1;
					        			break;
					        		}
					        		else
					        		{
					        			echo "Thêm SDT: ".$labelaction.=$data1;
				        			}
				        		}
				        	}
				        	if($key == "emaillist")
				        	{
				        		foreach ($value as $key1 => $data1) {
				        			if(count($data) == 2)
					        		{
					        			echo "Xóa Email: ".$data1;
					        			break;
					        		}
					        		else
					        		{
					        			echo "Thêm Email: ".$labelaction.=$data1;
				        			}
				        		}
				        	}
				        	/*
				        	if($key == "emaillist")
				        	{
				        		foreach ($value as $key1 => $data1) {
				        			$labelaction = $data1;
				        		}
				        		if(count($data) == 2)
				        		{
				        			echo "Thêm Email: ".$labelaction;
				        		}
				        	}
				        	*/
				        	if($key == "city")
				        	{
				        		echo "Thành phố: ".$value."<br />" ;
				        	}
				        	if($key == "district")
				        	{
				        		echo "Quận/ Huyện: ".$value."<br />" ;
				        	}
				        	if($key == "ward")
				        	{
				        		echo "Phường/ Xã: ".$value."<br />" ;
				        	}
				        	if($key == "street")
				        	{
				        		echo "Đường: ".$value."<br />" ;
				        	}
				        	if($key == "address")
				        	{
				        		echo "Số nhà: ".$value."<br />" ;
				        	}
				        	if($key == "label")
				        	{
				        		echo "Nhãn địa chỉ: ".$value."<br />" ;
				        	}
				        }
				        }
				         ?></p>
				    </div>
			  	</div>
			  	 <?php	$i++;}} ?>
			</div>

<?php 
function switchGender($value1)
{
	if($value1 == "M")
	{
		return "Nam";
	}
	else{
		return "Nữ";
	}
}
function switchRoleId($value1,$role_list)
{
	if(count($role_list)>0)
	{
	foreach ($role_list as $key => $value) {
		if($value1 == $key)
		{
			return $value;
		}
	}
	}
}
function switchGroupId($value1,$group_list)
{
	if(count($group_list)>0){
		foreach ($group_list as  $value) {
			if($value1 == $value['groupid'])
			{
				return $value['groupname'];
			}
		}
	}
} 
function switchExtField($extfields,$list_ext)
{
	$text = "";

	if(count($extfields)>0)
	{
		foreach ($extfields as $key => $value) {
			foreach ($list_ext as  $value1) {
				if($key == $value1['fieldcode'])
				{
					$text.= $value1['fieldname'].": ".$value."</br>";
				}
			}
		}
	}
	return $text;
}
?><file_sep><main class="app-content col-md-100 no-padding no-margin">
    		<div class="tile height-1024">
          		<div class="offset-10 col-md-2 margin-bot-10">
          			<?php $link =  base_url().'knowledge/detail';
          					$title = 'Thêm Knowledge';
          			?>
			    			<button onclick="addTab('<?php echo $link?>','<?php echo $title ?>')"  class="btn btn-primary float-right" id="ck-edit" type="button"> Thêm mới </button>
			    		</div>
	            <div class="table-responsive">
	              	<table class="table" id="table-1-knowledge">
	              		<thead class="no-border-top">
	              			<tr>
	              				<th>Chủ đề</th>
	              				<th>Phân loại</th>
	              				<th width="100">Nhóm vấn đề</th>
	              				<th>Chi tiết VĐ</th>
	              				
	              				<th>Đăng bởi</th>
	              				<th>Ngày đăng</th>
	              				<th>Trạng thái</th>
	              			</tr>
	              		</thead>
		                <tbody>
		                	<?php if(!empty($news)){ foreach ($news as $key => $value) { ?>
		                		<tr class="border-bot-1">

			                    <?php $linkUpdate=  base_url().'knowledge/detail/edit/'.$value['id'];
			                    	$titleUpdate = 'Cập nhật Knowledge '.$value['id']; ?>
			                    <td><a onclick="addTab('<?php echo $linkUpdate ?>','<?php echo $titleUpdate ?>')" href="#"><?php echo $value['title'] ?></a></td>

			                    <td>
			                    	
			                    	<?php if (isset($l_type) && !empty($l_type)) {
		                				$exi = 'Không xác định';
		                				foreach ($l_type as $k => $v) {
		                					if ($value['tickettype']==$v['code']) {
		                						$exi = $v['name'];
		                						break;
		                					}
		                				}
		                				echo $exi;
		                			} ?>
			                    </td>
		                		<td>
		                			<?php if (isset($l_group) && !empty($l_group)) {
		                				$exi = 'Không xác định';
		                				foreach ($l_group as $k => $v) {
		                					if ($value['groupid']==$v['code']) {
		                						$exi = $v['name'];
		                						break;
		                					}
		                				}
		                				echo $exi;
		                			} ?>
			                    </td>
			                    <td>
		                			<?php 
			                    	if (isset($l_cate) && !empty($l_cate)) {
		                				$exi = 'Không xác định';
		                				foreach ($l_cate as $k => $v) {
		                					if ($value['categoryid']==$v['code']) {
		                						$exi = $v['name'];
		                						break;
		                					}
		                				}
		                				echo $exi;
		                			} ?>
			                    </td>
			                    
			                    <td><?php echo($value['custname']); ?></td>
			                    <td><?php echo date("d-m-Y", strtotime($value['createdat'])); ?></td>
			                    <td><?php if($value['hidden']=='0')echo "Đang hoạt động"; else echo "Ngưng hoạt động"; ?></td>
			                    <!-- <td><?php echo($value['hidden']); ?></td> -->
		                  	</tr>
		                	<?php }} else echo("the data is empty"); ?>
		                </tbody>
	              	</table>
	            </div>
          	</div>   
</main><file_sep><?php 
      $type = "D"; 
      $queue = $this->input->get('queue');
?>
<div class="tile height-1024">
	            <div class="content-title">
			        <div class="div">
			          <h5>Danh sách hàng chờ: <?php echo nameTitle($queue) ?></h5>
			        </div>
			    </div>
				    <div style="float: right;">
						<button <?php if($type == 'T'){echo 'hidden';} ?> type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right" data-toggle="modal" data-target="#myModal">Thêm</button>
					</div>
			    
				<div class="bs-component" style="margin-top: 55px">
					<?php if ($type == 'T'){
						echo '<div class="component-fields">
				                    <i class="fas fa-align-justify"></i> 
				                    <span class="title_tab" style="padding-left: 6px">Text</span>
							</div>';
					} ?>
					<?php if(count($extension)>0){
						foreach ($extension as $value) { ?>
							<div class="component-fields" style="">
				                    <i class="fas fa-align-justify" style=""></i> 
				                    <span class="title_tab" style="padding-left: 6px;
                            "><?php echo $value['extension']." (Ưu tiên: ".$value['status'].")" ?></span>
				                     <!-- <a class="user-name" style="cursor: pointer;float: right; margin-right: 15px" data-toggle="modal" data-target="#modalUpdate" data-telephone="<?php echo $value['extension'] ?>" data-queue="<?php echo $value['queuecode'] ?>" data-status="<?php echo $value['status'] ?>"><i class="fas fa-edit"></i></a> -->

                             <a class="user-name" style="cursor: pointer;float: right;" data-toggle="modal" data-target="#modalDelete" data-telephone="<?php echo $value['extension'] ?>" data-queue="<?php echo $value['queuecode'] ?>"><i class="fas fa-sign-out-alt"></i></a>
							</div>
						<?php }}?>
	            </div>
          	</div>
 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document" style="margin-top: 5%">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Thêm Extension:</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
            <div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hàng đợi:</label>
            <select name="ref1_insert" onchange="getGroup(this,'ref2_insert')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="queue_login">
              <option value="<?php echo $queue ?>" selected=""><?php echo nameTitle($queue) ?></option>
              
            </select>
        </div>

        <div class="form-group extendbottom">
                <label class="control-label user-label col-md-3 col-sm-3 no-padding">Số điện thoại: </label>
                <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <input type="text" class="col-md-12 no-padding font-size-12" name="telephone_login" id="telephone_login" placeholder="-SĐT"></label>
        </div>

        <div class="form-group extendbottom">
                <label class="control-label user-label col-md-3 col-sm-3 no-padding">Độ ưu tiên: </label>
                <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <input type="text" class="col-md-12 no-padding font-size-12" name="status_insert" id="status_insert" placeholder="-Độ ưu tiên"></label>
        </div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="loginButton()" class="btn btn-primary">Thêm</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 7%" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Đăng Xuất Hàng chờ</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <p class="bg-danger" style="padding: 10px;color: #FFF;" >Bạn có chắc muốn đăng xuất không?</p>
        <input type="hidden" id="telephone" name="telephone">
        <input type="hidden" id="queue" name="queue">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="logoutButton()" class="btn btn-danger">Đăng xuất</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modalUpdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" style="margin-top: 7%" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Sửa Option</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
          <div class="">
        <label class="control-label user-label col-md-3 col-sm-3 no-padding">Hàng đợi:</label>
            <select name="ref1_insert" onchange="getGroup(this,'ref2_insert')" class="control-label col-md-8 col-sm-8 no-border no-padding" id="queue_login">
              <option value="<?php echo $queue ?>" selected=""><?php echo nameTitle($queue) ?></option>
              
            </select>
        </div>

        <div class="form-group extendbottom">
                <label class="control-label user-label col-md-3 col-sm-3 no-padding">Số điện thoại: </label>
                <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <input type="text" class="col-md-12 no-padding font-size-12" name="telephone_update" id="telephone_update" placeholder="-SĐT"></label>
        </div>

        <div class="form-group extendbottom">
                <label class="control-label user-label col-md-3 col-sm-3 no-padding">Độ ưu tiên: </label>
                <label class="control-label col-md-8 col-sm-8 no-padding-right no-padding-left">
                <input type="text" class="col-md-12 no-padding font-size-12" name="status_update" id="status_update" placeholder="-Độ ưu tiên"></label>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
        <button type="button" onclick="updateButton()" class="btn btn-primary">Sửa</button>
      </div>
    </div>
  </div>
</div>
<?php function nameTitle($value)
{
    if($value == "21114")
    {
      return "Chuyển nhượng hợp đồng";
    }
    else if($value == "21115")
    {
      return "Thanh toán vay";
    }
    else if($value == "21116")
    {
      return "Khác";
    }
     else if($value == "21121")
    {
      return "Tiếng Anh";
    }
} ?><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 padding-left-15">
          	<?php echo isset($left)?$left:'' ?>
        </div>

        <div class="col-md-7 padding-left-1">
          	<?php echo isset($center)?$center:'' ?>
        </div>
        <div class="col-md-2 col-md-18 padding-left-5">
        	
        </div>
    </div>
</main><file_sep><script src="<?php echo base_url('callevent/node_modules/socket.io-client/dist/socket.io.js');?>"></script>
<script>

    var timer=null,record=null;
    $(document).ready(function(){

      var socket = io.connect( 'http://'+window.location.hostname+':3000' ,{ query: "custid=C0001<?php echo($this->session->userdata('telephone')!=null?'&phone='.$this->session->userdata('telephone'):'')?>" });
      socket.on('connect', function () {
        clientid = socket.id;
        $('#phone-chat').attr('extension',"<?php echo($this->session->userdata('telephone')!=null?$this->session->userdata('telephone'):'')?>");
        // socket.emit('new_client', { 
        //     name: getRandomName(),
        //     phone: getRandomNumber(),
        //     id: clientid
        //   });
      });
      socket.on( 'new_connect', function( data ) {
  
          console.log(data);

      });

      socket.on('object_event',function(data){
        // console.log(data);
      });

      // $.post(
      //   "http://"+window.location.hostname+":3000/call",
      //   {
      //     name: getRandomName(),
      //     phone: getRandomNumber()
      //   },
      //   function(data){
      //     console.log(data);
      // });

      function getRandomName() {
            const arr = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"];
            return arr[Math.floor(Math.random() * arr.length)];
        }

        function getRandomNumber() {
            const arr = ["2455","7895","1230","4587","7849","2368","7842","8953","7412","5687"];
            return arr[Math.floor(Math.random() * arr.length)];
        }

      socket.on( 'disconnect_client', function( data ) {
  
          console.log(data);
          $("#node-view").find('button[id="'+data.client+'"]').remove();
      });

      socket.on( 'new_client', function( data ) {
  
          console.log(data);
          $("#node-view").append('<button class="btn btn-primary btn-call" type="button" id="'+data.id+'">'+data.name+' - '+data.phone+'</button> ');
      });
      socket.on('e_ringing',function(data){
            console.log(data);
            // save_call_log("call","ringing",data);
            var phone = data.fromnumber;
            var p_data = {};
            $('#phone-chat').css('display','block');
            hideScreen(0,p_data);
            start_timer('#has-call-pad #c-time');
            p_data['phone'] = phone;
            p_data['channel'] = data.channel;
            $.ajax({
                    type: "GET",
                    url: 'http://'+window.location.hostname+'/api/get_infor_user/'+phone,
                    dataType: "json",
                    success: function(data){
                      if (data.data!=null) {
                        var rec = data.data[0];
                        console.log(rec);
                        p_data['avatar'] = rec.avatar;
                        p_data['custname'] = rec.custname;
                        p_data['custid'] = rec.custid;
                        p_data['idcard'] = rec.idcard;
                        p_data['phone_act'] = 'newtab';
                        hideScreen(0,p_data);
                      }else{
                        p_data['avatar'] = null;
                        p_data['custname'] = "---";
                        p_data['phone_act'] = 'newuser';
                        hideScreen(0,p_data);
                      }
                    },error: function(xhr, status, error) {
                      console.log(error);
                      p_data['avatar'] = null;
                      p_data['custname'] = "---";
                      p_data['phone_act'] = 'newuser';
                      hideScreen(0,p_data);
                    }
                  });
        });
      socket.on('e_answered',function(data){

            console.log('e_answered');
            console.log(data);
            // save_call_log("call","answered",data);

            var phone = data.fromnumber;
            var callrefid = data.callrefid;
            var p_data = {};
            var act = $('#has-call-pad #c-number').attr('act');
            var custid = $('#has-call-pad #c-number').attr('custid');
            var cname = $('#has-call-pad #c-name').html();
            var idcard = $('#has-call-pad #c-name').attr('idcard');
            console.log(act+'-'+custid+'-'+phone+'-'+cname+'-'+idcard);


            p_data['phone'] = phone;
            p_data['channel'] = data.channel;
            p_data['custid'] = custid;

            $('#phone-chat').css('display','block');
            hideScreen(1,p_data);
            start_record('#has-call-pad #c-record');
            


            if (act) {
              if (act=='newtab'&&custid) {
                addTab('<?php echo base_url().'user/detail/?cusid='?>'+custid+'&idcard='+idcard+'&roleid=3',cname);
                $.ajax({
                  type: "POST",
                  url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_ticket/',
                  dataType: "json",
                  data:{
                    ticketchanel:2,
                    agentcreated:'<?php echo($this->session->userdata('custid'))?>',
                    custid:custid,
                    priority:1,
                    phone:phone,
                    callrefid:callrefid,
                    queue:data.queue
                  },
                  success: function(data){
                    console.log(data);
                    p_data['ticket'] = data.data;
                    hideScreen(1,p_data);
                    showTicketTab(data.data);
                  },error: function(xhr, status, error) {
                    console.log(error);
                    alert(error);
                  }
                });
              }else if(act=='newuser'){
                $.ajax({
                        type: "GET",
                        url: 'http://'+window.location.hostname+'/api/aj_tvc_isrt_user/'+phone,
                        dataType: "json",
                        success: function(data){
                          addTab('<?php echo base_url().'user/detail/?cusid='?>'+data.custid+'&idcard='+phone+'&roleid=3',phone);
                          if (data.code==1) {
                            showNewTab(phone);
                            $.ajax({
                              type: "POST",
                              url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_ticket/',
                              dataType: "json",
                              data:{
                                ticketchanel:2,
                                agentcreated:'<?php echo($this->session->userdata('custid'))?>',
                                custid:data.custid,
                                priority:1,
                                phone:phone,
                                queue:data.queue,
                                callrefid:callrefid
                              },
                              success: function(data){
                                console.log(data);
                                p_data['ticket'] = data.data;
                                hideScreen(1,p_data);
                                showTicketTab(data.data);
                              },error: function(xhr, status, error) {
                                console.log(error);
                                alert(error);
                              }
                            });
                          }
                        },error: function(xhr, status, error) {
                          console.log(error);
                          alert(error);
                        }
                      });
              }
            }
      });



      // e_answered event
      socket.on('e_completed',function(data){
            console.log('e_completed');
            console.log(data);
            save_call_log("call","completed",data);
            // $('#phone-chat').css('display','block');
            // hideScreen(1,data.fromnumber);

            var phone = data.fromnumber;
            var tonum = data.tonumber;
            var callrefid = data.callrefid;
            var record = data.recording_file;
            var duration = data.billsec;
            var custid = $('#has-call-pad #c-number').attr('custid');
            var ticketid = $('#has-call-pad #c-ticket').attr('ticketid');
            console.log(ticketid);
            $.ajax({
                  type: "POST",
                  url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_tcklog/',
                  dataType: "json",
                  data:{
                    ticketid:ticketid,
                    agentcreated:'<?php echo($this->session->userdata('custid'))?>',
                    custid:custid,
                    phone:phone,
                    callrefid:callrefid,
                    record:record,
                    duration:duration,
                    tonum:tonum
                  },
                  success: function(data){
                    console.log(data);
                  },error: function(xhr, status, error) {
                    console.log(error);
                    alert(error);
                  }
                });
      });





      socket.on('e_misscall',function(data){
        console.log('e_misscall');
          console.log(data);
          save_call_log("call","misscall",data);
          $('#phone-chat').css('display','block');
          hideScreen(5,data.fromnumber);
      });
      socket.on('e_hangup',function(data){
        console.log('e_hangup');
            console.log(data);
            // save_call_log("call","hangup",data);
            $('#phone-chat').css('display','block');
            hideScreen(5,data.fromnumber);
      });
      socket.on('e_customer_hangup',function(data){
        console.log('e_customer_hangup');
        console.log(data);
        // save_call_log("call","hangup",data);
        $('#phone-chat').css('display','block');
        hideScreen(5,data.fromnumber);
      });
      socket.on('e_customer_answered',function(data){
          console.log('e_cusomter_answered');
          console.log(data);

          // save_call_log("call","answered",data);
          var phone = data.tonumber;
          var extension = data.fromnumber;
          var p_data = {};
          p_data['phone'] = phone;

          p_data['channel'] = data.channel;
          p_data['ticket'] = "";
          p_data['calltype'] = "Cuộc gọi đi";
          if (extension=='<?php echo($this->session->userdata('telephone'));?>') {
            $('#phone-chat').css('display','block');
            hideScreen(9,p_data);
          }
          stop_timer();
          start_record('#has-call-pad #c-record');
      });

      socket.on('e_misscall_outbound',function(data){
        console.log(data);
        save_call_log("call","misscall",data);
        hideScreen(5);
      });

      socket.on('e_completed_outbound',function(data){
        console.log(data);
        save_call_log("call","completed",data);
        var phone = data.fromnumber;
            var tonum = data.tonumber;
            var callrefid = data.callrefid;
            var record = data.recording_file;
            var duration = data.billsec;
            var custid = $('#has-call-pad #c-number').attr('custid');
            var ticketid = $('#has-call-pad #c-ticket').attr('ticketid');
            console.log(ticketid);
            $.ajax({
                  type: "POST",
                  url: 'http://'+window.location.hostname+'/api/aj_crm_isrt_tcklog/',
                  dataType: "json",
                  data:{
                    ticketid:ticketid,
                    agentcreated:'<?php echo($this->session->userdata('custid'))?>',
                    custid:custid,
                    phone:phone,
                    callrefid:callrefid,
                    record:record,
                    duration:duration,
                    tonum:tonum
                  },
                  success: function(data){
                    console.log(data);
                  },error: function(xhr, status, error) {
                    console.log(error);
                    alert(error);
                  }
                });
      });

      socket.on('e_ringing_outbound',function(data){
        console.log(data);
        // save_call_log("call","ringing",data);
        var p_data = [];
        p_data['phone'] = data.tonumber;
        p_data['channel'] = data.channel;
        p_data['avatar'] = null;
        p_data['custname'] = "---";
        p_data['ticket'] = "";
        hideScreen(8,p_data);
        start_timer('#has-call-pad #c-time');
      });

      socket.on('e_not_inuse',function(data){
        console.log(data);
        var status = $('#phone-chat').css("display");
        console.log(status);
        if (status == "block") {
          console.log(status);
          hideScreen(5);
        }
      });

      $(document).on('click','#c-number',function(){

      });

      $('input#user-call-search').on('keyup',function(){
        var val = $(this).val();
        if (val!='') {
          $('i.search-destroy').css('display','block');
        }else{
          $('i.search-destroy').css('display','none');
        }
      });

      $('i.search-destroy').click(function(){
        var input = $('input#user-call-search').val();
        if (input.length>0) {
          var newlength = input.length-1;
          $('input#user-call-search').val(input.substr(0, newlength)).focus();
          if (newlength==0) {
            $('i.search-destroy').css('display','none');
          }
        }
      });
      $('i.search-icon').click(function(){
        var text = $('input#user-call-search').val();
        if (text.length>0){
            console.log(text);
            $('#call-input').css('display','block');
        }else{
            $('#call-input').css('display','none');
        }
      });
      $('i.call-input-close').click(function(){
        $('#call-input').css('display','none');
      });
      
      $(document).on('click','.btn-call',function(){
        var id = $(this).attr('id');
        socket.emit('to_target',id,{event:"ringing"});
      });

      $(document).on('click','#deny-call,#are-b-end a',function(){
        var channel = $('#c-chanel #channel').attr('channel');
        stop_timer();
        start_record();
        if (channel!='Kênh thoại') {
          console.log(channel);
          $.ajax({
                    type: "GET",
                    url: 'http://'+window.location.hostname+'/api/aj_mitek_hang_up/'+channel,
                    dataType: "json",
                    success: function(data){
                      console.log(data);
                    },error: function(xhr, status, error) {
                      console.log(error);
                    }
                  });
        }else{
          hideScreen(5,{});
        }
      });

      $(document).on('click','#are-b-call a',function(){
        var extension = $('#phone-chat').attr('extension');
        var phone = $('#user-call-search').val();
        var p_data = [];
        if (phone) {
          stop_timer();
          p_data['phone'] = phone;
          p_data['channel'] = '';
          p_data['avatar'] = null;
          p_data['custname'] = "---";
          // p_data['ticket'] = "";
          // p_data['phone_act'] = 'newuser';
          hideScreen(7,p_data);
          api_call_to_number(extension,phone);
          $.ajax({
            type: "GET",
            url: 'http://'+window.location.hostname+'/api/get_infor_user/'+phone,
            dataType: "json",
            success: function(data){
              if (data.data!=null) {
                var rec = data.data[0];
                console.log(rec);
                p_data['avatar'] = rec.avatar;
                p_data['custname'] = rec.custname;
                p_data['custid'] = rec.custid;
                p_data['phone_act'] = 'newtab';
                hideScreen(7,p_data);
              }
            },error: function(xhr, status, error) {
              console.log(error);
            }
          });
        }
      });

      $("#status-options ul li").click(function(){
        $("#status-options ul li").each(function(){
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
            }
        });
        $(this).addClass('active');
        var stt = $(this).attr('id');
        var txt = $(this).find('p').html();
        $("#status-selection").removeClass().addClass(stt).find('p').html(txt);
      });

      $(document).on('click','.s-rst-li',function(){
        var act = $(this).closest('ul').attr('action');
        var extension = $('#phone-chat').attr('extension');
        var phone = $(this).find('.user-num').html();
        var channel = $('#c-chanel #channel').attr('channel');
        if (act=='call') {
          hideScreen(7);
          api_call_to_number(extension,phone);
        }else if(act=='tranfer'){
          api_tranfer_to_extension(phone,channel);
          hideScreen(3);
        }
      });

      $(document).on('click','#direct-call',function(){
        var p_data = {};
        p_data['channel'] = $('#c-chanel #channel').attr('channel');
        p_data['avatar'] = $('#has-call-pad').find('#c-avatar').find('img').attr('src');
        p_data['custname'] = $('#has-call-pad').find('#c-name').html();
        p_data['phone'] = $('#has-call-pad').find('#c-number').html();
        hideScreen(2,p_data);
      });

      $(document).on('click','#key-board',function(){
        var pad = $('#num-pad');
        if (pad.hasClass('hide')) {
          pad.removeClass('hide');
          $(this).addClass('icon-active');
        }else{
          pad.addClass('hide');
          $(this).removeClass('icon-active');
        }
      });

      $(document).on('click','#deny-direct',function(){
        
        hideScreen(2,p_data);
      });

      $(document).on('click','#call-direct',function(){
       
      });
    });
  function api_call_to_number(extension,phone){
    $.ajax({
      type: "GET",
      url: 'http://'+window.location.hostname+'/api/aj_mitek_clicktocall/'+extension+'/'+phone,
      dataType: "json",
      success: function(data){
        console.log(data);
      },error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  function api_tranfer_to_extension(extension,channel){
    $.ajax({
      type: "GET",
      url: 'http://'+window.location.hostname+'/api/aj_mitek_tranfer/'+extension+'/'+channel,
      dataType: "json",
      success: function(data){
        console.log(data);
      },error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  function start_timer(element){
    var time = 0;
    stop_timer();
    timer = setInterval(countdown, 1000);
    function countdown() {
        if (time > 59 ) {
            clearTimeout(timer);
        }else{
          time++;
          $(element).html('Thời gian chờ: '+time+' s');
        }
    }
  }

  function stop_timer(){
    if (timer!=null) {clearTimeout(timer);timer=null}
  }

  function stop_record(){
    if (record!=null) {clearTimeout(record);record=null}
  }

  function start_record(element){
    var timer = 0, minutes, seconds;
    stop_record();
    record = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        $(element).html(minutes + ":" + seconds); 

        if (++timer > 300) {
            timer = 0;
        }
    }, 1000);
  }

  function save_call_log(object,event,data){
    $.ajax({
      type: "POST",
      url: 'http://'+window.location.hostname+'/api/save_call_log/',
      dataType: "json",
      data:{
        value:data,
        object:object,
        event:event
      },
      success: function(data){
        console.log(data);
      },error: function(xhr, status, error) {
        console.log(error);
        alert(error);
      }
    });
  }
  function iframe_click(number=undefined,ticket=undefined){
    var extension = $('#phone-chat').attr('extension');
        if (number && ticket) {
          api_call_to_number(extension,number);
          var p_data = [];
          p_data['phone'] = number;
          p_data['channel'] = '';
          p_data['avatar'] = null;
          p_data['custname'] = "---";
          p_data['ticket'] = ticket;
          // p_data['phone_act'] = 'newuser';
          $('#phone-chat').css("display","block");
          hideScreen(7,p_data);
          $.ajax({
            type: "GET",
            url: 'http://'+window.location.hostname+'/api/get_infor_user/'+number,
            dataType: "json",
            success: function(data){
              if (data.data!=null) {
                var rec = data.data[0];
                console.log(rec);
                p_data['avatar'] = rec.avatar;
                p_data['custname'] = rec.custname;
                p_data['custid'] = rec.custid;
                p_data['phone_act'] = 'newtab';
                hideScreen(7,p_data);
              }
            },error: function(xhr, status, error) {
              console.log(error);
            }
          });
        }
  }
</script>

<!-- https://api-popupcontact-02.mitek.vn/api/v1/call -->
<!-- ac97db2cca493ad87045946aed59eb29 -->

<file_sep><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Main CSS-->
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <link rel="stylesheet" type="text/css" href="css/customer.css">
    <!-- Font-icon css-->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Customer Relationship Management</title>
    <script src="https://www.google.com/recaptcha/api.js?hl=vi"></script>
  </head>
  <body class="height-1024">
    <section class="material-half-bg">
      <div class="cover"></div>
    </section>
    <section class="login-content">
      <div class="logo">
        <!-- <h1>Vali</h1> -->
        <img src="images/logo.png">
      </div>
      <div class="row login-box col-xl-12">
      	<div class="col-xl-6 border-right-offset">
      		<div class="offset-2 col-xl-8">
            <form id="login_form">
		          <h3 class="login-head">
		          	<img src="images/tavicoCRM.png">
		          </h3>
		          <div class="form-group">
		            <label class="control-label login-label">Tên đăng nhập</label>
		            <input class="form-control login-input" name="username" type="text" required="" placeholder="Username" autofocus>
		          </div>
		          <div class="form-group">
		            <label class="control-label login-label">Mật khẩu</label>
		            <input class="form-control login-input" name="password" type="<PASSWORD>" required="" placeholder="<PASSWORD>">
		          </div>
              <!-- <div class ="form-group lgin">
                <div class="g-recaptcha"  data-sitekey="<KEY>"></div>
              </div> -->
              <div class="form-group">
                <p class="text-danger alert-danger"><?php if($this->session->flashdata('message')){echo($this->session->flashdata('message'));}?></p>
              </div>
		          <div class="form-group btn-container">
		            <!-- <button type="button" class="btn btn-primary btn-block" onclick="checkCaptcha()"><i class="fa fa-sign-in fa-lg fa-fw"></i>Log in</button> -->
                <!--<button type="submit" class="btn btn-primary btn-block"><i class="fa fa-sign-in fa-lg fa-fw"></i>Log in</button>-->
                <button class="btn btn-primary btn-block btn_login" type="submit"><i class="fa fa-sign-in"></i>Log in</button>
		          </div>
              <div class="form-group">
                <!-- <p class="text-danger alert-danger"><?php if($this->session->flashdata('message')){echo($this->session->flashdata('message'));}?></p> -->
                <!-- <div class="utility">
                  <div class="animated-checkbox">
                    <label>
                      <input name="remember_me" type="checkbox"><span class="label-text">Stay Signed in</span>
                    </label>
                  </div>
                  <p class="semibold-text mb-2"><a href="#" data-toggle="flip">Quên mật khẩu ?</a></p>
                  <p class="semibold-text mb-2"><a href="#" data-toggle="flip">Chưa có tài khoản ?</a></p>
                </div> -->
                <p class="semibold-text mb-2"><a href="#" data-toggle="flipppp">Quên mật khẩu ?</a></p>
                <p class="semibold-text mb-2"><a href="#" data-toggle="flipppp">Chưa có tài khoản ?</a></p>
              </div>

		        </form>

		        <form class="forget-form" action="">
		          <h3 class="login-head"><i class="fa fa-lg fa-fw fa-lock"></i>Forgot Password ?</h3>
		          <div class="form-group">
		            <label class="control-label">EMAIL</label>
		            <input class="form-control" type="text" placeholder="Email">
		          </div>
		          <div class="form-group btn-container">
		            <button class="btn btn-primary btn-block"><i class="fa fa-unlock fa-lg fa-fw"></i>RESET</button>
		          </div>
		          <div class="form-group mt-3">
		            <p class="semibold-text mb-0"><a href="#" data-toggle="flip"><i class="fa fa-angle-left fa-fw"></i> Back to Login</a></p>
		          </div>
		        </form>
      		</div>
      	</div>
      	<div class="col-xl-6 text-center">
      		<h5 class="margin-top-50">THE FRIENDLY <a href="">CUSTOMER SERVICE</a> SYSTEM</h5>
      		<p class="no-margin-bot">Smart help desk support via e-mail, telephony, chatting and more…</p>
      		<p>CLICK TO DISCOVER AWESOME FEATURE</p>
      		<img class="clearfix" src="images/people.png">
      	</div>
      </div>
    </section>
    <form method="post" action="<?php echo base_url() ?>dashboard" id="myForm" >
        <input type="hidden" name="custid" id="custid">
        <input type="hidden" name="groupid" id="groupid">
        <input type="hidden" name="telephone" id="telephone">
        <input type="hidden" name="username" id="username1">
        <input type="hidden" name="password" id="<PASSWORD>">
        <input type="hidden" name="custname" id="custname">
        <input type="hidden" name="avatar" id="avatar">
        <input type="hidden" name="roleid" id="roleid">
        <input type="hidden" name="idcard" id="idcard">
    </form>
    <!-- Essential javascripts for application to work-->
    <script src="js/jquery-3.2.1.min.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
    <script type="text/javascript" src="<?=base_url()?>js/plugins/sweetalert.min.js"></script>
    <!-- The javascript plugin to display page loading on top-->
    <script src="js/plugins/pace.min.js"></script>
    <?php echo isset($script) ? $script : ''; ?>
    
  </body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Customer Relationship Managerment</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Main CSS-->
    <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/main.css">
    <!-- Font-icon css-->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="<KEY>" crossorigin="anonymous">
    <!-- Customer CSS-->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="<?php echo base_url() ?>css/jquery.scrolling-tabs.css">
    <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer.css">
     <link rel="stylesheet" type="text/css" href="<?=base_url()?>css/customer2.css">
  </head>
  <body class="app sidebar-mini rtl sidenav-toggled">
    <!-- Navbar-->
    <?php echo isset($navbar) ? $navbar : ''; ?>
    <!-- Sidebar menu-->
    <?php echo isset($sidebar) ? $sidebar : ''; ?>
     
    <?php if(isset($link)){ ?>
        <div class="tab-content">
            <div role="tabpanel" class="tab-pane active" id="1000">
                <iframe id="myiframe" class="myiframe" name="myiframe" src="<?php echo base_url().$link ?>" frameborder="0"></iframe>
            </div>
        </div>
    <?php } ?>
    <div class="holds-the-iframe">
    <script type="text/javascript">
        var arrayTab = [];
        for(var i = 100; i<1000;i++)
        {
            arrayTab.push(i);
        }
    </script>
    <iframe id="myiframetext" width="0" height="0" class="myiframetext" name="myiframetext" src="<?php echo base_url().$link ?>" frameborder="0"></iframe>
    </div>
    <!-- Essential javascripts for application to work-->
    <script src="<?=base_url()?>js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="<?=base_url()?>js/popper.min.js"></script>
    <script src="<?=base_url()?>js/bootstrap.min.js"></script>
    <script src="<?=base_url()?>js/main.js"></script>
    <script src="<?=base_url()?>js/main2.js"></script>
    <!-- The javascript plugin to display page loading on top-->
    <script src="<?=base_url()?>js/plugins/pace.min.js"></script>
    <!-- Page specific javascripts-->
    <script type="text/javascript" src="<?=base_url()?>js/plugins/chart.js"></script>
    <script type="text/javascript" src="<?=base_url()?>js/plugins/bootstrap-notify.min.js"></script>
    <script type="text/javascript" src="<?=base_url()?>js/plugins/sweetalert.min.js"></script>
    
            <script src="<?php echo base_url() ?>js/jquery.scrolling-tabs.js"></script>
            <?php echo isset($script2) ? $script2 : ''; ?>
    <!-- <------------------script -->
    <?php echo isset($script) ? $script : ''; ?>
    <?php echo isset($nodejs) ? $nodejs : ''; ?>
  </body>
</html><file_sep><script type="text/javascript">
	$('.btn-creategroupuser').click(function(){
     $('.btn-creategroupuser').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
     getValueCheckbox("viewticket","viewtickethidden");
     getValueCheckbox("addticket","addtickethidden");
     getValueCheckbox("editticket","edittickethidden");

     getValueCheckbox("viewuser","viewuserhidden");
     getValueCheckbox("adduser","adduserhidden");
     getValueCheckbox("edituser","edituserhidden");

     getValueCheckbox("viewtask","viewtaskhidden");
     getValueCheckbox("addtask","addtaskhidden");
     getValueCheckbox("edittask","edittaskhidden");

     getValueCheckbox("viewknowledge","viewknowledgehidden");
     getValueCheckbox("addknowledge","addknowledgehidden");
     getValueCheckbox("editknowledge","editknowledgehidden");

     getValueCheckbox("viewpermission","viewpermissionhidden");
		 $.ajax({
        url: '<?php echo base_url()?>groupuser/groupuserinsert',
        type: 'POST',
        dataType: 'JSON',
        data: $('#dataInsertGroup').serialize(),
        // data: $('#insertUserVal').serialize(),
      })
      .done(function(data) {
                 if(data.message =='Success')
                 {
                  alert('Thêm nhóm người dùng thành công');
                  $('.btn-creategroupuser').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
                    location.reload();
                 }
                 else{
                  alert(data.message);
                 }
              })
      .fail(function() {
         alert('Thêm nhóm người dùng thất bại');
      })
	});
  function getValueCheckbox(name,namehidden)
  {
    if(document.getElementById(name).checked) {
        document.getElementById(namehidden).disabled = true;
      }
  }
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Queue extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model('M_api');
	}
	public function index()
	{
		$_body = [];
        $_body['left'] = $this->load->view('datasource/queue/qu_left',null,TRUE); 
        $_data = [];    
        $_data['script'] = $this->load->view('script/script_queue', NULL, TRUE); 
        $_data['mainview'] = $this->load->view('datasource/queue/form', $_body , TRUE);
        $this->load->view('dashboard',$_data);
	}
	public function rightFilter()
    {
		$list_extend['list_ext'] = [];
    	$queue = $this->input->get('queue');
    	// $postdata = http_build_query([
     //            'queue' => $queue,
     //            'secret' => 'ac97db2cca493ad87045946aed59eb29'
     //    ]);
     //    $opts = array('http' =>
     //        array(
     //            'method'  => 'POST',
     //            'header'  => 'Content-type: application/x-www-form-urlencoded',
     //            'content' => $postdata
     //        )
     //    );
     //    $context  = stream_context_create($opts);
     //    $result = file_get_contents('https://api-prod.mipbx.vn/api/v1/call/getExtensionInQueue',false,$context);
        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/select?queuecode='.$queue);
        $list_extend['extension'] = json_decode($result,true)['data'];
        $_data['script'] = $this->load->view('script/script_queue', NULL, TRUE); 
        $_data['mainview'] = $this->load->view('datasource/queue/qu_center', $list_extend, TRUE);
        $this->load->view('dashboard',$_data);
        // echo $result;
    }

    public function loginQueue()
    {
        $secret = 'ac97db2cca493ad87045946aed59eb29';
        $data = $this->input->post();
        $extension = $data['telephone'];
        $queue = $data['queue'];
        $status = $data['status'];

        // // $secret = $frm['secret'];
        if ($extension == NULL || $queue == NULL || $secret == NULL) {
            $data['code'] = 0;
            $data['message'] = 'Failed';
            $data['data'] = null;
            echo json_encode($data);
        }else{
            $postfields = array('extension'=>$extension, 'queue'=>$queue, 'secret' => 'ac97db2cca493ad87045946aed59eb29' , 'penalty'=>$status);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://api-prod.mipbx.vn/api/v1/call/loginQueue');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            // Edit: prior variable $postFields should be $postfields;
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
            $result = curl_exec($ch);
            $err = curl_error($ch);
            curl_close($ch);

            if ($err) {
              echo "cURL Error #:" . $err;
            } else {
              // var_dump($postfields);
              echo $result;
            }
        }
        $arrayResult = json_decode($result,true);
        if( ($arrayResult['code'] != '400') || ($arrayResult['code'] == '200' && $arrayResult['result']['response'] != "Error"))
        {
            $postdata = http_build_query([
                    'queuecode' => $queue,
                    'extension' => $extension,
                    'status' => $status
            ]);
            $opts = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata
                )
            );
            $context  = stream_context_create($opts);
            $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/insert',false,$context);   
        }
        
    }

    public function logoutQueue()
    {
        $secret = 'ac97db2cca493ad87045946aed59eb29';
        $data = $this->input->post();
        $extension = $data['telephone'];
        $queue = $data['queue'];
        // $secret = $frm['secret'];
        if ($extension == NULL || $queue == NULL || $secret == NULL) {
            $data['code'] = 0;
            $data['message'] = 'Failed';
            $data['data'] = null;
            echo json_encode($data);
        }else{
            $postfields = array('extension'=>$extension, 'queue'=>$queue, 'secret' => 'ac97db2cca493ad87045946aed59eb29');
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://api-prod.mipbx.vn/api/v1/call/logoutQueue');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            // Edit: prior variable $postFields should be $postfields;
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
            $result = curl_exec($ch);
            $err = curl_error($ch);
            curl_close($ch);

            if ($err) {
              echo "cURL Error #:" . $err;
            } else {
              echo $result;
            }
            
        }
        $arrayResult = json_decode($result,true);
        if( ($arrayResult['code'] == 200))
        {
            $result1 = file_get_contents('http://test.tavicosoft.com/crm/index.php/queue/delete?queuecode='.$queue.'&extension='.$extension);   
        }
        
    }
}

/* End of file Queue.php */
/* Location: ./application/controllers/Queue.php */
?><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
      	<div class="col-md-12 margin-bot-10 margin-top-5 margin-left-10">
      		<div class="fc-left">
      			<div class="fc-button-group hide">
      				<button type="button" class="fc-month-button fc-button fc-state-default fc-corner-left">Bài viết</button><button type="button" class="fc-agendaWeek-button fc-button fc-state-default">Quy trình</button><button type="button" class="fc-agendaWeek-button fc-button fc-state-default">Thanh lý</button><button type="button" class="fc-agendaWeek-button fc-button fc-state-default fc-state-active fc-corner-right">Thanh lý hợp đồng cọc</button>
      			</div>
      		</div>      	</div>
        <div class="col-md-2 col-md-22 no-padding padding-left-15">
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-10">
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Phân loại</label>
	            		<select name="type" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_1" value="<?php echo isset($knowledge[0]['tickettype'])?$knowledge[0]['tickettype']:'' ?>">
	              			<?php if (isset($l_type) && !empty($l_type)) {
	              				foreach ($l_type as $key => $value) {
	              					$sel = '';
	              					if (isset($knowledge[0]['tickettype']) && $value['code']==$knowledge[0]['tickettype']) {
	              						$sel = 'selected';
	              					}
	              					echo '<option '.$sel.' value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              				# code...
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Nhóm vấn đề</label>
	            		<select name="group" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_2" value="<?php echo isset($knowledge[0]['groupid'])?$knowledge[0]['groupid']:'' ?>">
	              			<?php if (isset($l_group) && !empty($l_group)) {
	              				foreach ($l_group as $key => $value) {
	              					$sel = '';
	              					if (isset($knowledge[0]['groupid']) && $value['code']==$knowledge[0]['groupid']) {
	              						$sel = 'selected';
	              					}
	              					echo '<option '.$sel.' ref1="'.$value['ref1'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              				# code...
	              			} ?>
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Chi tiết VĐ</label>
	            		<select name="cate" class="control-label col-md-8 no-border no-padding margin-left-10" id="level_3" value="<?php echo isset($knowledge[0]['categoryid'])?$knowledge[0]['categoryid']:'' ?>">
	              			<?php if (isset($l_cate) && !empty($l_cate)) {
	              				foreach ($l_cate as $key => $value) {
	              					$sel = '';
	              					if (isset($knowledge[0]['categoryid']) && $value['code']==$knowledge[0]['categoryid']) {
	              						$sel = 'selected';
	              					}
	              					echo '<option '.$sel.' ref1="'.$value['ref1'].'" ref2="'.$value['ref2'].'" value="'.$value['code'].'">'.$value['name'].'</option>';
	              				}
	              			} ?>
	              		</select>
	            	</div>
	            	
	            </div>
          	</div>
          	<div class="tile p-0 padding-5 margin-bot-5">
	            <div class="tile-body padding-left-10">
	            	<div class="hide">
	            		<label class="control-label user-label col-md-3 no-padding">Quyền sửa</label>
	              		<label class="control-label col-md-8 col-71 no-padding-right">
		              		<input name="right" class="col-md-12 no-padding font-size-12" list="i-right" value="">
		              		<datalist id="i-right">
		              			<option value="0">Tất cả mọi người</option>
		              		</datalist>
		              	</label>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Tag</label>
	            		<select name="ticketprioty" class="control-label col-md-8 no-border no-padding margin-left-10" value="<?php echo isset($knowledge[0]['ticketprioty'])?$knowledge[0]['ticketprioty']:'' ?>">
	            			<?php if (isset($knowledge[0]['ticketprioty'])) {
	            				if ($knowledge[0]['ticketprioty']=='0') {
	            					echo '<option value="0" selected>Thường</option><option value="1">Cao</option><option value="2">Khẩn cấp</option>';
	            				}elseif ($knowledge[0]['ticketprioty']=='1') {
	            					echo '<option value="0">Thường</option><option  selected value="1">Cao</option><option value="2">Khẩn cấp</option>';
	            				}elseif ($knowledge[0]['ticketprioty']=='2') {
	            					echo '<option value="0">Thường</option><option value="1">Cao</option><option  selected value="2">Khẩn cấp</option>';
	            				}
	            			}else{
	            					echo '<option value="0">Thường</option><option value="1">Cao</option><option value="2">Khẩn cấp</option>';
	            				} ?>
	              			
	              			
	              		</select>
	            	</div>
	            	<div class="">
	            		<label class="control-label user-label col-md-3 no-padding">Trạng thái</label>
	            		<select name="status" class="control-label col-md-8 no-border no-padding margin-left-10" value="<?php echo isset($knowledge[0]['hidden'])?$knowledge[0]['hidden']:'' ?>">
	            			<?php if (isset($knowledge[0]['ticketprioty'])) {
	            				if ($knowledge[0]['hidden']=='0') {
	            				 echo '<option value="0" selected>Đang hoạt động</option><option value="1">Ngưng hoạt động</option>';
	            				}elseif ($knowledge[0]['hidden']=='1') {
	            				 echo '<option value="0">Đang hoạt động</option><option selected value="1">Ngưng hoạt động</option>';
	            				}
	            			}else{
	            					echo '<option value="0">Đang hoạt động</option><option value="1">Ngưng hoạt động</option>';
	            				} ?>
	              		</select>
	            	</div>
	            </div>
          	</div>
          	<div class="padding-5 margin-bot-5 padding-left-10">
	          	<div class="">
	        		<label class="control-label user-label col-md-3 no-padding">Đăng bởi</label>
	          		<label class="control-label col-md-8 no-padding-right"><?php echo isset($knowledge[0]['custname'])?$knowledge[0]['custname']:'' ?></label>
	        	</div>
	        	<div class="">
	        		<label class="control-label user-label col-md-3 no-padding">Ngày đăng</label>
	          		<label class="control-label col-md-8 no-padding-right"><?php echo isset($knowledge[0]['createdat'])?date("d-m-Y", strtotime($knowledge[0]['createdat'])):'' ?></label>
	        	</div>
	        	<div class="clearfix hide">
	        		<label class="control-label user-label col-md-3 no-padding">Cập nhật</label>
	          		<label class="control-label col-md-8 no-padding-right no-margin-top">hh:mm dd/mm/yyyy</label>
	        	</div>
	        </div>        
	    </div>
        <div class="col-md-6 col-md-56 no-padding padding-left-5">
          	<div class="tile height-1024">
	            <div class="content-title">
			        <div class="div width-100per">
			          	<h5 id="knl-title"><?php echo isset($knowledge[0]['title'])?$knowledge[0]['title']:'' ?>
			          		<input type="hidden" name="title" value="">
			          	</h5>
			        </div>
			    </div>
			    <div class="bs-component">
			    	<div class="row">
			    		<div class="offset-10 col-md-2 margin-bot-10">
			    			<button class="btn btn-primary float-right" id="ck-edit" type="button"> Chỉnh sửa </button>
			    			<button action="<?php if($this->uri->segment(3)!='')
			    			{
			    				echo $this->uri->segment(3);
			    			}
			    			else
			    			{
			    				echo 'add';
			    			}
			    			 ?>" class="btn btn-primary float-right hide" id="ck-save" type="button"> Lưu </button>
			    		</div>
			    	</div>
			    	<div id="content" ck-edit="close">
		              	<div class="knc-content">
							<!-- Kham pha -->
							<?php echo isset($knowledge[0]['article'])?$knowledge[0]['article']:'' ?>
						</div>
					</div>
	            </div>
          	</div>        </div>
        <div class="col-md-3 col-md-22 no-padding padding-left-5 padding-top-10 hide">
        	<div class="timeline">
			  	<div class="entry">
				    <div class="title gray">
				      	<p class="time-detail">hh:mm:ss</p>
				      	<p class="date-detail">dd/mm/yyyy</p>
				    </div>
				    <div class="body">
				      	<p class="margin-bot-3">System - Hệ thống</p>
				        <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p>
				    </div>
			  	</div>
			  	<div class="entry">
				    <div class="title red">
				      	<p class="time-detail">hh:mm:ss</p>
				      	<p class="date-detail">dd/mm/yyyy</p>
				    </div>
				    <div class="body">
				      	<p class="margin-bot-3">System - Hệ thống</p>
				        <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p>
				    </div>
			  	</div>
			  	<div class="entry">
				    <div class="title green">
				      	<p class="time-detail">hh:mm:ss</p>
				      	<p class="date-detail">dd/mm/yyyy</p>
				    </div>
				    <div class="body">
				      	<p class="margin-bot-3">System - Hệ thống</p>
				        <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p>
				    </div>
			  	</div>
			  	<div class="entry">
				    <div class="title yellow">
				      	<p class="time-detail">hh:mm:ss</p>
				      	<p class="date-detail">dd/mm/yyyy</p>
				    </div>
				    <div class="body">
				      	<p class="margin-bot-3">System - Hệ thống</p>
				        <p class="no-margin-bot">User History in only two line, User History only in two line. Thanks !!</p>
				    </div>
			  	</div>
			</div>        
		</div>
    </div>
</main><file_sep><?php $lq = $this->input->get('lienquan'); ?>
<div class="col-md-100 no-padding padding-left-5">
	    	<div class="tile height-1024">
	            <div class="table-responsive">
	              	<table class="table" id="table-1-searchticket">
	              		<thead class="no-border-top">
	              			<tr>
	              				<th width="100">ID</th>
	              				<th width="250">Tên phiếu</th>
	              				<th width="130px">Người yêu cầu</th>
	              				<th width="130px">Người phụ trách</th>
	              				<th width="60px">Độ ưu tiên</th>
	              				<th width="50">Đến hạn</th>
	              				<th width="50">Ngày tạo</th>
	              				<!-- <th width="50">Cập nhật</th> -->
	              			</tr>
	              		</thead>
		                <tbody>
		                	<?php 
		                	if(count($result['data']) >0&& $result['code']==1)
		                	{
		                		$i =0;
		                	foreach ($result['data'] as $rows) { 
		                			if($lq == 'false')
		                			{
		                			if(($rows['status']==$status && $rows['agentcurrent']==$agentcurrent && $rows['status'] != 9) || ($status==-1 && $rows['agentcurrent']==$agentcurrent && $rows['status'] != 9 )){
		                		?>
		                	<tr class="border-bot-1">
			                    <td>
			                    	<a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.urlencode($rows['custid']).'/'.urlencode($rows['idcard']) ?>','#<?php echo $rows['ticketid'] ?>')" href="#">
			                    	<span class="id-label span-warning">P</span>  #<?php echo $rows['ticketid'] ?>
			                    	</a>
			                    </td>
			                    <td>
			                    	<?php echo $rows['title'] ?>
			                    </td>
			                    <td><?php if(isset($rows['custname'])){ echo $rows['custname'];} ?></td>
			                    <td><?php if(isset($rows['agentcurrentname'])){ echo $rows['agentcurrentname'];} ?></td>
			                    <td><?php 
			                    	if ($rows['priority']==1) {echo "Thường";}
			                    	elseif ($rows['priority']==2) {echo "Cao";}
			                    	elseif ($rows['priority']==3) {echo "Khẩn cấp";}
			                    	else {echo "Không xác định";}
			                    ?></td>
			                    <td>
			                    	<?php if (strtotime($rows['duedate'])>strtotime("2000/01/01"))
				                    echo date("d/m/Y H:i:s", strtotime($rows['duedate']));?>
			                    	</td>
			                    <td><?php if (strtotime($rows['duedate'])>strtotime("2000/01/01"))
			                    echo date("d/m/Y H:i:s", strtotime($rows['createat']));?></td>
		                  	</tr>	
		                	<?php }}else{
		                		if(($rows['agentcreated'] == $agentcurrent && $rows['status']!= 9) || (strpos($rows['ticketusers'], $agentcurrent) !== false && $rows['status']!= 9)){?>
							<tr class="border-bot-1">
			                    <td>
			                    	<a class="buttonsearchiframe" onclick="addTab('<?php echo base_url().'ticket/detail/'.$rows['ticketid'].'/'.urlencode($rows['custid']).'/'.urlencode($rows['idcard']) ?>','#<?php echo $rows['ticketid'] ?>')" href="#" title="">
			                    	<span class="id-label span-warning">P</span>  #<?php echo $rows['ticketid'] ?>
			                    	</a>
			                    </td>
			                    <td>
			                    	<?php echo $rows['title'] ?>
			                    </td>
			                    <td><?php if(isset($rows['custname'])){ echo $rows['custname'];} ?></td>
			                    <td><?php if(isset($rows['agentcurrentname'])){ echo $rows['agentcurrentname'];} ?></td>
			                    <td><?php 
			                    	if ($rows['priority']==1) {echo "Thường";}
			                    	elseif ($rows['priority']==2) {echo "Cao";}
			                    	elseif ($rows['priority']==3) {echo "Khẩn cấp";}
			                    	else {echo "Không xác định";}
			                    ?></td>
			                    <td><?php if (strtotime($rows['duedate'])>strtotime("2000/01/01"))
				                    echo date("d/m/Y H:i:s", strtotime($rows['duedate']));?></td>
			                    <td><?php if (strtotime($rows['duedate'])>strtotime("2000/01/01"))
			                    echo date("d/m/Y H:i:s", strtotime($rows['createat']));?></td>
		                  	</tr>	
		                		<?php }}}} ?>				  
		                </tbody>
	              	</table>
	            </div>  
	        </div>
	    </div><file_sep><script type="text/javascript">
	$(document).ready(function(){
		$('#modalDelete').on('shown.bs.modal', function (e) {
  			var code = $(e.relatedTarget).data('code');
			$(e.currentTarget).find('input[name="codedelete"]').val(code);
			var category = $(e.relatedTarget).data('category');
			$(e.currentTarget).find('input[name="categorydelete"]').val(category);
		});
		$('#modalUpdate').on('shown.bs.modal', function (e) {
  			var code = $(e.relatedTarget).data('code');
			$(e.currentTarget).find('input[name="code"]').val(code);
			var category = $(e.relatedTarget).data('category');
			$(e.currentTarget).find('input[name="category"]').val(category);
			var name = $(e.relatedTarget).data('name');
			$(e.currentTarget).find('input[name="name"]').val(name);
		});
	});
	function insertExtUser(formid)
	{
		var fieldtype = $('#fieldtype').val();
		var fieldcode = $('#fieldcode').val();
		var fieldname = $('#fieldname').val();
		var datasource = $('#datasource').val();
		var dataExt = $('#dataExt').serialize();
		 $.ajax({
             url: '<?php echo base_url().'groupuser/insertFieldUser' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {fieldtype:fieldtype,fieldcode:fieldcode,fieldname:fieldname,formid:formid,dataExt : dataExt,datasource:datasource},
           })
           .done(function(data) {
               if(data.code==1){
               	window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}

	function selectType(obj)
	{
		$('.optionD').remove();
		var id = obj.value;
		if(id == 'D')
		{
			$('.extendbottom').append('<form id="dataExt" method="POST" role="form"><div class="optionD">\
				<div class="form-group">\
					    <label for="exampleInputEmail1">Mã nguồn dữ liệu</label>\
					    <input type="text" class="form-control" name="datasource" id="datasource" placeholder="-Mã nguồn dữ liệu">\
				</div>\
						<div class="form-group optionbottom">\
					    <label for="exampleInputEmail1">Dropdown Options</label>\
					    <div class="">\
	            		<label class="control-label user-label col-md-2 no-padding">Mã trường:</label>\
	              		<label class="control-label col-md-8 no-padding-right">\
		              		<input name="code[]" class="form-control" placeholder="Mã trường">\
		              	</label>\
	            		</div>\
	            		<div class="">\
	            		<label class="control-label user-label col-md-2 no-padding">Tên trường:</label>\
	              		<label class="control-label col-md-8 no-padding-right">\
		              		<input name="name[]" class="form-control" placeholder="Tên trường">\
		              	</label>\
	            		</div>\
	            		\
			</div>\
			<div class="addoption">\
	            		<label class="control-label user-label col-md-3 no-padding"></label>\
	              		<label class="control-label col-md-8 no-padding-right field-click-able"><a onclick="addOption()" style="cursor: pointer;" class="user-name">+ Thêm Option</a></label>\
	        </div></div></form>');
		}
	}
	function addOption()
	{
		$('.addoption').before('<div class="optionD">\
						<div class="form-group optionbottom">\
					    <label for="exampleInputEmail1">Options</label>\
					    <div class="">\
	            		<label class="control-label user-label col-md-2 no-padding">Mã trường:</label>\
	              		<label class="control-label col-md-8 no-padding-right">\
		              		<input name="code[]" class="form-control" placeholder="Mã trường">\
		              	</label>\
	            		</div>\
	            		<div class="">\
	            		<label class="control-label user-label col-md-2 no-padding">Tên trường:</label>\
	              		<label class="control-label col-md-8 no-padding-right">\
		              		<input name="name[]" class="form-control" placeholder="Tên trường">\
		              	</label>\
	            		</div>\
	            		\
			</div>\
			</div>');
	}
	function insertSelectBox()
	{
		var code = $('#code').val();
		var name = $('#name').val();
		var category = $('#category').val();
		$.ajax({
             url: '<?php echo base_url().'groupuser/insertSelectBox' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {code:code,name:name,category:category},
           })
           .done(function(data) {
               if(data.code==1){
               	window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}
	$('#udpategroup_btn').click(function(){
               var groupid = $('#groupid').val();
          	   var ticketrule = $('#ticketrule').val();
          	   var taskrule = $('#taskrule').val();
          	   var userrule = $('#userrule').val();
          	   var knowledgerule = $('#knowledgerule').val();var status = $('#status').val()
          $.ajax({
             url: '<?php echo base_url().'groupuser/updategroup' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {groupid:groupid,ticketrule:ticketrule,taskrule:taskrule,userrule:userrule,knowledgerule:knowledgerule,status:status},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
          });
	function uddateFields()
	{
		var fieldcode = $('#fieldcode').val();
		var fieldname = $('#fieldname').val();
		var status = $('#status').val();
		$.ajax({
             url: '<?php echo base_url().'groupuser/updateFields' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {fieldcode:fieldcode,fieldname:fieldname,status:status},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}

	function deleteButton()
	{
		var category = $('#categorydelete').val();
		var code = $('#codedelete').val();
		var action = 'delete';
		$.ajax({
             url: '<?php echo base_url().'groupuser/updateCodictionary' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {category:category,code:code,action:action},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}

	function updateButton()
	{
		var category = $('#category').val();
		var code = $('.code').val();
		var name = $('.nameField').val();
		var action = 'update';
		$.ajax({
             url: '<?php echo base_url().'groupuser/updateCodictionary' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {category:category,code:code,name:name,action:action},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
	}
</script><file_sep><?php
  if(!$update){
    ?>
    <script type="text/javascript">
        $("#form-ticket *").attr("disabled", "disabled").off('click');
    </script>
    <?php
  }
?> 
<script type="text/javascript">
  $(document).ready(function(){
    search('','','','');
  });

  var tic = $('select[name=agentgroup]').val();
  if (tic!='') {
    $('select[name=agentcurrent] option').each(function(){
      var group = $(this).attr('data-group');
      if (tic==group) {$(this).prop('disabled',false);}
      else{$(this).prop('disabled',true);}
    });
  }

  var tickettype = $('select[name=tickettype]').val();
  if (tickettype!='') {
    $('select[name=groupid] option').each(function(){
      var ref1 = $(this).attr('ref1');
      if (ref1==tickettype) {$(this).removeClass('hide').addClass('show');}
      else{$(this).addClass('hide').removeClass('show');}
    });
    $('select[name=groupid] option.show:first').prop('selected',true);
  }

  var groupid = $('select[name=groupid]').val();
  if (groupid!='') {
    $('select[name=categoryid] option').each(function(){
      var ref2 = $(this).attr('ref2');
      if (ref2==groupid) {$(this).removeClass('hide').addClass('show');}
      else{$(this).addClass('hide').removeClass('show');}
    });
    $('select[name=categoryid] option.show:first').prop('selected',true);
  }



  $('input[name=sla],input[name=duedate],input[name=finishdate],input[name=firstreply],input[name=requestdate]').
  datetimepicker({format:'d-m-Y H:i'});

  var rights = $('select[name=ticketstatus] option:selected').attr('value');
  if (rights==4 || rights==9) {
    $('.crm-control,.crm-ext,textarea,.btn-updateAction,.btn-updateActionUpdate,#btnGroupDrop1').prop('disabled',true);
  }

  var agentcurrent = $('select[name=agentcurrent]').val();
  if (agentcurrent) {
    $('#btn-accept').remove();
  }else{
    $('.crm-control,.crm-ext,btnGroupDrop1').prop('disabled',true);
  }




  $('select[name=ticketchannel],select[name=priority],select[name=ticketstatus]').select2();

  $('select[name=agentgroup]').select2({
    placeholder: "Chọn nhóm phụ trách...",
    allowClear: true,
    ajax: { 
     url: "<?php echo(base_url('api/search_group'));?>",
     type: "post",
     dataType: 'json',
     delay: 250,
     data: function (params) {
      return {
        searchTerm: params.term // search term
      };
     },
     processResults: function (response) {
       return {
          results: response
       };
     },
     cache: true
    }
   });

  $('select[name=agentcurrent]').select2({
    placeholder: "Chọn người phụ trách...",
    allowClear: true,
    ajax: { 
     url: "<?php echo(base_url('api/search_agent'));?>",
     type: "post",
     dataType: 'json',
     delay: 250,
     data: function (params) {
      var tic = $('select[name=agentgroup]').val();
      return {
        groupid:tic,
        searchTerm: params.term // search term
      };
     },
     processResults: function (response) {
       return {
          results: response
       };
     },
     cache: true
    }
   });


  $('select[name=levelticket]').select2({
    placeholder: "Chọn giai đoạn...",
    allowClear: true,
    minimumResultsForSearch: -1,
    ajax: { 
     url: "<?php echo(base_url('api/search_stage'));?>",
     type: "post",
     dataType: 'json',
     delay: 250,
     data: function (params) {
      return {
        searchTerm: params.term // search term
      };
     },
     processResults: function (response) {
       return {
          results: response
       };
     },
     cache: true
    }
   });

  $('select[name=tickettype]').select2({
    placeholder: "Chọn phân loại...",
    allowClear: true,
    minimumResultsForSearch: -1,
    ajax: { 
     url: "<?php echo(base_url('api/search_issue_type'));?>",
     type: "post",
     dataType: 'json',
     delay: 250,
     data: function (params) {
      return {
        searchTerm: params.term // search term
      };
     },
     processResults: function (response) {
       return {
          results: response
       };
     },
     cache: true
    }
   });

  $('select[name=groupid]').select2({
    placeholder: "Chọn nhóm vấn đề...",
    minimumResultsForSearch: -1,
    allowClear: true,
    ajax: { 
     url: "<?php echo(base_url('api/search_issue_group'));?>",
     type: "post",
     dataType: 'json',
     delay: 250,
     data: function (params) {
      var p = $('select[name=tickettype]').val();
      return {
        ref1:p,
        searchTerm: params.term // search term
      };
     },
     processResults: function (response) {
       return {
          results: response
       };
     },
     cache: true
    }
   });

  $('select[name=categoryid]').select2({
    placeholder: "Chọn chi tiết vấn đề...",
    minimumResultsForSearch: -1,
    allowClear: true,
    ajax: { 
     url: "<?php echo(base_url('api/search_issue_detail'));?>",
     type: "post",
     dataType: 'json',
     delay: 250,
     data: function (params) {
      var p = $('select[name=groupid]').val();
      return {
        ref2:p,
        searchTerm: params.term // search term
      };
     },
     processResults: function (response) {
       return {
          results: response
       };
     },
     cache: true
    }
   });



  $('#form-ticket').on('submit',function(){
    var formData = new FormData($(this)[0]);
    var error = [];
    for (var [key, value] of formData.entries()) { 
      // console.log(key, value);
    }
    if (formData.get('agentgroup')==undefined && formData.get('agentcurrent')==undefined) {
      error[key] = '1';
      parent.alertLog('Cảnh báo','Bạn phải nhập 1 trong 2 thông tin: Nhóm phụ trách, Người phụ trách.','warning');
    }
    if (!jQuery.isEmptyObject(error)) {
      var msg = '';
      for (let key in error){
        msg+= error[key]+"\n";
      }
      console.log(msg);
    }else{
      $('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
      $.ajax({
          type: "POST",
          url: "<?php echo base_url().'ticket/aj_insert_ticket';?>",
          data:  formData,
          dataType:'json',
          contentType: false,
          cache: false,
          processData:false,
          beforeSend: function() {
          },
          success: function(data) {
            if(data.code==0){
               $('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
               parent.alertLog("Cảnh báo !", data.message, "warning");
            }else{
               // alert("thêm thành công.");
               parent.alertLog("Thành công !", "Thêm phiếu thành công.", "success");
                var tab = window.top.$('div.tab-pane.active').attr('id');
                window.top.$('li a.nav-link[href="#'+tab+'"]').find('span').html('#'+data.data);
               location.href= '<?php echo base_url().'/ticket/detail/';?>'+data.data;
            }
          },
          error: function(xhr, status, error) {
            console.log(error);
            $(this).prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
          }
      });
    }
    return false;
  });



  $('select[name=tickettype]').change(function(){
    var val = $(this).val();
    if (val) {search('',val,'','');}
  });

  $('select[name=groupid]').change(function(){
    var val = $(this).val();
    if (val) {search('','',val,'');}
  });

  $('select[name=categoryid]').change(function(){
    var val = $(this).val();
    if (val) {search('','','',val);}
  });




  $('#table-23').DataTable( {
    "ajax": "<?php echo base_url('ticket/recent_contract/'.$param['idcard']);?>",
    "paging":         false,
    "info":           false,
    "searching":      false,
    "scrollY":        false,
    "scrollX":        false,
    "scrollCollapse": false,
    "ordering": false,
    "processing": true,
    'language':{ 
       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />"
    },
    "initComplete": function(settings, json){ 
        this.find('thead').css("display","none");
        this.fnAdjustColumnSizing(true);
        $(this).find('tbody td').css('padding','2px 8px');
        
        $(function () {
          $('[data-toggle="tooltip"]').tooltip()
        })
    }
  });
  $('#table-22').DataTable( {
    "ajax": "<?php echo base_url('ticket/recent_ticket/'.$this->uri->segment(4).'/'.$this->session->userdata('custid').'/'.$param['idcard'])?>",
    "paging":         false,
    "info":           false,
    "searching":      false,
    "scrollY":        false,
    "scrollX":        false,
    "scrollCollapse": false,
    "ordering": false,
    "processing": true,
    'language':{ 
       "loadingRecords": "<img style='width:50px; height:50px;' src='<?php echo base_url().'images/ajax-loading.gif' ?>' />"
    },
    "initComplete": function(settings, json){ 
        this.find('thead').css("display","none");
        this.fnAdjustColumnSizing(true);
        $(this).find('tbody td').css('padding','2px 8px');
    }
  });

  $(document).on('change','.crm-control,.crm-ext',function(){
    // $('.btn-updateAction').html('<i class="fa fa-share"></i> Cập nhật phiếu');
    var log = $(this).attr('log');
    var old_value = $(this).attr('old-value');
    var new_value = $(this).val();
    if (log) {
      var text = $(this).find('option:selected').text();
      if (!text) {
        text = $(this).val();
      }
      if (old_value === new_value) {deletelog(log);}else{changelog(log,text);}
    }
  });


  $('.btn-updateActionUpdate').click(function(){
    var cur = $(this);
    var ticketid = $(this).attr('title');
    var cmt= $('textarea[name=cmt]').val();
    if (cmt=='') {
      parent.alertLog('Cảnh báo','Bạn chưa nhập ghi chú cho phiếu.','warning');
    }else{
      cur.prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
     $.ajax({
        url: '<?php echo base_url().'ticket/updateTicketLog' ?>',
        type: 'POST',
        dataType: 'JSON',
        data: {cmt:cmt,ticketid:ticketid},
      })
      .done(function(data) {
          cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
          if(data.code==1){
            $('#action').val('');
            var iframe = window.tck_log;
            iframe.location.reload();
            parent.notification("OK");
            iframe.onload = function() {
             alert('myframe is loaded'); 
            }; // before setting 'src'
          }else{
            alert(data.message);
          }
        })
      .fail(function() {
         cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
         alert('Lỗi hệ thống, vui lòng liên hệ Admin');
      });
    }
    
  });
 
  $('#form-ticket').on('submit',function(){
    var formData = new FormData($(this)[0]);
    var error = [];
    for (var [key, value] of formData.entries()) { 
      // console.log(key, value);
      switch(key){
        case 'customer':
          if (value=='') {
            error[key] = "1";
            parent.alertLog('Cảnh báo','Vui lòng chọn người yêu cầu.','warning');
          }
          break;
        case 'agentgroup':
          if (value=='' && formData.get('agentcurrent') == '') {
            error[key] = '1';
            parent.alertLog('Cảnh báo','Bạn phải nhập 1 trong 2 thông tin: Nhóm phụ trách, Người phụ trách.','warning');
          }else if (value=='' && formData.get('agentcurrent') !='') {
            var agent = $('select[name=agentcurrent]').find('option:selected').attr('data-group');
            console.log(agent);
            if (agent) {formData.set('agentgroup',agent)}
          }
          break;
        default: break;
      }
    }
    if (!jQuery.isEmptyObject(error)) {
      var msg = '';
      for (let key in error){
        msg+= error[key]+"\n";
      }
      console.log(msg);
    }else{
      $('button[type=submit]').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
      $.ajax({
          type: "POST",
          url: "<?php echo base_url().'ticket/aj_update_ticket';?>",
          data:  formData,
          dataType:'json',
          contentType: false,
          cache: false,
          processData:false,
          beforeSend: function() {
          },
          success: function(data) {
            if(data.code==0){
               $('button[type=submit]').prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
               parent.alertLog("Cảnh báo !", data.message, "warning");
            }else{
               // alert("thêm thành công.");
               parent.notification("Ok.");
               window.location.reload();
            }
          },
          error: function(xhr, status, error) {
            console.log(error);
            $(this).prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
          }
      });
    }
    return false;
  });


  $('#btn-ticket-merge').click(function(){
    var old_ticketid = $(this).attr('tck-id'),new_ticketid='';
    var old_status   = $(this).attr('tck-stt');
    var old_title    = $(this).attr('tck-title');
    var stt_cls   = "danger",stt_txt = "OPEN";
    if (old_status==0) {stt_cls="warning";stt_txt="PENDDING"}
    if (old_status==4) {stt_cls="success";stt_txt="SUCCESS"}

    var modal = createModal();
    modal.modal("show").on("hidden", function(){
          modal.remove();
    });
    $.ajax({
      url: '<?php echo base_url().'api/aj_tck_id_title';?>',
      type: 'GET',
      dataType: 'JSON',
    })
    .done(function(data) {
        if(data){
          // console.log(data);
          var option = '';
          for (var i = 0; i < data.length; i++) {
            option += '<option status="'+data[i]['status']+'" value="'+data[i]['ticketid']+'">'+data[i]['title']+'</option>';
          }
          modal.find('.modal-body')
          .html('<div class="table-responsive">\
                    <table class="table margin-bot-5 table1" id="table-1">\
                        <tbody>\
                          <tr class="no-border">\
                            <td class="no-border" width="150">\
                              <span class="id-label span-'+stt_cls+'">'+stt_txt+'</span>  #Ticket '+old_ticketid+'\
                            </td>\
                            <td class="no-border">\
                              '+old_title+'\
                            </td>\
                            \
                          </tr>\
                        </tbody>\
                    </table>\
                </div>\
                <p>Tìm phiếu cần ghép</p>\
                <div id="call-input">\
                      <input class="form-control margin-top-10 margin-bot-5" type="number" placeholder="Nhập mã phiếu được ghép" list="tck_lst">\
                      <datalist id="tck_lst">\
                        '+option+'\
                      </datalist>\
                </div>\
                <div class="table-responsive">\
                    <table class="table margin-bot-5 table2" id="table-1">\
                        <tbody>\
                        </tbody>\
                    </table>\
                </div>');
          modal.find('input').on('keyup',function(){
            var val = $(this).val();
            var opt = modal.find('option[value="'+val+'"]');
            console.log(opt);
            if (opt.length>0) {
              var tck_id    = new_ticketid = opt.attr('value');
              var tck_title = opt.html();
              var tck_stt   = opt.attr('status');
              var stt_cls   = "danger",stt_txt = "OPEN";
              if (tck_stt==0) {stt_cls="warning";stt_txt="PENDDING"}
              if (tck_stt==4) {stt_cls="success";stt_txt="SUCCESS"}
              modal.find('.modal-body table.table2 tbody').
              html('<tr class="no-border">\
                <td class="no-border" width="150">\
                  <span class="id-label span-'+stt_cls+'">'+stt_txt+'</span>  #Ticket '+tck_id+'\
                </td>\
                <td class="no-border">\
                  '+tck_title+'\
                </td>\
              </tr>');
            }else{
              new_ticketid = '';
              modal.find('.modal-body table.table2 tbody').
              html('');
            }
          });

          modal.find('button#submit').click(function(){
            var cur = $(this);
            if (new_ticketid=='') {
              parent.alertLog('Cảnh báo','Vui lòng chọn 1 ticket','warning');
            }else{
              modal.find('button').prop('disabled',true);
              cur.find('i').addClass('fa fa-spinner fa-spin');
            $.ajax({
                url: '<?php echo base_url().'api/aj_merge_ticket';?>',
                type: 'POST',
                dataType: 'JSON',
                data: {oldticket:old_ticketid,newticket:new_ticketid},
              })
              .done(function(data) {
                  console.log(data);
                  if (data.code==1) {
                    console.log('ok');
                    modal.find('button').prop('disabled',false);
                    modal.find('button#remove').click();
                    parent.notification("Ghép phiếu thành công");
                    window.location.reload();
                  }else{
                    modal.find('button').prop('disabled',false);
                    cur.find('i').removeClass('fa fa-spinner fa-spin');
                  }
                })
              .fail(function() {
                 modal.find('button').prop('disabled',false);
                 cur.find('i').removeClass('fa fa-spinner fa-spin');
                 alert('error');
              });
            }
          });
        }
      })
    .fail(function() {
       parent.alertLog('Cảnh báo','Lỗi kết nối.','warning');
    });
  });

  $('#btn-accept').click(function(){
    var cur = $(this);
    var tckid = $(this).attr('tckid');
    if (tckid)
    cur.prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
    $.ajax({
        url: '<?php echo base_url().'ticket/get_to_my_ticket/'?>'+tckid,
        type: 'POST',
        dataType: 'JSON',
      })
      .done(function(data) {
          if(data.code==1){
            parent.notification('Tiếp nhận phiếu thành công.');
            window.location.reload();
          }else{
            parent.alertLog('Lỗi',data.message,'danger');
            // alert(data.message);
          }
        })
      .fail(function() {
         cur.prop('disabled',false).find('i').removeClass().addClass('fa fa-share');
         alert('Lỗi hệ thống, vui lòng liên hệ Admin');
      });
  });

  function createModal(){
    var modal = $(
            '<div class="modal fade">\
                  <div class="modal-dialog" role="document" style="top:15%;">\
                        <div class="modal-content">\
                              <div class="modal-header">\
                                    <h5 class="modal-title">Ghép vào một phiếu khác</h5>\
                                    <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\
                              </div>\
                              <div class="modal-body relative">\
                                    <i class="fa fa-spinner fa-spin" style="position:absolute;top:30%;left:49%;font-size:18px;"></i>\
                              </div>\
                              <div class="modal-footer">\
                                    <button class="btn btn-primary btn-89" type="button" id="remove" data-dismiss="modal">Hủy</button>\
                                    <button class="btn btn-secondary btn-89" type="button" id="submit"><i></i>Ghép</button>\
                              </div>\
                        </div>\
                  </div>\
            </div>');  
    return modal;
  }

  function changelog(log,text){
      var oldchange = $('input[name=changelog]').val();
      var newchange = '';
      var arr_log = oldchange.split('|');
      if (arr_log.length>0) {
        for (var i = 0; i < arr_log.length; i++) {
          // console.log(arr_log[i]);
          if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){
            newchange += arr_log[i].trim()+" | ";
          }
        }
      }
      newchange += log+': '+text+" | ";
      console.log(newchange);
      $('input[name=changelog]').val(newchange);
      return false;
    }
  function deletelog(log){
      var oldchange = $('input[name=changelog]').val();
      var newchange = '';
      var arr_log = oldchange.split('|');
      if (arr_log.length>0) {
        for (var i = 0; i < arr_log.length; i++) {
          // console.log(arr_log[i]);
          if(arr_log[i]!= ' ' && arr_log[i]!= '' && arr_log[i].indexOf(log) == -1){
            newchange += arr_log[i].trim()+" | ";
          }
        }
      }
      console.log(newchange);
      $('input[name=changelog]').val(newchange);
      return false;
    }
  function fillExtTicket(magd,idcanho)
    {
      $('input[name="transref"]').val(magd);
      $('input[name="ext[duan]"]').val(magd.substring(0, 3));
      $('input[name="ext[canho]"]').val(idcanho);
      $('[data-toggle="tooltip"]').tooltip('hide');
    }
  function showDetailKnowledge(id){
    var show = $('.knl-caret');
    if (show.hasClass('fa-angle-double-up')) {$('.knl-caret').trigger('click');}
    $('#knl_list').css('display','none');
    $('.knl-content').html("Đang tải dữ liệu...").css('display','block');
      $.ajax({
        url: '<?php echo base_url().'knowledge/detailKnowledge' ?>',
        type: 'POST',
        dataType: 'JSON',
        data: {id:id},
      })
      .done(function(data) {
          $('.knl-content').html(data.data[0].article).css('display','block');
        })
      .fail(function() {
         alert('Lỗi hệ thống, vui lòng liên hệ Admin');
      });
  }
</script>
<file_sep><?php
// error_reporting(0);
// ini_set('display_errors', 0);
defined('BASEPATH') OR exit('No direct script access allowed');

class Issuetype extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url'));
        $this->load->model('M_api');
    }

    public function index(){
        $list_extend['list_ext'] = [];
        $list_extend['detail'] =[];
        $fieldtype = 'D';
        if($fieldtype == 'D')
        {
            $datasource = 'tcktype';
            $_jsonlistext = file_get_contents('http://test.tavicosoft.com/crm/index.php/codedictionary/selectall/'.$datasource);
            $list_ext = json_decode($_jsonlistext,true);
            $list_extend['list_ext'] = $list_ext['data']; 
        }
        $_body = [];
        $_body['left'] = $this->load->view('datasource/issuetype/it_left',null,TRUE); 
        $_body['center'] = $this->load->view('datasource/issuetype/it_center', $list_extend, TRUE);
        $_data = [];    
        $_data['script'] = $this->load->view('script/script_datastage', NULL, TRUE); 
        $_data['mainview'] = $this->load->view('datasource/issuetype/form', $_body , TRUE);
        $this->load->view('dashboard',$_data);
    }
}<file_sep><?php
ob_start();
class Api extends CI_Controller{

    public $menu = array();
    public function __construct() {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url','json_output'));
        $this->load->model(array('M_api'));
    }

    public function get_erp_token($loginid=''){

        if ($loginid=='') {
            $result = null;
            json_output(200,$result);
        }else{

        $url = "https://demo.tavicosoft.com/DirectRouter/Index";
        $action = 'ConnectDB';
        $method = 'loginToken';
        $data = array(array(
            'loginid'=>$loginid
            )
        );
        $type='rpc';
        $tid=1;

        $result = $this->M_api->execute_tvc_api($url,$action,$method,$data,$type,$tid);
        // var_dump($result);
        json_output(200,$result);
        }
    }

    public function get_list_contract(){

        // $post = $this->input->post();

        $post = json_decode(file_get_contents('php://input'), true);

        // var_dump($post);

        if (empty($post)) {
            json_output(200,'null');
        }else{

        $reportcode = isset($post['reportcode'])?$post['reportcode']:'';
        $action = isset($post['action'])?$post['action']:'FrmFdReport';
        $method = isset($post['method'])?$post['method']:'qry';
        $limit = isset($post['limit'])?$post['limit']:25;
        $start = isset($post['start'])?$post['start']:0;

        $queryFilters['contractid'] = 
            isset($post['queryFilters']['contractid'])?$post['queryFilters']['contractid']:'';
        $queryFilters['property'] = 
            isset($post['queryFilters']['property'])?$post['queryFilters']['property']:'';
        $queryFilters['clientname'] = 
            isset($post['queryFilters']['clientname'])?$post['queryFilters']['clientname']:'';
        $queryFilters['idcard'] = 
            isset($post['queryFilters']['idcard'])?$post['queryFilters']['idcard']:'';
        $queryFilters['telephone'] = 
            isset($post['queryFilters']['telephone'])?$post['queryFilters']['telephone']:'';
        $queryFilters['email'] = 
            isset($post['queryFilters']['email'])?$post['queryFilters']['email']:'';
        $queryFilters['address'] = 
            isset($post['queryFilters']['address'])?$post['queryFilters']['address']:'';
   
        $url = "https://demo.tavicosoft.com/DirectRouter/Index";
        $data = array(array(
        	'reportcode'=>$reportcode,
        	'limit'=>$limit,
        	'start'=>$start,
        	'queryFilters'=>array(
                array('name'=>'contractid','value'=>$queryFilters['contractid']),
        		array('name'=>'property','value'=>$queryFilters['property']),
        		array('name'=>'clientname','value'=>$queryFilters['clientname']),
        		array('name'=>'idcard','value'=>$queryFilters['idcard']),
        		array('name'=>'telephone','value'=>$queryFilters['telephone']),
        		array('name'=>'email','value'=>$queryFilters['email']),
        		array('name'=>'address','value'=>$queryFilters['address'])
			))
        );
        $type='rpc';
        $tid=1;

        $result = $this->M_api->execute_tvc_api($url,$action,$method,$data,$type,$tid);
        // var_dump($result);
        json_output(200,$result);
    }}

    public function get_infor_user($phone){
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/select/'.$phone);
        $data = json_decode($json,true);
        json_output(200,$data);
    }

    public function get_normal_api(){
        $data = array(
            'reportcode'=>'crmContract01f',
            'limit'=>25,
            'start'=>0,
            'method'=>'qry',
            'queryFilters'=>array(
                'contractid'=>'AGR00333',
                'property'=>'',
                'clientname'=>'',
                'idcard'=>'',
                'telephone'=>'',
                'email'=>'',
                'address'=>''
            )
        );

        $result = $this->M_api->execute_normal_api("http://crm.tavicosoft.com/api/get_list_contract",$data);
        // var_dump($result);
        json_output(200,json_decode($result,true));
    }

    public function aj_tvc_isrt_user($telephone=''){

        $custid = $this->M_api->gen_custid();

        $postdata = http_build_query([
            'custid'=>$custid,
            'custname'=>$telephone,
            'telephone'=>$telephone,
            'idcard'=>$telephone,
            'email'=>$telephone,
            'groupid'=>3,
            'roleid'=>3
        ]); 
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/insert',false,$context);
        $array = json_decode($result,true);
        // var_dump($result);
        $array[0]['custid'] = $custid;
        json_output(200,$array);
    }

    public function aj_crm_isrt_ticket(){

        // var_dump($this->input->post());
        $var = $this->session->userdata;
        $log_groupid = $var['groupid'];

        $ticketchanel = $this->input->post('ticketchanel');
        $priority = $this->input->post('priority');
        $custid = $this->input->post('custid');
        $phone = $this->input->post('phone');
        $callrefid = $this->input->post('callrefid');
        $agentcreated = $this->input->post('agentcreated');
        $queue = $this->input->post('queue');
        $tickettype = '1';

        if ($queue) {
            //tieng anh
            if ($queue=='21121') {
                $tickettype='1';
            }
            if ($queue=='21114') {
                $tickettype='1';
            }
            if ($queue=='21115') {
                $tickettype='2';
            }
            if ($queue=='21116') {
                $tickettype='3';
            }
        }

        $postdata = http_build_query([
                'ticketchannel' => $ticketchanel,
                'agentcreated' => $agentcreated,
                'agentcurrent' => $agentcreated,
                'custid' => $custid,
                'priority' => $priority,
                'title' =>'Hỗ trợ khách hàng '.$phone,
                'ticketusers' => $agentcreated,
                'callrefid' => $callrefid,
                'tickettype' => $tickettype,
                'log_groupid' => $log_groupid
        ]); 
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        // var_dump($postdata);
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert',false,$context);

        // var_dump($result);

        json_output(200,json_decode($result,true));
    }

    public function aj_crm_isrt_tcklog(){
        // var_dump($this->input->post());

        $ticketid = $this->input->post('ticketid');
        $phone = $this->input->post('phone');
        $callrefid = $this->input->post('callrefid');
        $agentcreated = $this->input->post('agentcreated');
        $record = $this->input->post('record');
        $duration = $this->input->post('duration');
        $tonum = $this->input->post('tonum');

        $postdata = http_build_query([
                'ticketid' => $ticketid,
                'action' => 'Lưu record từ cuộc gọi '.$phone,
                'useraction' => $agentcreated,
                'srcrecord' => $record,
                'changelog' => 'From: '.$phone.' | To: '.$tonum.' | Duration: '.$duration.'s',
                'callrefid' => $callrefid
        ]); 
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        // var_dump($postdata);
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/insert_ticketlog',false,$context);

        // var_dump($result);

        json_output(200,json_decode($result,true));
    }

    public function aj_mitek_hang_up($SIP,$channel){

        $curl = curl_init();

        $url = 'https://apipbx03.micxm.vn/api/v1/call/hangup?channel='.$SIP.'/'.$channel.'&secret=ac97db2cca493ad87045946aed59eb29';

        curl_setopt_array($curl, array(
          CURLOPT_URL => $url,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => array(
            "Cache-Control: no-cache"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
          json_output(400,$err);
        } else {
          json_output(200,json_decode($response,true));
        }
    }

    public function aj_mitek_agt_stt($extension){
        $json = file_get_contents('https://apipbx03.micxm.vn/api/v1/call/getstatusagent?extension='.$extension);
        $data = json_decode($json,true);
        json_output(200,$data);
    }

    public function aj_mitek_tranfer($extension,$SIP,$channel){
        $json = file_get_contents('https://apipbx03.micxm.vn/api/v1/call/transferCall?extension='.$extension.'&channel='.$SIP.'/'.$channel.'&secret=ac97db2cca493ad87045946aed59eb29');
        // echo ('https://apipbx03.micxm.vn/api/v1/call/transferCall?extension='.$extension.'&channel='.$SIP.'/'.$channel.'&secret=ac97db2cca493ad87045946aed59eb29');
        $data = json_decode($json,true);
        json_output(200,$data);
    }

    public function aj_mitek_clicktocall($extension,$phone){
        $json = file_get_contents('https://apipbx03.micxm.vn/api/v1/call/clicktocall?extension='.$extension.'&phone='.$phone.'&secret=ac97db2cca493ad87045946aed59eb29');
        $data = json_decode($json,true);
        json_output(200,$data);
    }


    public function avatar($cusid){
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/api/search?action=search_customer&search=&custid='.$cusid.'&telephone=&roleid=1');
        $data = json_decode($json,true);
        if($data['code']==1){
            $avatar = $data['data'][0]['avatar'];
            redirect($avatar, 'location');
        }else{
            redirect('https://s3.amazonaws.com/uifaces/faces/twitter/dancounsell/128.jpg', 'location');
        }
    }


    public function getlistormuser(){

        // $post = $this->input->post();

        $post = json_decode(file_get_contents('php://input'), true);

        $url = "https://demo.tavicosoft.com/DirectRouter/Index";
        $action = 'FrmFdReport';
        $method = 'getReturnData';
        $data = array(array(
            'reportcode'=>'crmCustomer01',
            'limit'=>400,
            'start'=>0)
        );
        $type='rpc';
        $tid=1;

        $result = $this->M_api->execute_tvc_api($url,$action,$method,$data,$type,$tid);
        $result_array = json_decode($result,true);
        // var_dump($result_array['result']);
        $data = $result_array['result']['data'];
        echo count($data);
        foreach ($data as $user) {
            $user['custid'] = $this->M_api->gen_custid();
            $user['groupid'] = 3;
            $user['roleid'] = 3;
            foreach ($user as $key => $value) {
                // echo $key.'=>'.$value.'<br>';
                if ($key=='email'||$key=='idcard') {
                    if ($user['email']=='') {
                        $user['email']=$user['idcard'];
                    }
                    // echo $key.'=>'.$value.'<br>';
                }
                
                if ($value==null) {
                    $user[$key]=='';
                }
            }
            $postdata = http_build_query($user); 
            $opts = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata
                )
            );

            $context  = stream_context_create($opts);

            $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/customer/insert',false,$context);
            $array = json_decode($result,true);
            // var_dump($user);
            var_dump($array);
            // json_output(200,$array);

            // var_dump($user);
            echo "<br>";
            // exit;
            # code...
        }
        // json_output(200,$data);
    }

    public function save_call_log(){
        $post = $this->input->post();

        $event  = isset($post['event'])?$post['event']:'';
        $object = isset($post['object'])?$post['object']:'';
        $value  = isset($post['value'])?$post['value']:[];

        $mitek = [];

        $mitek['callRefId']            = array(isset($value['callrefid'])?$value['callrefid']:'');
        $mitek['startDate']            = isset($value['calldate'])?date('Y-m-d H:i:s',strtotime($value['calldate'])):'';
        $mitek['endDate']              = isset($value['endtime'])?date('Y-m-d H:i:s',strtotime($value['endtime'])):'';
        $mitek['secret']               = 'ac97db2cca493ad87045946aed59eb29';

        $raw_data = json_encode($mitek);          

        $ch = curl_init('https://api-prod.mipbx.vn/api/dev/cdr/getCallsLog');

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data);                                                                  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
            'Content-Type: application/json;charset=uft-8'                                                                    
        ));                                                                                                             

        $result = curl_exec($ch);

        // var_dump($mitek);

        $response = json_decode($result,true);
        if (isset($response[0])) {
            $rs = $this->save_call_info($response[0]);
            echo $rs;   
        }else{
            json_output(200,array('code'=>1,'message'=>'Lấy dữ liệu từ mitek thất bại.'));
            exit;
        }
    }

    private function save_call_info($value){
        $push = [];

        $push['callRefId']            = isset($value['callRefId'])?$value['callRefId']:'';
        $push['callStartTime']        = isset($value['callStartTime'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['callStartTime']))):'';
        $push['duration']             = isset($value['duration'])?$value['duration']:'';
        $push['billSec']              = isset($value['billSec'])?$value['billSec']:'';
        $push['src']                  = isset($value['src'])?$value['src']:'';
        $push['dst']                  = isset($value['dst'])?$value['dst']:'';
        $push['callStatus']           = isset($value['callStatus'])?$value['callStatus']:'';
        $push['createdby']            = $this->session->userdata('custid');

        foreach ($push as $k => $v) {
            if ($v=='') {
                unset($push[$k]);
            }
        }

        // var_dump($push);

        $postdata   = http_build_query($push);
        $opts       = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context  = stream_context_create($opts);

        $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/callinfo/insertcallinfo',false,$context);
        return $result;
    }

    // private function save_call_info($value){
    //     $push = [];

    //     $push['callrefid']            = isset($value['recid'])?$value['recid']:'';
    //     $push['calldate']             = isset($value['callDate'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['callDate']))):'';
    //     $push['starttime']            = isset($value['startTime'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['startTime']))):'';
    //     $push['endtime']              = isset($value['endTime'])?date('Y-m-d H:i:s',strtotime(str_replace('/','-',$value['endTime']))):'';
    //     $push['duration']             = isset($value['duration'])?$value['duration']:'';
    //     $push['billsec']              = isset($value['billSec'])?$value['billSec']:'';
    //     $push['waittime']             = isset($value['waitTime'])?$value['waitTime']:'';
    //     $push['recordingfile']        = isset($value['recFile'])?$value['recFile']:'';
    //     $push['queue']                = isset($value['queue'])?$value['queue']:'';
    //     $push['fromnumber']           = isset($value['src'])?$value['src']:'';
    //     $push['tonumber']             = isset($value['dst'])?$value['dst']:'';
    //     $push['status']               = isset($value['disposition'])?$value['disposition']:'';
    //     $push['calltype']             = isset($value['calltype'])?$value['calltype']:'';
    //     $push['transfercallrefid']    = isset($value['transfercallrefid'])?$value['transfercallrefid']:'';
    //     $push['transferidto']         = isset($value['dstForward'])?$value['dstForward']:'';
    //     $push['extension']            = isset($value['cnam'])?$value['cnam']:'';
    //     $push['extensiontransferto']  = isset($value['extensiontransferto'])?$value['extensiontransferto']:'';
    //     $push['createdby']            = $this->session->userdata('custid');

    //     foreach ($push as $k => $v) {
    //         if ($v=='') {
    //             unset($push[$k]);
    //         }
    //     }

    //     // var_dump($push);

    //     $postdata   = http_build_query($push);
    //     $opts       = array('http' =>
    //         array(
    //             'method'  => 'POST',
    //             'header'  => 'Content-type: application/x-www-form-urlencoded',
    //             'content' => $postdata
    //         )
    //     );
    //     $context  = stream_context_create($opts);

    //     $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/callinfo/insert',false,$context);
    //     return $result;
    // }

    public function aj_tck_id_title(){
        $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/sl_tck_by_match/ticketid.title.status/'.$this->session->userdata('custid'));
        $data = json_decode($json,true)['data'];
        json_output(200,$data);
    }

    public function aj_merge_ticket(){
        $post = $this->input->post();
        $oldticket = isset($post['oldticket'])?$post['oldticket']:'';
        $newticket = isset($post['newticket'])?$post['newticket']:'';
        if ($oldticket!='' && $newticket!='') {
            $json = file_get_contents('http://test.tavicosoft.com/crm/index.php/ticket/mergeticket/'.$oldticket.'/'.$newticket);
            // $data = json_decode($json,true);
            echo $json;
        }else{
            json_output(200,"expected argument.");
        }
        
    }

    // public function save_call_log(){
    //     $post = $this->input->post();

    //     $event  = isset($post['event'])?$post['event']:'';
    //     $object = isset($post['object'])?$post['object']:'';
    //     $value  = isset($post['value'])?$post['value']:[];

    //     $push = [];

    //     $push['event']  = $event;
    //     $push['object'] = $object;

    //     $push['callrefid']            = isset($value['callrefid'])?$value['callrefid']:'';
    //     $push['calldate']             = isset($value['calldate'])?$value['calldate']:'';
    //     $push['starttime']            = isset($value['starttime'])?$value['starttime']:'';
    //     $push['endtime']              = isset($value['endtime'])?$value['endtime']:'';
    //     $push['duration']             = isset($value['duration'])?$value['duration']:'';
    //     $push['billsec']              = isset($value['billsec'])?$value['billsec']:'';
    //     $push['waittime']             = isset($value['waittime'])?$value['waittime']:'';
    //     $push['recordingfile']        = isset($value['recording_file'])?$value['recording_file']:'';
    //     $push['queue']                = isset($value['queue'])?$value['queue']:'';
    //     $push['fromnumber']           = isset($value['fromnumber'])?$value['fromnumber']:'';
    //     $push['tonumber']             = isset($value['tonumber'])?$value['tonumber']:'';
    //     $push['status']               = isset($value['status'])?$value['status']:'';
    //     $push['calltype']             = isset($value['calltype'])?$value['calltype']:'';
    //     $push['transfercallrefid']    = isset($value['transfercallrefid'])?$value['transfercallrefid']:'';
    //     $push['transferidto']         = isset($value['transferidto'])?$value['transferidto']:'';
    //     $push['extension']            = isset($value['extension'])?$value['extension']:'';
    //     $push['extensiontransferto']  = isset($value['extensiontransferto'])?$value['extensiontransferto']:'';
    //     $push['createdby']            = $this->session->userdata('custid');

    //     foreach ($push as $k => $v) {
    //         if ($v=='') {
    //             unset($push[$k]);
    //         }
    //     }

    //     // var_dump($push);

    //     $postdata   = http_build_query($push);
    //     $opts       = array('http' =>
    //         array(
    //             'method'  => 'POST',
    //             'header'  => 'Content-type: application/x-www-form-urlencoded',
    //             'content' => $postdata
    //         )
    //     );
    //     $context  = stream_context_create($opts);

    //     $result = file_get_contents('http://test.tavicosoft.com/crm/index.php/callinfo/insert',false,$context);
    //     echo $result;
    // }
}
// {
//   "secret":"ac97db2cca493ad87045946aed59eb29",
//   "startDate": "2018-08-01 00:00:00",
//   "endDate": "2018-09-06 17:11:24",
//   "extensions": [
//     "2300",
//     "2301",
//     "2302",
//     "2303",
//     "2304",
//     "2305",
//     "2306",
//     "2307",
//     "2308",
//     "2309"
//   ],
//   "search": "",
//   "sorts": {
//     "calldate": "desc"
//   },
//   "page": 1,
//   "recordsOnPage": 10,
//   "dsts": [],
//   "srcs": [],
//   "dispositions": [],
//   "getList": true,
//   "typeFilter": "total"
// }<file_sep><script type="text/javascript">
   function locphieu($custid,$status,$lienquan){
      document.getElementById('iframesearch').src = "<?php echo base_url()?>search/rightSearchTicket/?search=&agentcreated=&agentcurrent="+$custid+"&priority=&status="+$status+"&lienquan="+$lienquan;
   }

   function loctheonhom(type){
      	 document.getElementById('iframesearch').src = "<?php echo base_url()?>search/ticketByType/"+type;
   }

</script><file_sep><main class="app-content padding-5 no-padding-right">
    <div class="row">
        <div class="col-md-2 col-md-22 padding-left-15">
          	<?php echo isset($left)?$left:'' ?>
        </div>

        <div class="col-md-7 padding-left-1">
          	<?php echo isset($center)?$center:'' ?>
        </div>
        <div class="col-md-2 col-md-18 padding-left-5">
        	<div class="tile">
	            <h5>Cập nhật</h5>
			    <p class="margin-top-10 no-margin-bot">Cập nhật thông tin khách hàng đã có trên hệ thống OMS, việc đồng bộ được thực hiện sau mỗi 05 phút. Để đảm bảo dữ liệu là mới nhất, người dùng có thể đồng bộ chủ động bằng lệnh dưới đây.</p>
			    <a href="#">- Đồng bộ Thông tin khách hàng...</a>
			</div>
        </div>
    </div>
</main><file_sep><script type="text/javascript">
      $(".nav-tabs").on("click", "a", function (e) {
              e.preventDefault();
              if (!$(this).hasClass('add-contact')) {
                  $(this).tab('show');
              }
                })
                .on("click", ".fa-times", function () {
                  var id = $(".nav-tabs").children().length;
                  // alert(id);
                  var widthsub = window.top.$('.nav-insert').width() * 2;
                  var width = window.top.$('#lengthmenu').width() - widthsub;
                  if(id >4)
                  {
                      $("ul.nav-tabs li").each(function(){
                        $(this).attr('style', 'width:'+width/(id)+'px !important;');
                      });
                     
                  }
                  else{
                    $("ul.nav-tabs li").each(function(){
                        $(this).attr('style', 'width:170px !important;');
                      });
                  }
                  if(id >1)
                  {
                    var anchor = $(this).siblings('a');
                    $(anchor.attr('href')).remove();
                    $(this).parent().remove();
                    $('.nav-tabs li:nth-child(' + (id-1) + ') a').click();
                  }
       });
          $('#udpategroup_btn').click(function(){
               var groupid = $('#groupid').val();
               var ticketrule = $('#ticketrule').val();
               var taskrule = $('#taskrule').val();
               var userrule = $('#userrule').val();
               var knowledgerule = $('#knowledgerule').val();var status = $('#status').val()
          $.ajax({
             url: '<?php echo base_url().'groupuser/updategroup' ?>',
             type: 'POST',
             dataType: 'JSON',
             data: {groupid:groupid,ticketrule:ticketrule,taskrule:taskrule,userrule:userrule,knowledgerule:knowledgerule,status:status},
           })
           .done(function(data) {
               if(data.code==1){
                 window.location.reload();
               }else{
                 alert(data.message);
               }
             })
           .fail(function() {
              alert('Lỗi hệ thống, vui lòng liên hệ Admin');
           });
          });  
          $('a.app-menu__item').click(function(){
              $('a.app-menu__item').removeClass("active");
              $(this).addClass("active");
          });
        $('#formChangePass').on('submit',function(){
          // e.preventDefault();
          if($('#new_pass').val() != $('#confirm_pass').val())
          {
              swal("Không trùng !", "Mật khẩu mới và xác nhận không trùng.", "error");
          }
          else{

          var formData = new FormData($(this)[0]);
          $('#btn_changepass').prop('disabled',true).find('i').removeClass().addClass('fa fa-spin fa-spinner');
            $.ajax({
              url: '<?php echo base_url() ?>dashboard/changePassword',
              dataType: 'JSON',
              type: 'POST',
              contentType: false,
              cache: false,
              processData:false,
              data: formData
            })
            .done(function(data){
                if(data.code == 1)
                {
                  $('#btn_changepass').prop('disabled',false).find('i').removeClass();
                  swal("Thành công !", data.message, "success");
                  $('#modalChangePass').modal('toggle');
                  $('#old_pass').val('');
                  $('#new_pass').val('');
                  $('#confirm_pass').val('');
                }
                else{
                  $('#btn_changepass').prop('disabled',false).find('i').removeClass();
                  swal("Lỗi !", data.message, "error");
                }
            })
            .fail(function(){

            });
          }
          return false;
        });
</script><file_sep><script type="text/javascript">
	$(document).ready(function(){
		$('#modalDelete').on('shown.bs.modal', function (e) {
  			var telephone = $(e.relatedTarget).data('telephone');
			$(e.currentTarget).find('input[name="telephone"]').val(telephone);
			var queue = $(e.relatedTarget).data('queue');
			$(e.currentTarget).find('input[name="queue"]').val(queue);
		});
		$('#modalUpdate').on('shown.bs.modal', function (e) {
  			var telephone = $(e.relatedTarget).data('telephone');
			$(e.currentTarget).find('input[name="telephone_update"]').val(telephone);
			var status_update = $(e.relatedTarget).data('status');
			$(e.currentTarget).find('input[name="status_update"]').val(status_update);
		});
	})
	function changeiFrameQueue()
	  {
	      var ref1 = $('#queue_code').val();
	      document.getElementById('iframeQueue').src = "<?php echo base_url() ?>queue/rightFilter?queue="+ref1;
	  }

	  function logoutButton()
	  {
	  	var telephone = $('#telephone').val();
	  	var queue = $('#queue').val();
	  	$.ajax({
	  		url: '<?php echo base_url() ?>queue/logoutQueue',
	  		type: 'POST',
	  		dataType: 'JSON',
	  		data : {telephone: telephone, queue:queue}
	  	})
	  	.done(function(data){
	  		if(data.code == 200)
	  		{
		  			window.location.reload();
	  		}
	  	})
	  	.fail(function(){
	  		alert("Lỗi hệ thống xin vui lòng liên hệ admin!!");
	  	});
	  }

	  function loginButton()
	  {
	  	var telephone = $('#telephone_login').val();
	  	var queue = $('#queue_login').val();
	  	var status = $('#status_insert').val();
	  	$.ajax({
	  		url: '<?php echo base_url() ?>queue/loginQueue',
	  		type: 'POST',
	  		dataType: 'JSON',
	  		data : {telephone: telephone, queue:queue, status:status}
	  	})
	  	.done(function(data){
	  		if(data.code == 200)
	  		{
		  		if (data.result.response == "Error" && data.result.message.indexOf("ready there"))
		  		{
		  			alert('Số điện thoại đã ở hàng đợi này!!');
		  		} 
		  		else if(data.result.response == "Success")
		  		{
		  			window.location.reload();
		  		}
	  		}
	  		else if(data.code ==400)
	  		{
	  			if (data.message.indexOf("not valid"))
		  		{
		  			alert('Số điện thoại hoặc hàng đợi không hợp lệ!!');
		  		}
	  		}
	  	})
	  	.fail(function(){

	  	});
	  }
</script>