<?
include getenv("DOCUMENT_ROOT")."/include/session_include.php";

//$func->checkAdmin("index.php");

$m_uid = trim($_POST["muid"]);

//echo "[$m_uid]";exit;

if ($m_uid == "") $mode = "create";
else $mode = "update";

if ($mode == "") $mode = "update";

if ($mode == "create") {
	$btnName = "CREATE";
}
else if ($mode == "update") {
	$btnName = "UPDATE";
	$admTag = "DISABLED";
}

if ($m_uid != "") {
		// Get Information
		$query = "SELECT * FROM tbl_member WHERE m_uid = '".$m_uid."' ";
		$result=$jdb->fQuery($query, "fetch query error");
		//	echo"$query";

		for($i=0; $i<sizeof($result); $i++)
		{
			//list($key, $value) = each($result);
			foreach ( (Array) $result as $key => $value )			
				$$key = $value;
		}

		$m_firstnameSTR = str_replace("\\", "", $m_firstname);
		$m_lastnameSTR = str_replace("\\", "", $m_lastname);
		$m_initialSTR = str_replace("\\", "", $m_initial);
		
		$m_cellSTR = preg_replace('/[^A-Za-z0-9\-]/', '', $m_cell);
		$m_cellSTR = str_replace("\\", "", $m_cellSTR);
		$m_cellSTR = str_replace("-", "", $m_cellSTR);
		$m_cellSTR = substr ($m_cellSTR, 0, 3)."-".substr ($m_cellSTR, 3, 3)."-".substr ($m_cellSTR, 6, 4);
		$m_commentSTR = str_replace("\\", "", $m_comment);
		
		$m_signupdateSTR = $func -> convertFormat ($m_signupdate, 1);
		$m_logindateSTR = $func -> convertFormat ($m_logindate, 1);
}

if ($m_level == 9) $hiddenTag = "";
else $hiddenTag = "hidden";
		

// Get Status Info
foreach ($arrStatus AS $key=>$value)
{
	//echo "[$key][$value]";   => [0][Waiting][1][Confirmed][E][Declined]...
	
	if ($key == $m_status) $selectStr = "selected";
	else $selectStr = "";
	
	if ($key != 'F') {
			$m_statusSTR .= "
								<option value='$key' $selectStr>$value</option>";
	}

}


// Get Member Level
foreach ($arrMemberLevel AS $key=>$value)
{
	//echo "[$key][$value]";   => [0][Waiting][1][Confirmed][E][Declined]...
	
	if ($key == $m_level) $selectStr = "selected";
	else $selectStr = "";
	
	$m_levelSTR .= "
								<option value='$key' $selectStr>$value</option>";
}





// Get Region Info
$qry_region = "SELECT * FROM tbl_region WHERE rg_status = 'A' ORDER by rg_region ASC ";
$rt_region = $jdb->nQuery($qry_region, "list error"); 

while($lt_region=mysqli_fetch_array($rt_region, MYSQLI_ASSOC)) {

	if ($lt_region['rg_uid'] == $m_regionuid) $selectStr = "selected";
	else $selectStr = "";
	
	$m_regionSTR .= "
								<option value='".$lt_region['rg_uid']."' $selectStr>".$lt_region['rg_region']."</option>";								
														
}


// Get Driver Info
$qry_driver = "SELECT * FROM tbl_driver WHERE dr_status = 'A' ORDER by dr_initial ASC ";
$rt_driver = $jdb->nQuery($qry_driver, "list error"); 

while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {

	if ($lt_driver['dr_uid'] == $m_defaultdriver) $selectdefStr = "selected";
	else $selectdefStr = "";
	
	$m_defaultdriverSTR .= "
								<option value='".$lt_driver['dr_uid']."' $selectdefStr>".$lt_driver['dr_initial']."</option>";								
								

	if ($lt_driver['dr_uid'] == $m_currentdriver) $selectcurStr = "selected";
	else $selectcurStr = "";
	
	$m_currentdriverSTR .= "
								<option value='".$lt_driver['dr_uid']."' $selectcurStr>".$lt_driver['dr_initial']."</option>";
																
}



?>


<SCRIPT>

// xmlhttp RUN script
function xmlhttpPost(strURL, param, tagID) {

    var xmlHttpReq = false;
    var self = this;

    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }

    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText, tagID);
        }
    }
    self.xmlHttpReq.send(getquerystring(param));
}


function getquerystring(param) {

    qstr = 's=' + escape(param);  // NOTE: no '?' before querystring
    return qstr;
}



function updatepage(str, tagID){

    document.getElementById(tagID).innerHTML = str;
}

	
function checkEmail() {
	var str = document.getElementById('m_userid').value;
	//alert(str);

	str = str.toLowerCase();

  if (str=="") {
    //document.getElementById("PPMUNITPRICEid").value="";
    //return;
  } 

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    	var rt = xmlhttp.responseText;
    	//alert(rt);
    	   	
 		if (rt.trim() >= 1) {

    		//alert("Existing no. Please change the no.");
    		//document.getElementById("emailcheckid").innerHTML= "<font color='#FF0000'>(Existing Email. Please input other Email.)</font>";
    		//document.getElementById('PPPPONOid').value="";
    		document.getElementById('emailValidateid').value = 0;
				//alert('This email is already in use. Please enter a different email.');
				$('#myModal').find('.modal-body').text('This email is already in use. Please enter a different email.');
				$('#myModal').modal('show');		
				$('#myModal').on('hidden.bs.modal', function () {
						document.getElementById('m_userid').value = "";
						document.getElementById('m_userid').focus();
				});						

    		return false;
    	}
    	else {
    		//alert("Available no.");
    		//document.getElementById("emailcheckid").innerHTML= "<font color='#0000FF'>(Available no.)</font>";
    		
    		var reg = /^((\w|[\-\.])+)@((\w|[\-\.])+)\.([A-Za-z]+)$/;
    		
				if (str.length > 1 && str.search(reg) == -1) {
					//alert("이메일 주소가 올바르지 않습니다. 다시 입력해 주세요.");
					//alert("Please input correct email.");
					$('#myModal').find('.modal-body').text('Please input correct email.');
					$('#myModal').modal('show');
					$('#myModal').on('hidden.bs.modal', function () {
							document.getElementById('m_userid').value = "";
							document.getElementById('m_userid').focus();
					});


					return false;
				}
    		
    		document.getElementById('emailValidateid').value = 1;
    		document.getElementById('m_userid').value = str;
    		return true;
    	}
    	
      //document.getElementById('ORGCPTYPEid').value=sellunit.trim();
    }
  }
  xmlhttp.open("GET","/lib/checkemaillib.php?s="+str,true);
  xmlhttp.send();
}


</SCRIPT>


<script>
$(document).ready(function(){

		loadLevel();

		function loadLevel() {
				var selectedLevel = $('#m_level').val();
				
		    if (selectedLevel === '9') {
		        // driver 선택시 보이기
		        $('#region_area').removeClass('hidden').show();
		        $('#defaultdriver_area').removeClass('hidden').show();
		        $('#currentdriver_area').removeClass('hidden').show();
		        $('#initial_area').removeClass('hidden').show();
		        $("#m_initial").attr('readonly', true);
		        $("#m_firstname").attr('readonly', true);
		        $("#m_lastname").attr('readonly', true);
		    } else {
		        // 그외: 모두 숨기기
		        $('#region_area').hide();
		        $('#defaultdriver_area').hide();
		        $('#currentdriver_area').hide();
		        $('#initial_area').hide();
		        $("#m_firstname").attr('readonly', false);
		        $("#m_lastname").attr('readonly', false);        
		    }
		}
        
    $('#m_level').on('change', function() {
        var selectedLevel = $(this).val();
        
        if (selectedLevel === '9') {
            // driver 선택시 보이기
            $('#region_area').removeClass('hidden').show();
            $('#defaultdriver_area').removeClass('hidden').show();
            $('#currentdriver_area').removeClass('hidden').show();
            $('#initial_area').removeClass('hidden').show();
            $("#m_initial").attr('readonly', true);
            $("#m_firstname").attr('readonly', true);
            $("#m_lastname").attr('readonly', true);
        } else {
            // 그외: 모두 숨기기
            $('#region_area').hide();
            $('#defaultdriver_area').hide();
            $('#currentdriver_area').hide();
            $('#initial_area').hide();
		        $("#m_firstname").attr('readonly', false);
		        $("#m_lastname").attr('readonly', false);              
        }
    });


    $('#m_currentdriver').on('change', function() {
        var selectedcurrentdriver = $(this).val();
        $.ajax({
            type: "POST",
            url:"/lib/lib_getdriverinfo.php",  
            data: { driveruid : selectedcurrentdriver },
				    success: function(response){ 
				      //alert(response);
				      var rt = response.split("|");
				      if (rt[0].trim().match('1')) {
				      		$('#m_firstname').val(rt[1]);
				      		$('#m_lastname').val(rt[2]);
				      		$('#m_initial').val(rt[3]);
				      		$('#m_cell').val(rt[4]);
				      		
              } else {
									$('.myModalPopup-body').html("Failed. Please Try again.");
									$('.myModalPopup-body').css('background-color', '#FF8205');
									
                  $('#myModalPopup').modal('show'); 
							    setTimeout(function () {
							        $('#myModalPopup').modal('hide'); 
							    }, 1500); 
              }
				    }
		  	});
    });
    

		// 숫자만 입력가능 xxx-xxx-xxxx 형식으로 자동 - 삽입
		$('#m_cell').on('input', function() {
		    var number = $(this).val().replace(/[^\d]/g, '')
		    if (number.length == 7) {
		      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
		    } else if (number.length == 10) {
		      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
		    }
		    $(this).val(number);
		});
		
		
	  $("#memberinfo").validate({
	    // Specify validation rules
	    ignore: ".ignore",
	    rules: {
	      m_pwd: {
	        required: true,
	        minlength: 6,
	      },
	      m_pwd_chk: {
	        required: true,
	        minlength: 6,
	        equalTo : '[name="m_pwd"]'
	      },
	      m_firstname: {
	        required: true,
	      },
	      m_lastname: {
	        required: true,
	      },
	      m_regionuid: {
	        required: 	function(elem) {
												if ($("#m_level").val() == '9') { return true; }
												else { return false; }
											},
				}, 
	      m_defaultdriver: {
	        required: 	function(elem) {
												if ($("#m_level").val() == '9') { return true; }
												else { return false; }
											},
				}, 
	      m_currentdriver: {
	        required: 	function(elem) {
												if ($("#m_level").val() == '9') { return true; }
												else { return false; }
											},
				}, 				
	    },
	    messages: {
					m_pwd: {
							required: "Please input password (Minimum of 6 characters)",
							minlength: "Minimum of 6 characters.",
					},
					m_pwd_chk: {
							required: "Password and confirm password don't match",
							minlength: "Minimum of 6 characters.",
							equalTo : "Password and confirm password don't match",
					},  
					m_firstname: {
							required: "Please input First name",
					},				
					m_lastname: {
							required: "Please input Last name",
					},
					m_regionuid: {
							required: "Please select Region",
					},
					m_defaultdriver: {
							required: "Please select Default Driver",
					},	
					m_currentdriver: {
							required: "Please select Current Driver",
					},											
	    },
	    
	    errorElement : 'div',


		  submitHandler: function(form) {
		  	
		 							//e.preventDefault();
				         	var mmode = $('#mode').val();
				         	//var aactionStrid = $('#actionStrid').val();
				         	//var aactionPageid = $('#actionPageid').val();
				         	
									var m_uid = $('#m_uid').val();
									var m_userid = $('#m_userid').val();
									var m_pwd = $('#m_pwd').val();
									
									var m_regionuid = $('#m_regionuid').val();
									var m_currentdriver = $('#m_currentdriver').val();
									var m_defaultdriver = $('#m_defaultdriver').val();
									
									var m_firstname = $('#m_firstname').val();
									var m_lastname = $('#m_lastname').val();
									var m_initial = $('#m_initial').val();
									var m_cell = $('#m_cell').val();
									var m_status = $('#m_status').val();
									var m_level = $('#m_level').val();
									var m_comment = $('#m_comment').val();
				         	//alert(amodeid);

					        $.ajax({  
					             url:"/lib/member_lib_process.php",  
					             method:"POST",  
					             data:{mmode:mmode, m_uid:m_uid, m_userid:m_userid, m_pwd:m_pwd, 
					             			m_regionuid:m_regionuid,
					             			m_currentdriver:m_currentdriver, m_defaultdriver:m_defaultdriver, 
					             			m_firstname:m_firstname, m_lastname:m_lastname, m_initial:m_initial, 
					             			m_cell:m_cell, m_comment:m_comment, 
					             			m_status:m_status, m_level:m_level	},
					             //beforeSend:function(){  
					             //     $('#submitid').val("Updating");  
					             //},  
					             success:function(response){  
					                  //$('#addcartformid')[0].reset();  
					                  //For debugging
					                  //$('.rt_debugging').html(response);
					                  //alert(response);exit;
					                  
					                  if (response) {
																$('.myModalPopup-body').html("Successfully Saved");
																$('.myModalPopup-body').css('background-color', '#2A9B56');
																
							                  $('#myModalPopup').modal('show'); 
														    setTimeout(function () {
														        $('#myModalPopup').modal('hide'); 
														        $('#myModalMemberInfo').modal('hide');
														        parent.location.reload();
														    }, 1500);                  
					                  } else {
																$('.myModalPopup-body').html("Failed. Please Try again.");
																$('.myModalPopup-body').css('background-color', '#FF8205');
																
							                  $('#myModalPopup').modal('show'); 
														    setTimeout(function () {
														        $('#myModalPopup').modal('hide'); 
														    }, 1500); 
					                  }
					                  
					                  //$('#myModalAdminInfo').modal('hide');
					                  //$('.cart-item-no').html(response);  

					             }  
					        });  

			}		



	});
  
});
</script>


<style>
.error{
	color: red;
	font-weight: 200;
	margin-left: 0em;
}
.hidden { display: none; }
</style>

<div class="rt_debugging"></div>



        <div class="modal-header">
          <h4 class="modal-title">USER INFORMATION</h4>
          <button type="button" class="btn" data-dismiss="modal" aria-label="Close" style="color:#fff;"><i class="bi bi-x"></i></button>
        </div>
        <div class="modal-body" style="background-color:#ffffff;">

<FORM name=memberinfo id=memberinfo method="post">
          <input type=hidden name=mode id="mode" value="<?=$mode?>">
          <input type=hidden name=m_uid id="m_uid" value="<?=$m_uid?>">
          <input type=hidden name=emailValidateid id="emailValidateid" value="">
        	<input type=hidden name=actionStr id="actionStr" value="MEMBERINFO">
          
            <table class="tb-info-box">

              <tr>
                <td class="td-title-info">User ID</td>
                <td class="td-text-info">
                  <input type="text" id="m_userid" name="m_userid" placeholder="name@company.com" value='<?=$m_userid?>' option='email' onBlur="checkEmail();" <?=$admTag?>>
                </td>
              </tr>

              <tr>
                <td class="td-title-info">Password</td>
                <td class="td-text-info">
                  <input type="password" id="m_pwd" name="m_pwd" required='required'  minlength="6" maxlength=15>
                </td>
              </tr>

              <tr>
                <td class="td-title-info">Re-Password</td>
                <td class="td-text-info">
                  <input type="password" NAME='m_pwd_chk' id="m_pwd_chk" required='required' minlength="6" maxlength=15>
                </td>
              </tr>

              <tr>
                <td class="td-title-info">Level</td>
                <td class="td-text-info">
                  <select id="m_level" name="m_level" class="custom-select" required='required' >
                  		<option value=''>Select</option>
											<?=$m_levelSTR?>
                  </select>
                </td>
              </tr>


              <tr id="region_area" class="<?=$hiddenTag?>">
                <td class="td-title-info">Region</td>
                <td class="td-text-info">
                  <select id="m_regionuid" name="m_regionuid" class="custom-select" required='required' >
                  		<option value=''>Select</option>
											<?=$m_regionSTR?>
                  </select>
                </td>
              </tr>

              <tr id="defaultdriver_area" class="<?=$hiddenTag?>">
                <td class="td-title-info">Default Driver</td>
                <td class="td-text-info">
                  <select id="m_defaultdriver" name="m_defaultdriver" class="custom-select" required='required' >
                  		<option value=''>Select</option>
											<?=$m_defaultdriverSTR?>
                  </select>
                </td>
              </tr>              

              <tr id="currentdriver_area" class="<?=$hiddenTag?>">
                <td class="td-title-info">Current Driver</td>
                <td class="td-text-info">
                  <select id="m_currentdriver" name="m_currentdriver" class="custom-select" required='required' >
                  		<option value=''>Select</option>
											<?=$m_currentdriverSTR?>
                  </select>
                </td>
              </tr>  
                    
              <tr>
                <td class="td-title-info">First Name</td>
                <td class="td-text-info">
                  <input type="text" id="m_firstname" name="m_firstname" placeholder="James" required='required'  VALUE='<?=htmlspecialchars($m_firstnameSTR, ENT_QUOTES)?>' maxlength=50>
                </td>
              </tr>

              <tr>
                <td class="td-title-info">Last Name</td>
                <td class="td-text-info">
                  <input type="text" NAME='m_lastname' id='m_lastname' placeholder="Lee" required='required'  VALUE='<?=htmlspecialchars($m_lastnameSTR, ENT_QUOTES)?>' maxlength=50>
                </td>
              </tr>

              <tr id="initial_area" class="<?=$hiddenTag?>">
                <td class="td-title-info">Initial</td>
                <td class="td-text-info">
                  <input type="text" NAME='m_initial' id='m_initial' placeholder="E.S" VALUE='<?=htmlspecialchars($m_initialSTR, ENT_QUOTES)?>' maxlength=50>
                </td>
              </tr>
              
<!--
              <tr>
                <td class="td-title-info">Phone</td>
                <td class="td-text-info">
                  <input type="number" id="phone" name="phone" placeholder="1-123-456-7890">
                </td>
              </tr>

              <tr>
                <td class="td-title-info">Ext.</td>
                <td class="td-text-info">
                  <input type="text" id="ext" name="ext" placeholder="123">
                </td>
              </tr>
-->

              <tr>
                <td class="td-title-info">Cell</td>
                <td class="td-text-info">
                  <input type="text" name='m_cell' id='m_cell' placeholder="416-777-8888" value="<?=htmlspecialchars($m_cellSTR, ENT_QUOTES)?>" maxlength="12">
                </td>
              </tr>

<? if ($mode == "update") { ?>

              <tr>
                <td class="td-title-info">Last Login Date</td>
                <td class="td-text-info"><?=$m_logindateSTR?></td>
              </tr>     
              
              <tr>
                <td class="td-title-info">Signup Date</td>
                <td class="td-text-info"><?=$m_signupdateSTR?></td>
              </tr>     
                                          
              <tr>
                <td class="td-title-info">Login No</td>
                <td class="td-text-info"><?=$m_loginnum?></td>
              </tr>
<? } ?>
                                          
              <tr>
                <td class="td-title-info">Status</td>
                <td class="td-text-info">
                  <select id="m_status" name="m_status" class="custom-select" required='required' >
											<option value=''>Select</option>
											<?=$m_statusSTR?>
                  </select>
                </td>
              </tr>
              

              
<!--
              <tr>
                <td class="td-title-info">Access</td>
                <td class="td-text-info">
                  <select id="access" name="access" class="custom-select">
                    <option value="local">Local</option>
                    <option value="internet">Internet</option>
                  </select>
                </td>
              </tr>
-->

              <tr>
                <td class="td-title-info">Memo</td>
                <td class="td-text-info">
                  <textarea class="textarea" id="m_comment" name="m_comment" rows="4" cols="20"><?=$m_commentSTR?></textarea>
                </td>
              </tr>
            </table>
           
            <div class="modal-footer text-center grid-layout-col-2">
              <button type="submit" class="btn-sub">SAVE</button>
              <button type="button" class="btn-gray" data-dismiss="modal">CLOSE</button>
            </div>
         
          </FORM>
        </div>

                
                

        
  
				

<div class="modal fade" id="myModalPopup" tabindex="-1" role="dialog" aria-labelledby="myModalPopup"  style="opacity: 0.5; padding-right: 0px !important;">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
      <div class="modal-content" style="background-color:#2A9B56 !important; max-width:260px; margin: 0 auto;">
        <div class="myModalPopup-body" style="text-align: center; border-radius: 5px; max-height:60px;	font-size:18px; background-color:#2A9B56; color: #FFFFFF; font-weight: bold;padding:0.5em 1em; ">

        </div>     	
      </div>
  </div>
</div>