<?php
$form=$this->beginWidget('CActiveForm',[
'id'=>'sales-return-form'
]);
?>

<div class="modal-header">
<h4>Create Sales Return</h4>
</div>

<div class="modal-body">

<div class="row">

<div class="col-md-6">
<label>Invoice Number</label>

<select class="form-control" name="invoice_id" id="invoice_id">

<option value="">Select Invoice</option>

<?php foreach($invoices as $inv): ?>

<option value="<?php echo $inv->id ?>">
<?php echo $inv->invoice_number ?>
</option>

<?php endforeach; ?>

</select>
</div>

<div class="col-md-6">
<label>Customer Name</label>
<input type="text" class="form-control" id="customer_name" readonly>
</div>

</div>

<br>

<div class="row">

<div class="col-md-12">
<label>Customer Address</label>
<textarea class="form-control" id="customer_address" readonly></textarea>
</div>

</div>

<br>

<table class="table table-bordered" id="product-table">

<thead>

<tr>
<th>Product</th>
<th>SKU</th>
<th>Sold Qty</th>
<th>Return Qty</th>
</tr>

</thead>

<tbody>

</tbody>

</table>

</div>

<div class="modal-footer">

<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>

<button type="button" class="btn btn-success" id="saveReturn">
Save Return
</button>

</div>

<?php $this->endWidget(); ?>

<script>

$("#invoice_id").change(function(){

var invoiceId=$(this).val();

if(invoiceId==""){
$("#product-table tbody").html('');
return;
}

$.ajax({

url:"<?php echo Yii::app()->createUrl('salesReturn/getInvoiceItems'); ?>",

type:"GET",

data:{id:invoiceId},

success:function(res){

var data=JSON.parse(res);

$("#customer_name").val(data.customer_name);
$("#customer_address").val(data.customer_address);

var html='';

$.each(data.items,function(i,item){

html+='<tr>';

html+='<td>'+item.product_name+'</td>';

html+='<td>'+item.sku+'</td>';

html+='<td>'+item.qty+'</td>';

html+='<td><input type="number" name="return_qty['+item.id+']" class="form-control return_qty" min="0" max="'+item.qty+'"></td>';

html+='</tr>';

});

$("#product-table tbody").html(html);

}

});

});

</script>