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

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

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


// 날짜변경 기능 제한 (Admin : 1, Staff : 5만 가능)
$permit = array("1", "5");
if (in_array($_SESSION['ss_LEVEL'], $permit)) {
    $setTag = "ENABLED";
}
else $setTag = "DISABLED";	

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

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

if($d_uid == "") {
		$msg = "Invaild data. Please try again. [Err - d_uid / PICKUPORDER]";
		$func -> modalMsg ($msg, 1);
		exit();
} else {
	
		// Get Information
		$query = "SELECT * FROM tbl_daily WHERE d_uid = '".$d_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;
		}

		$d_nameSTR = str_replace("\\", "", $d_name);
		$d_accountnoSTR = str_replace("\\", "", $d_accountno);

		$d_orderdateSTR = $func -> convertFormat ($d_orderdate, 3);
		$d_payeenameSTR = str_replace("\\", "", $d_payeename);
		
		$folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$d_customeruid;
		
		if (is_file($folderPath."/".trim($d_payeesign))) {
			$d_payeesignSTR = "<img style='border:1px solid;' src='/upload_sign/".$d_customeruid."/".$d_payeesign."'>";
			$setDisplayNEWStr = " DISPLAY:inline; ";
			$setDisplayBTNStr = " DISPLAY:none; ";
			$setDisplaySIGNYESStr = " DISPLAY:inline; ";
			$setDisplaySIGNNEWStr = " DISPLAY:none; ";			
		}
		else {
			$setDisplayNEWStr = " DISPLAY:none; ";
			$setDisplayBTNStr = " DISPLAY:block; ";
			$setDisplaySIGNYESStr = " DISPLAY:none; ";
			$setDisplaySIGNNEWStr = " DISPLAY:inline; ";
		}		

		// 이미 존재하는 오더장을 수정한다면 Note 정보도 가져와야 함
		$qry_note = "SELECT * FROM tbl_note WHERE n_dailyuid = '$d_uid' ";
		$rt_note=$jdb->fQuery($qry_note, "fetch query error");
		$n_noteSTR = str_replace("\\", "", $rt_note['n_note']);
				
	
}

// d_orderdate 이 현재일이고, Finished 안된 경우만 입력할수 있음
// 운영자는 예외
//if (($d_orderdate == date("Ymd") && $d_status != "F") || $_SESSION['ss_LEVEL'] == "1") {

// d_orderdate 이 현재일이고, Finished 상관없이 입력할수 있음 (2023.08.31 request)
// 운영자는 예외	
if (($d_orderdate == date("Ymd")) || $_SESSION['ss_LEVEL'] == "1") { 
		$gridSTR = " grid-layout-col-2";
		$buttonSTR = "<button type=\"submit\" id=\"buttonADD\" class=\"btn-sub\">SAVE</button>";
} 
else { 
		$gridSTR = " width-200";
		$buttonSTR = "";	
} 


if ($_SESSION['ss_LEVEL'] == 9) $add_qry = " AND dr_uid = '".$_SESSION['ss_DRUID']."' ";
else $add_qry = " ";

// Get Sludge Info
$qry_sludge = "SELECT c_sludge FROM tbl_customer WHERE c_uid ='$d_customeruid' ";
$rt_sludge = $jdb->fQuery($qry_sludge, "fetch query error");



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

while($lt_dr=mysqli_fetch_array($rt_dr, MYSQLI_ASSOC)) {

	if ($lt_dr['dr_uid'] == $d_druid) $selectStr = "selected";
	else $selectStr = "";
	
	$dr_uidSTR .= "
								<option value='".$lt_dr['dr_uid']."' $selectStr>".$lt_dr['dr_initial']."</option>";
								
}

?>


<!--link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css"-->
<!--link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/south-street/jquery-ui.css" rel="stylesheet"--> 
<script type="text/javascript" src="/assets/js/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="/assets/js/jquery.signature.min.js"></script>
<link rel="stylesheet" type="text/css" href="/assets/css/jquery.signature.css">


<style>
    .kbw-signature { width: 340px; height: 120px;}
    #sig canvas{
        /*width: 100% !important;*/
        width: 100%;
        height: auto;
        border-bottom: 1px solid #BCBBBB;
    }

	.btn-clear{
	  color: #fff;
	  background: #BCBBBB;

	  border-radius: 5px;
	  border: 1px solid #BCBBBB;
	  float:right;
	}

</style>


<script type="text/javascript">
    var sig = $('#sig').signature({syncField: '#signature64', syncFormat: 'PNG', thickness: 2});
    $('#clear').click(function(e) {
        e.preventDefault();
        sig.signature('clear');
        $("#signature64").val('');
    });
</script>


	
<SCRIPT language=javascript>

$(document).ready(function()
{
  $('#signednew').change(function() 
  {
    if(this.checked != true)
    {
			document.getElementById("signitureedid").style.display="inline";
			document.getElementById("signitureid").style.display="none";
			document.getElementById("clrbtnid").style.display="none";
    }
    else {
			document.getElementById("signitureedid").style.display="none";
			document.getElementById("signitureid").style.display="inline";
			document.getElementById("clrbtnid").style.display="inline";
    }
  });   
});

</SCRIPT>


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

	$(function () {
		$('#d_visitdate').datepicker({ 

						dateFormat: 'yy-mm-dd',
										//minDate: "-10D", 
										//maxDate: "+1M",
										//maxDate: "+1M +10D",
			              //showOn: "button",
			              //yearRange: '-50:+5',
			              buttonImage: "/images/cal_red.png",
			              //beforeShowDay: $.datepicker.noWeekends,
			              buttonImageOnly: true,
			              //showOn: "both",
			              changeMonth: true,
			              changeYear: true,
			              firstDay: 7              
		});
	});

});
</script>

<script>

$(document).ready(function(){

		// Decimal (ex 11, 11.0)
		$("#d_quantity, #d_payamount").on("input", function(evt) {
				var self = $(this);
				self.val(self.val().replace(/[^0-9\.]/g, ''));
				if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) 
				{
				 evt.preventDefault();
				}
		});

		
	  $("#pickupOrder").validate({
	    // Specify validation rules
	    ignore: ".ignore",
	    rules: {
	      d_quantity: {
	        required: true,
	        //minlength: 6,
	      },
	      d_payamount: {
	        required: "#d_paystatuspaid:checked",
	        //minlength: 6,
	      }, 	      
	    },
	    messages: {
					d_quantity: {
							required: "Please input Oil Quantity",
							//minlength: "Minimum of 6 characters.",
					},
					d_payamount: {
							required: "Please input Cash Amount",
							//minlength: "Minimum of 6 characters.",
					},						
	    },
	    
	    errorElement : 'div',
		
		submitHandler: function(form) {
		  	
		  	var $inputs = $(form).find("input, select, button, textarea");
		  	var serializedData = $(form).serialize();

			$.ajax({
				url:"/lib/order_lib_process.php",
				method:"POST",
				data: serializedData,

				success:function(response){

					console.log("SUCCESS:", response);

					response = $.trim(response);

					if (response === "1") {

						$('.myModalPopup-body').html("Saved Successfully.");
						$('.myModalPopup-body').css('background-color', '#2A9B56');

						$('#myModalPopup').modal('show');

						setTimeout(function () {
							$('#myModalpickupOrder').modal('hide');
							$('#myModalPopup').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);
					}
				},

				error:function(xhr, status, error){
					console.log("ERROR:", status, error);
					console.log(xhr.responseText);
					alert("AJAX ERROR");
				}
			});

		}
	});
  
});
</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">&nbsp;&nbsp;<?=$d_nameSTR?></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">

<FORM NAME=pickupOrder id=pickupOrder METHOD=POST >
    	<input type=hidden name=actionStr value="PICKUPORDER">
    	<input type=hidden name=actionPage value="">
    	<input type=hidden name=d_uid id=d_uid value="<?=$d_uid?>">
    	<input type=hidden name=d_paymenttype id=d_paymenttype value="<?=$d_paymenttype?>">
    	<input type=hidden name=d_customeruid id=d_customeruid value="<?=$d_customeruid?>">
		<input type=hidden name=d_customerno  id=d_customerno  value="<?=$d_accountno?>">
			<input type=hidden name=mode id=mode value="update">

<? if (trim($d_payeesign) != "") { ?>
			<input type=hidden name=d_payeesign id=d_payeesign value="<?=$d_payeesign?>">
<? }?>

          <table class="tb-info-box">
            <tr>
              <td class="td-title-info td-name">Account No</td>
              <td class="td-text-info">           	
                  <?=$d_accountnoSTR?>
              </td>
            </tr>            
            <tr>
              <td class="td-title-info">Visited Date</td>
              <td class="td-text-info">
<? if ($setTag == "ENABLED") { ?>
                <input type="text" id="d_visitdate" name="d_visitdate" value="<?=$d_orderdateSTR?>" readonly>
<? } else { ?>
              	<input type="text" name="d_visitdate" value="<?=$d_orderdateSTR?>" readonly>
<? } ?>              	
              </td>
            </tr>

            <tr>
              <td class="td-title-info">Driver</td>
              <td class="td-text-info">           	
                <select id="d_druid" name="d_druid" class="custom-select">
                  <?=$dr_uidSTR?>
                </select>
              </td>
            </tr>

            <tr>
              <td class="td-title-info">Oil Quantity</td>
              <td class="td-text-info">
                <input type="text" id="d_quantity" name="d_quantity" placeholder="500" value="<?=$d_quantity?>" required='required' minlength="1" maxlength="10">
              </td>
            </tr>

            <tr>
              <td class="td-title-info">Sludge</td>
              <td class="td-text-info">
                <input type="text" id="d_sludge" name="d_sludge" value="<?= (empty($d_sludge)) ? $rt_sludge['c_sludge'] : $d_sludge ?>" placeholder="50">
              </td>
            </tr>

<? if ($d_paymenttype =="CA") { ?>
            <tr>
              <td class="td-title-info">Cash</td>
              <td class="td-text-info">
                <input type="text" id="d_payamount" name="d_payamount" value="<?=$d_payamount?>" placeholder="100" >
              </td>
            </tr>

              <tr>
                <td class="td-title-info">Pay Status</td>
                <td class="td-text-info">

                  <label class="container-chk">Paid
                    <input type="radio" id="d_paystatuspaid" name="d_paystatus" required='required' <?=($d_paystatus == "P")?"checked":"";?> value="P">
                    <span class="checkmark"></span>
                  </label>

                  <label class="container-chk">UnPaid
                    <input type="radio" id="d_paystatusunpaid" name="d_paystatus" required='required' <?=($d_paystatus == "N" || $d_paystatus == "")?"checked":"";?> value="N">
                    <span class="checkmark"></span>
                  </label>

                </td>
              </tr>
              <tr>
                <td class="td-title-info">Customer Name</td>
	              <td class="td-text-info">
	                <input type="text" id="d_payeename" name="d_payeename" value="<?=htmlspecialchars($d_payeenameSTR, ENT_QUOTES)?>" placeholder="Customer Name" >
	              </td>
              </tr>
              <tr>
                <td class="td-title-info">Signature
                		<div id="newbtnid" style="<?=$setDisplayNEWStr?> float:right; padding-right: 10px;">New <input type="checkbox" id="signednew" name="signednew" value="1" ></div>
                		<div id="clrbtnid" style="<?=$setDisplayBTNStr?> float:right; padding-right: 10px;padding-bottom: 10px;"><button id="clear" class="btn-clear">Clear</button></div>
                </td>
	              <td class="td-text-info">
					        <div id="signitureedid" style="<?=$setDisplaySIGNYESStr?>">
					            <?=$d_payeesignSTR?>
					        </div>	              	
	              	
					        <div id="signitureid" style="<?=$setDisplaySIGNNEWStr?>">
					            <div id="sig" ></div>
					            <br/>
					            <textarea id="signature64" name="signed" class="textarea" style="display: none;width: 100%;"></textarea>
					        </div>
	              </td>
              </tr>              

        
            <!--tr>
              <td class="td-title-info">Pay Status</td>
              <td class="td-text-info">
                <select name="d_paystatus" id="d_paystatus" class="custom-select" required='required' >
                	<option value="">Select</option>
									<option <?=($d_paystatus == "P")?"selected":"";?> value="P">Paid</option>
									<option <?=($d_paystatus == "N")?"selected":"";?> value="N">Not Paid</option>
                </select>
              </td>
            </tr-->
<? } ?>

            <tr>
              <td class="td-title-info">Note</td>
              <td class="td-text-info">
                <textarea id="d_note" class="textarea" name="d_note" rows="3" cols="20"><?=$n_noteSTR?></textarea>
              </td>
            </tr>
          </table>
          <br>
          <div class="text-center <?=$gridSTR?>">
            <?=$buttonSTR?>
            <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>