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

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

$dr_uid = trim($_POST["dr_uid"]);

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

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

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

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

if ($dr_uid != "") {
		// Get Information
		$query = "SELECT * FROM tbl_driver WHERE dr_uid = '".$dr_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;
		}

		$dr_firstnameSTR = str_replace("\\", "", $dr_firstname);
		$dr_lastnameSTR = str_replace("\\", "", $dr_lastname);
		$dr_initialSTR = str_replace("\\", "", $dr_initial);
		
		$dr_cellSTR = preg_replace('/[^A-Za-z0-9\-]/', '', $dr_cell);
		$dr_cellSTR = str_replace("\\", "", $dr_cellSTR);
		$dr_cellSTR = str_replace("-", "", $dr_cellSTR);
		$dr_cellSTR = substr ($dr_cellSTR, 0, 3)."-".substr ($dr_cellSTR, 3, 3)."-".substr ($dr_cellSTR, 6, 4);
		
		$dr_createdateSTR = $func -> convertFormat ($dr_createdate, 1);
		
}
else $dr_status = 'A';


// Get Status Info
foreach ($arrStatus AS $key=>$value)
{
	//echo "[$key][$value]";   => [0][Waiting][1][Confirmed][E][Declined]...
	
	if ($key == $dr_status) $selectStr = "selected";
	else $selectStr = "";
	
	if ($key != 'F') {
			$dr_statusSTR .= "
								<option value='$key' $selectStr>$value</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 checkInitial() {
	var str = document.getElementById('dr_initial').value;
	//alert(str);

	str = str.toUpperCase();

  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('initialValidateid').value = 0;
				//alert('This email is already in use. Please enter a different email.');
				$('#myModal').find('.modal-body').text('This Initial is already in use. Please enter a different Initial.');
				$('#myModal').modal('show');		
				$('#myModal').on('hidden.bs.modal', function () {
						document.getElementById('dr_initial').value = "";
						document.getElementById('dr_initial').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 > 2 && str.search(reg) == -1) {
				if (str.length > 4) {
					//alert("이메일 주소가 올바르지 않습니다. 다시 입력해 주세요.");
					//alert("Please input correct email.");
					$('#myModal').find('.modal-body').text('Please input correct Initial.');
					$('#myModal').modal('show');
					$('#myModal').on('hidden.bs.modal', function () {
							document.getElementById('dr_initial').value = "";
							document.getElementById('dr_initial').focus();
					});


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

</SCRIPT>


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

		var selectedMode = $('#mode').val();
		if (selectedMode != 'create') {	
				$("#dr_initial").attr('readonly', true);
		}

		// 숫자만 입력가능 xxx-xxx-xxxx 형식으로 자동 - 삽입
		$('#dr_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: {

	      dr_firstname: {
	        required: true,
	      },
	      dr_lastname: {
	        required: true,
	      },
	      dr_initial: {
	        required: true,
	      }, 	      
	    },
	    messages: {
  
					dr_firstname: {
							required: "Please input First name",
					},				
					dr_lastname: {
							required: "Please input Last name",
					},
					dr_initial: {
							required: "Please input Initial",
					},						
	    },
	    
	    errorElement : 'div',


		  submitHandler: function(form) {
		  	
		 							//e.preventDefault();
				         	var mmode = $('#mode').val();
				         	//var aactionStrid = $('#actionStrid').val();
				         	//var aactionPageid = $('#actionPageid').val();
				         	
									var dr_uid = $('#dr_uid').val();
									var dr_firstname = $('#dr_firstname').val();
									var dr_lastname = $('#dr_lastname').val();
									var dr_initial = $('#dr_initial').val();
									var dr_cell = $('#dr_cell').val();
									var dr_status = $('#dr_status').val();
				         	//alert(amodeid);

					        $.ajax({  
					             url:"/lib/driver_lib_process.php",  
					             method:"POST",  
					             data:{mmode:mmode, dr_uid:dr_uid, 
					             			dr_firstname:dr_firstname, dr_lastname:dr_lastname, dr_initial:dr_initial, 
					             			dr_cell:dr_cell, dr_status:dr_status	},
					             //beforeSend:function(){  
					             //     $('#submitid').val("Updating");  
					             //},  
					             success:function(response){  
					                  //$('#addcartformid')[0].reset();  
					                  //For debugging
					                  //$('.rt_debugging').html(response);
					                  //alert(response);exit;
					                  
					                  if (response == 1) {
																$('.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 if (response == 2) {
																$('.myModalPopup-body').html("Failed. This Initial is already in use.");
																$('.myModalPopup-body').css('background-color', '#FF8205');
																
							                  $('#myModalPopup').modal('show'); 
														    setTimeout(function () {
														        $('#myModalPopup').modal('hide');
														    }, 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;
}		
</style>

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



        <div class="modal-header">
          <h4 class="modal-title">DRIVER 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=dr_uid id="dr_uid" value="<?=$dr_uid?>">
          <input type=hidden name=initialValidateid id="initialValidateid" value="">
        	<input type=hidden name=actionStr id="actionStr" value="DRIVERINFO">
          
            <table class="tb-info-box">

              <tr>
                <td class="td-title-info">First Name</td>
                <td class="td-text-info">
                  <input type="text" id="dr_firstname" name="dr_firstname" placeholder="James" required='required'  VALUE='<?=htmlspecialchars($dr_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='dr_lastname' id='dr_lastname' placeholder="Lee" required='required'  VALUE='<?=htmlspecialchars($dr_lastnameSTR, ENT_QUOTES)?>' maxlength=50>
                </td>
              </tr>

              <tr>
                <td class="td-title-info">Initial</td>
                <td class="td-text-info">
                  <input type="text" NAME='dr_initial' id='dr_initial' placeholder="E.S" required='required' VALUE='<?=htmlspecialchars($dr_initialSTR, ENT_QUOTES)?>' onblur="checkInitial();" <?=$admTag?> maxlength=10>
                </td>
              </tr>
              
              <tr>
                <td class="td-title-info">Cell</td>
                <td class="td-text-info">
                  <input type="text" name='dr_cell' id='dr_cell' placeholder="416-777-8888" value="<?=htmlspecialchars($dr_cellSTR, ENT_QUOTES)?>" maxlength="12">
                </td>
              </tr> 
              
              <tr>
                <td class="td-title-info">Signup Date</td>
                <td class="td-text-info"><?=$dr_createdateSTR?></td>
              </tr>     
                                                                    
              <tr>
                <td class="td-title-info">Status</td>
                <td class="td-text-info">
                  <select id="dr_status" name="dr_status" class="custom-select" required='required' >
											<option value=''>Select</option>
											<?=$dr_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>
-->

            </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>