<?php $ci = get_instance();?>
<style type="text/css">
	.transparent_input{
		background-color: transparent; 
		border-color: transparent;
	}
</style>
<form id ="div_form" onSubmit="return edit_validation(this);" action="<?php echo base_url($this->router->fetch_class()."/update")?>" method="POST" style="padding-left: 5px; padding-right: 5px;">
	<!--  -->
	<?php if(isset($data)):?>
        <input type="hidden" name="REFNO" value="<?php echo $data->REFNO;?>">
	<?php endif;?>
	<?php if(!isset($data)):?>
        <input type="hidden" name="UNIQID" value="<?php echo uniqid();?><?php echo date("YmdHis");?>">
    <?php endif;?>
	<!--  -->
	<div class = "row">
        <div class="col-md-12">
        	<table>
        		<tr>
        			<div class="col-md-6" id="REFNO_div">
				        <label> Ref.No.</label>
				        <div class="form-group">
				            <input type="text" name="REFNO" onInput="" value="<?php if(isset($data)) echo $ci->fm->str_esc(trim($data->REFNO), 2);?>" class="form-control" placeholder="(Auto-generate)" autocomplete="OFF" disabled>
				      	</div>
				    </div>
				    <div class="col-md-6" id="DATE_div">
				    	<span style="color: red;">* </span><label> Date</label>
				        <div class="form-group">
				            <div class="has-feedback" style="max-width: 200px; display: inline-block;">
				            <input type="text" name="DATE" id="DATE" value="<?php if(isset($data) && strlen($data->DATE) > 0) echo $this->fm->str_esc(date("Y-m-d", strtotime($data->DATE)), 2);?>" maxlength="19" class="form-control datepicker" autocomplete="OFF" required="required">
				            <span class="fa fa-calendar form-control-feedback" style="top: 10px; right: 0px;" aria-hidden="true"></span>
				            </div>
				        </div>
				    </div>
        		</tr>
        		<tr>
        			<div class="col-md-6" id="DEBTOR_div">
			        	<span style="color: red;">* </span><label> Debtor</label>
			            <div class="has-feedback">
	                        <select name="DEBTOR" id="DEBTOR" class="form-control select2" required="required">
			                    <option value="">--- Select a value ---</option>
			                    <?php foreach($all_debtor as $v):?>
			                        <option value="<?php echo $v->CODE;?>" <?php if(isset($data) && $data->DEBTOR == $v->CODE) echo "selected='selected'";?>>
			                        <?php echo "[".$v->CODE."] ".$v->NAME;?>
			                        </option>
			                    <?php endforeach;?>
			                </select>
                        </div>
			        </div>
			       <div class="col-md-6" id="TT_div">
			        	<span style="color: red;">* </span><label> Transaction Type</label>
			            <div class="has-feedback">
	                        <select name="TT" id="TT" class="form-control select2" required="required">
			                    <option value="">--- Select a value ---</option>
			                    <?php foreach($all_tt as $v):?>
			                        <option value="<?php echo $v->TT;?>" 
			                        	<?php if(isset($data) && $data->TT == $v->TT){
			                        		echo "selected='selected'";
			                        	}else if(!isset($data) && $v->TT == 'T'){
											echo "selected='selected'";
			                        	}
			                        	?>
			                        	>
			                        <?php echo "[".$v->TT."] ".$v->TTNAME;?>
			                        </option>
			                    <?php endforeach;?>
			                </select>
                        </div>
			        </div>
        		</tr>
        		<tr>
        			<div class="col-md-12">
        				<br/>
        			</div>
        		</tr>
        		<tr>
        			<div class="col-md-6" id="STAFF_div">
			        	<span style="color: red;">* </span><label> Staff</label>
			            <div class="has-feedback">
	                        <select name="STAFF" id="STAFF" class="form-control select2" required="required">
			                    <option value="">--- Select a value ---</option>
			                    <?php foreach($all_staff as $v):?>
			                        <option value="<?php echo $v->CODE;?>" <?php if(isset($data) && $data->STAFF == $v->CODE) echo "selected='selected'";?>>
			                        <?php echo "[".$v->CODE."] ".$v->NAME;?>
			                        </option>
			                    <?php endforeach;?>
			                </select>
                        </div>
			        </div>
			        <div class="col-md-6" id="REMARKS_div">
			        	<label> Remarks</label>
			            <div class="form-group">
			                <input type="text" name="PARTICULAR" id="REMARKS" value="<?php if(isset($data)) echo $ci->fm->str_esc($data->PARTICULAR, 2);?>" class="form-control" autocomplete="OFF">
			            </div>
			        </div>
        		</tr>
        		<tr>
        			<div class="col-md-12">
        				<br/>
        			</div>
        		</tr>
        		<tr>
        			<table id="table_sub" class="table table-bordered" style="height: 100px; max-height: 800px; overflow-y: scroll;">
						<thead>
							<tr>
								<th style="text-align: center; width: 20%;">Gold</th>
								<th style="text-align: center; width: 30%;">Description<br/>of Gold</th>
								<th style="text-align: center;">Weight<br/>of Gold</th>
								<th style="text-align: center;">Rate %</th>
								<th style="text-align: center;">Nett Weight<br/>of Pure Gold</th>
								<th style="text-align: center;">Delete</th>
							</tr>
						</thead>
						<tbody>
							<tr id="edit_sub_tr_add" style="<?php if(! $can_create) echo "display: none;";?>">
								<td id="sub_tr_add_btn" colspan="99" style="text-align: center;">
									<button type="button" onClick="edit_sub_add();" class="btn btn-primary">
										<i class="fa fa-plus-circle"></i>
									</button>
								</td>
							</tr>
						</tbody>
						<thead>
							<tr>
								<th colspan="4" style="text-align: right;">Total (gram):</th>
								<th class="" id="TRADEIN_W_th" style="text-align: right;"><?php if(isset($tradein_total)) echo number_format((float)$tradein_total, 2, '.', '');?></th>
								<input type="hidden" name="TRADEIN_W" id="TRADEIN_W" value="<?php if(isset($tradein_total)) echo number_format((float)$tradein_total, 2, '.', '');?>">
								<th></th>
							</tr>
							<tr>
								<th colspan="4" style="text-align: right;">Balance (gram):</th>
								<th id="BAL_TH" style="text-align: right;"><?php if(isset($data)) echo $ci->fm->str_esc(trim($data->BAL), 2);?></th>
								<input type="hidden" name="BAL" id="BAL" value="<?php if(isset($data)) echo $ci->fm->str_esc(trim($data->BAL), 2);?>">
								<th></th>
							</tr>
						</thead>
					</table>
        		</tr>
        	</table>
        </div>
    </div>
    <?php if((! isset($data) && $can_create) || (isset($data) && $can_edit)):?>
		<div class="form-group" style="margin-top: 30px;">
			<label></label>
			<button type="submit" id="edit_btn_submit" class="btn btn-primary btn-xs-block btn_submit">
				<i class="fa fa-save"></i>
				Save
			</button>
		</div>
	<?php endif;?>
</form>
<script>
	$(document).ready(function(){

		//Datepicker
		var DATE = $("[name='DATE']").val();

	    if(DATE == ""){
	        $("#edit_ajax_container .datepicker").datepicker({
	            format: "yyyy-mm-dd",
	            autoclose: true,
	            todayHighlight: true,
	        }).datepicker("setDate", new Date());
	    }else{
	        $("#edit_ajax_container .datepicker").datepicker({
	            format: "yyyy-mm-dd",
	            autoclose: true,
	            todayHighlight: true,
	          });
	    }

		$("#edit_ajax_container .select2").select2();

		<?php if(isset($sub_array)):?>
			<?php foreach($sub_array as $sub):?>
		 		edit_sub_add();

		 		$(".edit_sub_tr:last [name='SUB_TRADEIN_PKKEY[]']").val("<?php echo $sub->PKKEY;?>");
		 		$(".edit_sub_tr:last [name='SUB_TRADEIN_GOLD[]']").select2("val","<?php echo $sub->GOLD;?>");
		 		$(".edit_sub_tr:last [name='SUB_TRADEIN_DESCRIPT[]']").val("<?php echo $sub->DESCRIPT;?>");
		 		$(".edit_sub_tr:last [name='SUB_TRADEIN_WEIGHT[]']").val("<?php echo $sub->WEIGHT;?>");
		 		$(".edit_sub_tr:last [name='SUB_TRADEIN_RATE[]']").val("<?php echo $sub->RATE;?>");
		 		$(".edit_sub_tr:last [name='SUB_TRADEIN_GOLDPRICE[]']").val("<?php echo $sub->GOLDPRICE;?>");
		 	<?php endforeach;?>
		<?php endif;?>

		<?php if(isset($data)):?>
			<?php if($can_delete):?>
				$(".btn_delete").show();
			<?php endif;?>

			<?php if($can_delete):?>
				$("#edit_div_action").show("fast");
			<?php endif;?>
		
			$("#delete_modal [name='REFNO']").val("<?php echo $data->REFNO;?>");
		<?php endif;?>

		<?php if(isset($data) && ! $can_edit):?>
			$("#edit_ajax_container input").prop("disabled", true);
			$("#edit_ajax_container select").prop("disabled", true);
			$("#edit_ajax_container textarea").prop("disabled", true);
		<?php endif;?>

	});


	function edit_sub_add(){
		var content = "";
		content += "<tr class='edit_sub_tr'>";

		content += 	"<td class='' style=''>";
		content += 		"<input type='hidden' name='SUB_TRADEIN_PKKEY[]'>";
		content +=         '<select name="SUB_TRADEIN_GOLD[]" class="form-control select2" required="required" onChange="calculate_tradein_gold(this);find_gold_subdetail(this);">';
		content +=           '<option value="">--- Select a value ---</option>';
	    <?php foreach($all_gold as $v):?>
	    content +=			 '<option value="<?php echo $v->CODE;?>">';
	    content +=           ' <?php echo "[".$v->CODE."] ".$v->NAME;?>';
	    content +=           '</option>';
	    <?php endforeach;?>
	    content +=         '</select>';
		content += 	"</td>";

		content += 	"<td class='' style=''>";
		content += 	"	<input type='text' maxlength='50' name='SUB_TRADEIN_DESCRIPT[]' id='SUB_TRADEIN_DESCRIPT' class='form-control' style='text-align: left;' autocomplete='OFF'/>";
		content += 	"</td>";

		content += 	"<td class='' style=''>";
		content += 	"	<div class='input-group'>"
		content += 	"		<input type='number' min='0' step='.0001' name='SUB_TRADEIN_WEIGHT[]' id='SUB_TRADEIN_WEIGHT' class='form-control' style='text-align: left;' onblur='calculate_tradein_gold(this);edit_total_tradein(this);' autocomplete='OFF'/>";
		content += 	"		<span class='input-group-addon'>gram</span>"
		content += 	" 	</div>"
		content += 	"</td>";

		content += 	"<td class='' style=''>";
		content += 		"<input type='number' min='0' step='.0001' name='SUB_TRADEIN_RATE[]' id='SUB_TRADEIN_RATE' class='form-control' style='text-align: left;' onblur='calculate_tradein_gold(this);edit_total_tradein(this);' autocomplete='OFF' readonly='readonly'/>";
		content += 	"</td>";

		content += 	"<td class='' style=''>";
		content += 	"	<div class='input-group'>"
		content += 	"		<input type='number' min='0' step='.0001' name='SUB_TRADEIN_GOLDPRICE[]' id='SUB_TRADEIN_GOLDPRICE' class='form-control' style='text-align: left;' autocomplete='OFF' readonly='readonly'/>";
		content += 	"		<span class='input-group-addon'>gram</span>"
		content += 	" 	</div>"
		content += 	"</td>";

		<?php if($can_delete):?>
		content += 	"<td style='text-align: center;'>";
		content += 	"<button type='button' onClick='edit_sub_remove(this);' class='btn btn-danger'>";
		content += 		"<i class='fa fa-trash-o'></i>";
		content += 	"</button>";
		content += 	"</td>";
		<?php endif;?>
		content += "</tr>";

		$("#edit_sub_tr_add").before(content);
		$(".edit_sub_tr:last .select2").select2();

	}

	function edit_sub_remove(btn){
		var tr = $(btn).closest("tr");
		var pkkey = $(tr).find("[name='SUB_TRADEIN_PKKEY[]']").val();
		var first_pkkey = $(".edit_sub_tr:first [name='SUB_TRADEIN_PKKEY[]']").val();
		var x = confirm("Are you sure you want to delete this data ?");
		var GOLDPRICE = parseFloat($(tr).find("[name='SUB_TRADEIN_GOLDPRICE[]']").val());
		var BAL = parseFloat($("#BAL").val());
		
		if(pkkey != "" && x){	
			var content = "<input type='hidden' name='DEL_SUB_TRADEIN_PKKEY[]' value='" + pkkey + "'>";
			$(btn).closest("form").append(content);
			$(tr).remove();
			if(pkkey == first_pkkey){
				$("#TRADEIN_W").html(0);
			}
			edit_total_tradein();
			var NEW_BALANCE = BAL-GOLDPRICE;
			$("#BAL").val(number_format(NEW_BALANCE, 2));
			$("#BAL_TH").html(number_format(NEW_BALANCE, 2));

		}else if(pkkey == "" && x){	
			$(tr).remove();
			if(pkkey == first_pkkey){
				$("#TRADEIN_W").html(0);
			}
			edit_total_tradein();
			var NEW_BALANCE = BAL-GOLDPRICE;
			$("#BAL").val(number_format(NEW_BALANCE, 2));
			$("#BAL_TH").html(number_format(NEW_BALANCE, 2));
		}else{
			return false;
		}

	}

	function edit_total_tradein(){
		var sum = 0;
		$("[name='SUB_TRADEIN_GOLDPRICE[]']").each(function(index, element){
			sum += parseFloat($(this).val());
			$("#TRADEIN_W").val(sum);
			$("#TRADEIN_W_th").html(number_format(sum, 2));
		});

	}

	function edit_total_tradein_bal(){
		if($("#BAL").val() == ""){
			var BAL = 0;
		}else{
			var BAL = parseFloat($("#BAL").val());
		}
		var GOLDPRICE = parseFloat($(".edit_sub_tr:last [name='SUB_TRADEIN_GOLDPRICE[]']").val());
		var sum = BAL+GOLDPRICE;
		$("#BAL").val(number_format(sum, 2));
		$("#BAL_TH").html(number_format(sum, 2));
	}

	function calculate_tradein_gold(t){
    	var tr = $(t).closest("tr");
    	var gold = $(tr).find("[name='SUB_TRADEIN_GOLD[]']").val();
		var weight = $(tr).find("[name='SUB_TRADEIN_WEIGHT[]']").val();
		var rate = $(tr).find("[name='SUB_TRADEIN_RATE[]']").val();

		if(weight != "" && rate != "" && gold != ""){
			var goldprice = (weight*rate).toFixed(2);
			$(".edit_sub_tr:last [name='SUB_TRADEIN_GOLDPRICE[]']").val(goldprice);
			edit_total_tradein_bal();
		}else if(weight != "" && rate == "" && gold != "" ){
			$(".edit_sub_tr:last [name='SUB_TRADEIN_GOLDPRICE[]']").val(number_format(weight, 2));
			edit_total_tradein_bal();
		}
    }

    function find_gold_subdetail(t){
    	var tr = $(t).closest("tr");
		var id = $(tr).find("[name='SUB_TRADEIN_GOLD[]']").val();

        if(id !=""){
            var params = "id=" + id;

            $.ajax({
                type: "POST",
                url: "<?php echo base_url($this->router->fetch_class());?>/get_gold_detail",
                data: params,
                success: function(result, status, xhr){
                    //log(JSON.parse(result));
                    var info, i;
                    info = JSON.parse(result);
                    
                    for (i = 0; i < info.length; i++) {

                    	if(info[i].DESCRIPT != null){
							$(tr).find("[name='SUB_TRADEIN_DESCRIPT[]']").val(info[i].DESCRIPT.trim());
                    	}else{
                    		$(tr).find("[name='SUB_TRADEIN_DESCRIPT[]']").val('');
                    	}

                    	if(info[i].RATE != null){
							$(tr).find("[name='SUB_TRADEIN_RATE[]']").val(info[i].RATE.trim());
                    	}else{
                    		$(tr).find("[name='SUB_TRADEIN_RATE[]']").val('');
                    	}

                    } 
                },
                error: function(xhr,status,error){},
                complete: function(xhr,status){},
            });
        }else{
        	$(tr).find("[name='SUB_TRADEIN_DESCRIPT[]']").val('');
        	$(tr).find("[name='SUB_TRADEIN_RATE[]']").val('');
        }
    }

	function edit_check_unique(){
		var selector = "#edit_ajax_container [name='CUSTOMER']";
		$(selector).closest("div").removeClass("has-success");
		$(selector).closest("div").removeClass("has-error");
		$(selector).closest("div").find(".check_unique_feedback_ok").hide("fast");
		$(selector).closest("div").find(".check_unique_feedback_loading").show("fast");
		disable_btn("#edit_btn_submit");

		var unique = $(selector).val();
		checking_unique = unique;

		var params = "";
		params += "&unique=" + unique;
		<?php if(isset($data)):?>
			params += "&pk=" + $("#edit_ajax_container [name='REFNO']").val();
		<?php endif;?>

		clearTimeout(timer_check_unique);
		timer_check_unique = setTimeout(function(){
			$.ajax({
				type: "POST",
				url: "<?php echo base_url($this->router->fetch_class());?>/check_unique",
				data: params,
				success: function(result, status, xhr){
					if(checking_unique == unique){
						if(result == "1"){
							$(selector).closest("div").addClass("has-success");
							$(selector).closest("div").find(".check_unique_feedback_ok").show("fast");
							enable_btn("#edit_btn_submit");
						}
						else{
							$(selector).closest("div").addClass("has-error");
						}
					}
				},
				error: function(xhr,status,error){
					if(checking_unique == unique){
					}
				},
				complete: function(xhr,status){
					if(checking_unique == unique){
						$(selector).closest("div").find(".check_unique_feedback_loading").hide("fast");
					}
				},
			});
		}, 500);
	}
	
	function edit_validation(form){
		var error = "";
		
		$(form).find("[required]:not(:disabled)").each(function(){
			if($(this).val() == ""){
				if(error != "") error += "<br>";
				switch($(this).attr("name")){
					case "USERNAME":
						error += "Please fill in the Username!";
						break;
					case "NAME":
						error += "Please fill in the Name!";
						break;
					case "GROUP_ID":
						error += "Please select a Group!";
						break;
					default:
						error += "Please complete the Form!";
						break;
				}
				
				return false;
			}
		});

		if(error == ""){
			disable_btn(".btn_submit");
		}
		else{
			prompt_error(error);
			return false;
		}
	}


</script>