<?php
/* @var $this SalesInvoiceController */
/* @var $model SalesInvoice */

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

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

<div class="modal-body">

<!-- Invoice Header Fields -->
<div class="row">
    <div class="col-sm-3">
        <?php echo $form->labelEx($model,'invoice_number'); ?>
        <?php echo $form->textField($model,'invoice_number',['class'=>'form-control','readonly'=>true]); ?>
    </div>
    <div class="col-sm-3">
        <label>Customer</label>
        <select name="SalesInvoice[customer_name]" id="customer-dropdown" class="form-control">
            <option value="">Select</option>
            <?php foreach($customers as $id=>$name): ?>
                <option value="<?= $name ?>" data-id="<?= $id ?>"><?= $name ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="col-sm-3">
        <label>Invoice Date</label>
        <input type="date" name="SalesInvoice[invoice_date]" class="form-control" value="<?php echo date('Y-m-d'); ?>">
    </div>
    <div class="col-sm-3">
        <label>Status</label>
        <select name="SalesInvoice[status]" class="form-control">
            <option value="Draft">Draft</option>
            <option value="Pending">Pending</option>
            <option value="Paid">Paid</option>
        </select>
    </div>
</div>

<br>

<div class="row">
    <div class="col-sm-6">
        <label>Customer Address</label>
        <textarea name="SalesInvoice[customer_address]" id="customer-address" class="form-control"></textarea>
    </div>
    <div class="col-sm-6">
        <label>Notes</label>
        <textarea name="SalesInvoice[notes]" class="form-control"></textarea>
    </div>
</div>

<hr>

<!-- Invoice Items Table -->
<table class="table table-bordered" id="invoice_table">
<thead>
<tr>
<th>Product</th><th>SKU</th><th>Available</th><th>Qty</th><th>Unit Price</th><th>Total</th><th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="InvoiceItems[0][product_id]" class="form-control product_select">
<option value="">Select</option>
<?php foreach($products as $p): ?>
<option value="<?= $p->id ?>" data-sku="<?= $p->sku ?>" data-name="<?= $p->product_name ?>" data-price="<?= $p->price ?>" data-stock="<?= $p->quantity ?>"><?= $p->product_name ?></option>
<?php endforeach; ?>
</select>
<input type="hidden" name="InvoiceItems[0][product_name]" class="product_name">
</td>
<td><input type="text" name="InvoiceItems[0][sku]" class="form-control sku"></td>
<td><input type="text" class="form-control stock" readonly></td>
<td><input type="number" name="InvoiceItems[0][quantity]" class="form-control qty" value="0"></td>
<td><input type="number" name="InvoiceItems[0][unit_price]" class="form-control price"></td>
<td><input type="text" name="InvoiceItems[0][total_price]" class="form-control total" readonly></td>
<td><button type="button" class="btn btn-danger removeRow">X</button></td>
</tr>
</tbody>
</table>

<button type="button" class="btn btn-success" id="addRow">Add Product</button>

<hr>

<div class="row">
<div class="col-sm-3 col-sm-offset-6">
<label>Subtotal</label>
<input type="text" id="subtotal" class="form-control" readonly>
<label>VAT 5%</label>
<input type="text" id="vat" class="form-control" readonly>
<label>Grand Total</label>
<input type="text" id="grand_total" class="form-control" readonly>
</div>
</div>

</div>

<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="saveInvoice">Save Invoice</button>
</div>

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

<script>

let rowIndex=1;

$('#addRow').click(function(){

let row=$('#invoice_table tbody tr:first').clone();

row.find('input,select').each(function(){

let name=$(this).attr('name');

if(name){
$(this).attr('name',name.replace(/\d+/,rowIndex));
}

$(this).val('');

});

$('#invoice_table tbody').append(row);

rowIndex++;

});
$('#customer-dropdown').change(function(){
    let id = $(this).find(':selected').data('id');
    if(id){
        $.get('<?php echo Yii::app()->createUrl("salesInvoice/getAddress"); ?>', {id:id}, function(data){
            $('#customer-address').val(data);
        });
    } else {
        $('#customer-address').val('');
    }

});
$(document).on('change','.product_select',function(){

let row=$(this).closest('tr');

let sku=$(this).find(':selected').data('sku');
let name=$(this).find(':selected').data('name');
let price=$(this).find(':selected').data('price');
let stock=$(this).find(':selected').data('stock');

row.find('.sku').val(sku);
row.find('.product_name').val(name);
row.find('.price').val(price);
row.find('.stock').val(stock);

});

$(document).on('keyup change','.qty,.price',function(){

let row=$(this).closest('tr');

let qty=row.find('.qty').val();
let price=row.find('.price').val();

let total=qty*price;

row.find('.total').val(total);

calculateTotals();

});

function calculateTotals(){

let subtotal=0;

$('.total').each(function(){

subtotal+=parseFloat($(this).val())||0;

});

let vat=subtotal*0.05;

let grand=subtotal+vat;

$('#subtotal').val(subtotal.toFixed(2));
$('#vat').val(vat.toFixed(2));
$('#grand_total').val(grand.toFixed(2));

}

$(document).on('click','.removeRow',function(){

if($('#invoice_table tbody tr').length>1){
$(this).closest('tr').remove();
}

});

$('#saveInvoice').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).addClass('btn_loding').removeClass('btn-primary'); // loading style
        $("#loader").show();

        $.ajax({
            url: '<?php echo Yii::app()->createUrl("salesInvoice/save"); ?>',
            type: 'POST',
            data: $('#sales-invoice-form').serialize(),
            dataType: 'json',
            success: function(res) {
                $("#loader").hide();
                btn.prop('disabled', false).removeClass('btn_loding').addClass('btn-primary');

                if (res.status === 'success') {
                    t8.success(res.message); // success notification
                    $('#invoice-modal').modal('hide');
                            $('#tbl_sales_invoice').DataTable().ajax.reload(null, false);

                    // Refresh the grid
                    $.fn.yiiGridView.update('sales-invoice-grid');
                } else {
                    // handle validation errors returned as object or array
                    if (typeof res.message === 'object') {
                        $.each(res.message, function(k, v) {
                            t8.error(v);
                        });
                    } else {
                        t8.error(res.message);
                    }
                }
            },
            error: function(xhr) {
                $("#loader").hide();
                btn.prop('disabled', false).removeClass('btn_loding').addClass('btn-primary');
                t8.error("Something went wrong: " + xhr.responseText);
            }
        });
    });

</script>