@extends('layout.app')


@section('content')


    <form action="{{ route('purchase.update',$purchase) }}" method="POST" id="itemReturnForm">
        @method('put')
        @csrf
        <div class="card">
            <div class="card-body">
            <div class="row">
                <div class="form-group col-md-6">
                    <label for="supplier_id" class="">
                        Category
                    </label>

                    <select name="category_id" id="category_id" class="form-control select2">
                        <option value="">Select Category</option>
                        @foreach ($categories as $category)
                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                        @endforeach
                    </select>

                </div>

                <div class="form-group col-md-6">
                    <label for="product_id" class="">
                        Item
                    </label>

                    <select name="product_id" id="product_id"  class="form-control select2">
                        <option value="">Select Item</option>

                    </select>
                </div>
            </div>

                <div>

                    <button class="btn bg-primary float-right mb-2" id="addProduct" >Add</button>
                </div>

                <div class=" mt-2" id="forTable">
                    <div class="row">
                    <div class="form-group col-md-4">
                        <label for="supplier_id" class="">
                            Supplier Name
                        </label>

                        <select name="supplier_id" id="supplier_id"  class="form-control select2">

                            @foreach ($suppliers as $supplier)
                                <option value="{{ $supplier->id }}" @if ($supplier->id==$purchase->supplier_id)
                                    selected
                                @endif>{{ $supplier->name }}</option>
                            @endforeach
                        </select>

                    </div>
                    <div class="form-group col-md-4">
                        <label for="branch_id" class="">
                            Branch
                        </label>

                        <select name="branch_id" id="branch_id" class="form-control select2">
                            <option value="">Select Branch</option>
                            @foreach ($branches as $branche)
                                <option value="{{ $branche->id }}" @if ( $branche->id==$purchase->branch_id)
                                    selected
                                @endif>{{ $branche->name }}</option>
                            @endforeach
                        </select>

                    </div>
                    <div class="form-group col-md-4">
                        <label for="voucher_no" class="">
                            Voucher No
                        </label>

                        <input type="number" class="form-control" id="voucher_no" name="voucher_no" value="{{$purchase->voucher_no}}" required>
                        <input type="hidden" class="form-control" id="id" name="id" value="{{$purchase->id}}" >

                    </div>
                </div>
                <div class="table-responsive">
                    <table id="tableId" class="table">
                        <thead>
                            <th>Item</th>
                            <th>Category</th>
                            <th>Unit</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>Item Total</th>
                            <th>Action</th>
                        </thead>
                        <tbody>
                            @foreach ($purchase->items as $item)
                            <tr>
                                <td style="width: 250px">{{$item->item->name}}<input style="width: 80px" min=0 class="productId" value="{{$item->item->id}}"  type="hidden"  name="productId[]" step=".0001" required></td>
                                <td style="width: 200px">{{$item->item->category->name}}</td>
                                <td style="width: 150px">{{$item->item->unit->name}}</td>
                                <td style="width: 150px"><input class="quantity form-control" value="{{$item->quantity}}" type="number"   name="quantity[]" min=1 required autocomplete="off"></td>
                                <td style="width: 150px"><input class="price form-control" value="{{$item->buying_price}}" type="number" step=".01" name="price[]" min=0  autocomplete="off"></td>
                                <td style="width: 150px"><input  class="lineTotal form-control" value="{{$item->quantity * $item->buying_price }}" type="number" step=".01"  name="lineTotal[]" min=0 style="border: none" readonly autocomplete="off"></td>

                                <td>
                                    <label style="width: 40px" id="btnCancle" step=".01" class="btn btn-danger ">-</lable>
                                </td>
                            </tr>

                            @endforeach
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="4"></td>
                                <td >Net Payable</td>
                                <td><input  class="payable form-control" value="{{$purchase->subtotal}}" type="number" id="payable" step=".01" name="payable" min=0 style="border: none" readonly ></td>
                            </tr>
                            <tr>
                                <td colspan="2"></td>
                                <td colspan="2">
                                    <select name="payment_method_id" id="payment_method_id" class="form-control" required>
                                        <option value="">Select Payment Method</option>
                                        <option value="Cash" @if ($purchase->payment_method=="Cash") selected @endif>Cash</option>
                                        <option value="Cheque" @if ($purchase->payment_method=="Cheque") selected @endif>Cheque</option>
                                    </select>
                                </td>
                                <td >Paid</td>
                                <td><input  class="paid form-control"  value="{{$purchase->paid}}" type="number" id="paid" step=".01" name="paid" min=0  autocomplete="off" ></td>
                            </tr>
                            <tr>
                                <td colspan="4">
                                    <div class="row d-none" id="cheque">
                                        <div class="col-md-3">
                                            <label>Cheque Number</label>
                                            <input type="text" name="cheque_number" id="cheque_number" value="{{$purchase->payment_new->cheque_number ?? ""}}" class="form-control" placeholder="Cheque Number" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label>Bank Account</label>
                                            <select name="bank_account_id" id="bank_account_id" class="form-control">
                                                <option value="">Select Bank Account</option>
                                                @php
                                                    $currentBankAccountId = null;
                                                    if($purchase->payment_method == "Cheque" && $purchase->payment_new) {
                                                        // Get bank_account_id from payment (stored when purchase is created)
                                                        // If not found in payment, check expense (for approved purchases)
                                                        $currentBankAccountId = $purchase->payment_new->bank_account_id ?? null;
                                                        if (!$currentBankAccountId) {
                                                            $expense = \App\Models\Expense::where('invoice_number', $purchase->invoice_number)->first();
                                                            $currentBankAccountId = $expense->bank_account_id ?? null;
                                                        }
                                                    }
                                                @endphp
                                                @foreach ($bank_accounts as $bank_account)
                                                    <option value="{{ $bank_account->id }}" @if($currentBankAccountId == $bank_account->id) selected @endif>{{ $bank_account->account_name }} - {{ $bank_account->bank_name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label>Account Number</label>
                                            <input type="text" name="account_number" id="account_number" value="{{$purchase->payment_new->account_number ?? ""}}" class="form-control" placeholder="Account Number" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label>Branch Name</label>
                                            <input type="text" name="brance_number" id="branch_name" value="{{$purchase->payment_new->branch_name ?? ""}}" class="form-control" placeholder="Branch Name" required>
                                        </div>
                                        <div class="col-md-3 mt-2">
                                            <label>Bank Name</label>
                                            <input type="text" name="bank_name" id="bank_name" value="{{$purchase->payment_new->bank_name ?? ""}}" class="form-control" placeholder="Bank Name" required>
                                        </div>
                                    </div>
                                </td>
                                <td >Due</td>
                                <td><input  class="due form-control" value="{{$purchase->due}}" type="number" step=".01" id="due" name="due" min=0 style="border: none" readonly ></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>


                    <button class="btn bg-info float-right" id="saveBtn" >Save</button>
                </div>


            </div>
        </div>
    </form>



@endsection
@push('js')
<style>
    .table {
        border: 1px solid black;
    }

    .table thead th {
        border-top: 1px solid #000!important;
        border-bottom: 1px solid #000!important;
        border-left: 1px solid #000;
        border-right: 1px solid #000;
    }

    .table td {
        border-left: 1px solid #000;
        border-right: 1px solid #000;

    }
</style>

<script src="{{ asset('/')}}js/jquery.validate.js"></script>

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

    var paymentMethod=$('#payment_method_id').val();
    if(paymentMethod=="Cheque"){
        $("#cheque").removeClass("d-none");
    }

    $('#payment_method_id').change(function(){
        var paymentMethod=$('#payment_method_id').val();
        if(paymentMethod=="Cheque"){
            $("#cheque").removeClass("d-none");
        }else{
            $("#cheque").addClass("d-none");

        }
    });

    // Bank account auto-fill functionality
    $('#bank_account_id').change(function(){
        var bankAccountId = $(this).val();
        if(bankAccountId) {
            $.ajax({
                url: "{{ url('admin/fetch-bank-account-by-id') }}/" + bankAccountId,
                type: 'get',
                success: function (result) {
                    $('#account_number').val(result.account_no);
                    $('#branch_name').val(result.branch_name);
                    $('#bank_name').val(result.bank_name);
                },
                error: function() {
                    toastr.error('Something went wrong while fetching bank account details');
                }
            });
        } else {
            // Clear fields if no bank account selected
            $('#account_number').val('');
            $('#branch_name').val('');
            $('#bank_name').val('');
        }
    });

    $("#tableId").on("click", "#btnCancle", function() {
        $(this).closest("tr").remove();
        sumOfLineTotal();
        netPayable=$('#payable').val();
        paid=$('#paid').val();
        due=parseFloat(netPayable)- parseFloat(paid);
        $('#due').val(due.toFixed(2));
    });

    $(".quantity").keyup(function (){
        // console.log('comes');
        lineTotalFunction($(this));
    });

    $(".price").keyup(function (){

        lineTotalFunction($(this));
    });

    $('#paid').keyup(function () {
        paidFunction();
    });

    function lineTotalFunction(thisObj) {
        var price = thisObj.parents("tr").find( "input.price").val();
        var quantity = thisObj.parents("tr").find("input.quantity").val();
        if(price){
            price=price;
        }else{
            price=0;
        }
        if(quantity){
            quantity=quantity;
        }else{
            quantity=0;
        }
        var lineTotal = parseFloat(price) * parseFloat(quantity);
        thisObj.parents("tr").find("input.lineTotal").val(lineTotal .toFixed(2));

        sumOfLineTotal();
        paidFunction();

    }

    function paidFunction() {
        netPayable=$('#payable').val();
        paid=$('#paid').val();
        due=parseFloat(netPayable)- parseFloat(paid);
        $('#due').val(due.toFixed(2));
    }

    function sumOfLineTotal() {
        sum=0;
        $("tr .lineTotal").each(function(index,value){
            currentLineTotal=parseFloat($(this).val());
            sum +=currentLineTotal;

        });

        $('#payable').val(sum.toFixed(2));

    }

    $('#addProduct').on('click', function (e) {
        e.preventDefault();
        product =$('#product_id').val();
        var productName = $('#product_id').find(":selected").text();

        if(product){
            $('#forTable').removeClass("d-none");
            check=0;
            $("tr .productId").each(function(index,value){
                currentId=parseFloat($(this).val());
                if(currentId==product){
                    check=1;
                }

            });
            if(check==0){
                $.ajax({
                    type: 'get',
                    url: "{{route('add-item-card')}}",
                    data: {id: product},
                    success: function (success) {
                        $('#tableId tbody').append('<tr >' +
                            '<td style="width: 250px "; > '+success.item.name+' <input style="width: 80px" min=0 class="productId" value="'+success.item.id+'"  type="hidden"  name="productId[]" step=".0001" required></td>' +
                            '<td style="width: 200px">'+ success.item.category.name+' </td>' +
                            '<td style="width: 150px">'+ success.item.unit.name+' </td>' +
                            '<td style="width: 150px"><input class="quantity form-control" value="1" type="number"  name="quantity[]" min=0 required autocomplete="off"> </td>' +
                            '<td style="width: 150px"><input class="price form-control" value="0" type="number" step=".01" name="price[]" min=0  autocomplete="off"> </td>' +
                            '<td style="width: 150px"><input  class="lineTotal form-control" type="number" value="0" step=".01" name="lineTotal[]" autocomplete="off" style="border: none" readonly> </td>' +
                            '<td ><lable style="width: 40px" id="btnCancle" step=".01" class="btn btn-danger ">-</lable></td>' +
                            +'</tr>'
                        );

                        $(".quantity").keyup(function (){
                            // console.log('comes');
                            lineTotalFunction($(this));
                        });

                        $(".price").keyup(function (){

                            lineTotalFunction($(this));
                        });

                        $('#paid').keyup(function () {
                            paidFunction();
                        });

                        function lineTotalFunction(thisObj) {
                            var price = thisObj.parents("tr").find( "input.price").val();
                            var quantity = thisObj.parents("tr").find("input.quantity").val();
                            if(price){
                                price=price;
                            }else{
                                price=0;
                            }
                            if(quantity){
                                quantity=quantity;
                            }else{
                                quantity=0;
                            }
                            var lineTotal = parseFloat(price) * parseFloat(quantity);
                            thisObj.parents("tr").find("input.lineTotal").val(lineTotal .toFixed(2));

                            sumOfLineTotal();
                            paidFunction();

                        }

                        function sumOfLineTotal() {
                            sum=0;
                            $("tr .lineTotal").each(function(index,value){
                                currentLineTotal=parseFloat($(this).val());
                                sum +=currentLineTotal;

                            });

                            $('#payable').val(sum.toFixed(2));

                        }
                        function paidFunction() {
                            netPayable=$('#payable').val();
                            paid=$('#paid').val();
                            due=parseFloat(netPayable)- parseFloat(paid);
                            $('#due').val(due.toFixed(2));
                        }
                }





                });



            }else{
                toastr.info("Product allready added");
            }

        }
    });

    $('#category_id').change(function () {
        var id=$('#category_id').val();

        $.ajax({
            url: "{{route('get-item')}}",
            type: 'get',
            data: {data: id},
            success: function (result) {
                $('#product_id').find('option').remove().end().append('<option value="">Select Item</option>');

                $.each(result,function(key, value)
                {
                    $("#product_id").append('<option value=' + value.id + '>' + value.name + '</option>');
                });
            }
        });
    });

    $('#itemReturnForm').on('keydown', 'input', function(event) {

        if (event.which == 13) {
            event.preventDefault();

        }

    });

});
</script>

@endpush

