@extends('layout.app')
@section('content')
    <div class="" id="vue_app">

        <form action="{{ route('purchase.store') }}" method="POST">
            @csrf
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="form-group col-md-4">
                            <label for="name" class="">
                                Enter Name / Code
                            </label>
                            <input type="text" name="name" id="name" class="form-control"
                                placeholder="Serach Name/code" @keyup="fetch_item()" v-model="search_keyword"
                                autocomplete="off">
                            <ul class="list-group" style="">
                                <li style="cursor: pointer;" class="form-control" @click="select_item(result.id)"
                                    v-for="(result, index) in results">
                                    <a>@{{ result.name }} (@{{ result.code }})</a>
                                </li>
                            </ul>
                        </div>
                        <div class="form-group col-md-4">
                            <label for="supplier_id" class="">
                                Category
                            </label>

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

                            @error('category_id')
                                <div class="alert alert-danger mt-1">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>

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

                            <select name="product_id" id="product_id" v-model="product_id" class="form-control">
                                <option value="">Select Item</option>
                                <option :value="row.id" v-for="row in products" v-html="row.name"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">

                        <button type="button" class="btn btn-success float-right" @click="data_input">Add</button>

                    </div>


                    <div class="" v-if="items.length > 0">
                        <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" required>
                                    <option value="">Select Supplier</option>
                                    @foreach ($suppliers as $supplier)
                                        <option value="{{ $supplier->id }}">{{ $supplier->name }}</option>
                                    @endforeach
                                </select>

                                @error('supplier_id')
                                    <div class="alert alert-danger mt-1">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </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" required>
                                    <option value="">Select Branch</option>
                                    @foreach ($branches as $branch)
                                        <option value="{{ $branch->id }}">{{ $branch->name }}</option>
                                    @endforeach
                                </select>

                                @error('branch_id')
                                    <div class="alert alert-danger mt-1">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>

                            <div class="form-group col-md-4">
                                <label for="voucher_no" class="">
                                    Voucher No
                                </label>
                                <input type="number" name="voucher_no" id="voucher_no" class="form-control"
                                    placeholder="voucher_no" value="{{ old('voucher_no') }}" autocomplete="off" required>

                                @error('voucher_no')
                                    <div class="alert alert-danger mt-1">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div>

                        <table id="datatable" class="table table-bordered">
                            <tr>
                                <th>Item</th>
                                <th>Category</th>
                                <th>Unit</th>
                                <th>Quantity</th>
                                <th>Price</th>
                                <th>Item Total</th>
                                <th>Action</th>
                            </tr>
                            <tr v-for="(row, index) in items">
                                <td>
                                    <input type="hidden" :name="'products[' + index + '][item_id]'" class=""
                                        v-bind:value="row.item_id">

                                    <input type="text" class="form-control" v-bind:value="row.item_name" readonly>
                                </td>
                                <td><input type="text" class="form-control" v-bind:value="row.category" readonly></td>
                                <td><input type="text" class="form-control" v-bind:value="row.unit" readonly>
                                </td>
                                <td>
                                    <input type="number" v-model="row.quantity" :name="'products[' + index + '][quantity]'"
                                        class="form-control" @change="itemtotal(row)" required>
                                </td>
                                <td>

                                    <input type="text" v-model="row.price" :name="'products[' + index + '][price]'"
                                        class="form-control" @change="itemtotal(row)" required>

                                </td>
                                <td>
                                    <input type="text" class="form-control" v-bind:value="itemtotal(row)" readonly>
                                </td>


                                <td>
                                    <button type="button" class="btn btn-danger" @click="delete_row(row)"><i
                                            class="fa fa-times"></i></button>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4">

                                </td>
                                <td>
                                    Net Payable
                                </td>
                                <td>
                                    <input type="text" class="form-control" v-bind:value="subtotal" name="subtotal"
                                        readonly>
                                </td>
                                <td>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">

                                </td>
                                <td colspan="2">
                                    <div class="">
                                        <select class="form-control" v-model="payment_method" name="payment_method"
                                            required @change="payment_method_select">
                                            <option value="">Select Payment Method</option>
                                            <option value="Cash">Cash</option>
                                            <option value="Cheque">Cheque</option>
                                        </select>
                                    </div>
                                </td>
                                <td>
                                    Paid
                                </td>
                                <td>
                                    <input type="text" class="form-control" v-model="paid" name="paid"
                                        @keyup="duecal">
                                </td>
                                <td>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4">
                                    <div class="row" v-if="isBank">
                                        <div class="col-md-3">
                                            <label>Cheque Number</label>
                                            <input type="text" v-model="cheque_number" name="cheque_number"
                                                class="form-control" placeholder="Enter Cheque Number" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label>Bank Account</label>
                                            <select name="bank_account_id" id="bank_account_id" v-model="bank_account_id" class="form-control">
                                                <option value="">Select Bank Account</option>
                                                @foreach ($bank_accounts as $bank_account)
                                                    <option value="{{ $bank_account->id }}">{{ $bank_account->account_name }} - {{ $bank_account->bank_name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label>Account Number</label>
                                            <input type="text" v-model="account_number" name="account_number"
                                                class="form-control" placeholder="Enter Account Number" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label>Branch Name</label>
                                            <input type="text" v-model="branch_name" name="branch_name"
                                                class="form-control" placeholder="Enter Branch Name" required>
                                        </div>
                                        <div class="col-md-3 mt-2">
                                            <label>Bank Name</label>
                                            <input type="text" v-model="bank_name" name="bank_name"
                                                class="form-control" placeholder="Enter Bank Name" required>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    Due
                                </td>
                                <td>
                                    <input type="text" class="form-control" v-model="due" name="due" readonly>
                                </td>
                                <td>
                                </td>
                            </tr>
                        </table>
                        <button class="btn btn-success float-right" type="submit"><i class="fa fa-save"></i>
                            Save</button>
                    </div>

                </div>
            </div>
    </div>
    </form>
    </div>
    </div>
@endsection
@push('css')
    <link rel="stylesheet" href="{{ asset('/') }}plugins/select2/css/select2.min.css">
@endpush

@push('js')
    <script src="{{ asset('vue-js/vue/dist/vue.js') }}"></script>
    <script src="{{ asset('vue-js/axios/dist/axios.min.js') }}"></script>
    <script src="{{ asset('vue-js/bootstrap-select/dist/js/bootstrap-select.min.js') }}"></script>
    <script src="{{ asset('/') }}plugins/select2/js/select2.full.min.js"></script>
    <script>
        $(document).ready(function() {
            var app = new Vue({
                el: '#vue_app',
                data: {
                    config: {
                        get_keyword_wise_item_url: "{{ url('admin/fetch-item-by-search-keyword') }}",
                        get_item_by_id_url: "{{ url('admin/fetch-item-by-item-id') }}",
                        get_category_wise_product_url: "{{ url('admin/fetch-item-by-category-id') }}",
                        get_bank_account_by_id_url: "{{ url('admin/fetch-bank-account-by-id') }}",
                    },
                    category_id: '',
                    supplier_id: '',
                    due: '',
                    payment_method: '',
                    payment_status: '',
                    purchase_status: '',
                    isBank: '',
                    search_keyword: '',
                    results: [],
                    items: [],
                    product_id: '',
                    products: [],
                    cheque_number: '',
                    bank_account_id: '',
                    account_number: '',
                    branch_name: '',
                    bank_name: '',


                },
                computed: {
                    subtotal: function() {
                        return this.items.reduce((total, item) => {
                            return total + item.quantity * item.price
                        }, 0)
                    }
                },

                methods: {
                    payment_method_select() {

                        var vm = this;
                        // alert(vm.payment_method);
                        var slug = vm.payment_method;
                        if (slug == "Cheque") {
                            vm.isBank = true;
                        } else if (slug == "Cash") {
                            vm.isBank = false;
                        }


                    },
                    fetch_bank_account() {
                        var vm = this;
                        var bankAccountId = vm.bank_account_id;
                        if (bankAccountId) {
                            axios.get(this.config.get_bank_account_by_id_url + '/' + bankAccountId).then(function(response) {
                                vm.account_number = response.data.account_no;
                                vm.branch_name = response.data.branch_name;
                                vm.bank_name = response.data.bank_name;
                            }).catch(function(error) {
                                toastr.error('Something went wrong while fetching bank account details', {
                                    closeButton: true,
                                    progressBar: true,
                                });
                            });
                        } else {
                            // Clear fields if no bank account selected
                            vm.account_number = '';
                            vm.branch_name = '';
                            vm.bank_name = '';
                        }
                    },
                    duecal() {

                        var vm = this;
                        //alert(vm.subtotal-vm.paid);
                        vm.due = vm.subtotal - vm.paid;
                        //  return

                    },
                    fetch_item() {
                        var vm = this;
                        var slug = vm.search_keyword;
                        //   alert(slug);
                        if (slug) {
                            vm.results = [];
                            axios.get(this.config.get_keyword_wise_item_url + '/' + slug).then(function(
                                response) {

                                vm.results = response.data;
                                //  console.log(vm.results);
                            }).catch(function(error) {

                                toastr.error('Something went to wrong', {
                                    closeButton: true,
                                    progressBar: true,
                                });

                                return false;

                            });
                        }

                    },
                    fetch_product() {

                        var vm = this;

                        var slug = vm.category_id;

                        if (slug) {
                            axios.get(this.config.get_category_wise_product_url + '/' + slug).then(function(
                                response) {
                                console.log(response.data);
                                vm.products = response.data;


                            }).catch(function(error) {

                                toastr.error('Something went to wrong', {
                                    closeButton: true,
                                    progressBar: true,
                                });

                                return false;

                            });
                        }

                    },

                    select_item(id) {


                        var vm = this;
                        var slug = id;
                        // alert(slug);
                        if (slug) {
                            // vm.results = [];
                            axios.get(this.config.get_item_by_id_url + '/' + slug).then(function(response) {

                                item_details = response.data;
                                if (!vm.items.some(data => data.item_id === item_details.id)) {
                                    vm.items.push({
                                        item_id: item_details.id,
                                        item_name: item_details.name,
                                        unit: item_details.unit.name,
                                        quantity: 1,
                                        price: 0,
                                        itemtotal: 0,
                                        category: item_details.category.name,

                                    });
                                    vm.paid = 0,
                                        vm.due = 0,
                                        vm.search_keyword = '',
                                        vm.results = [];
                                } else {
                                    toastr.info('Already Selected This Item', {
                                        closeButton: true,
                                        progressBar: true,
                                    });

                                    return false;
                                }


                            }).catch(function(error) {

                                toastr.error('Something went to wrong', {
                                    closeButton: true,
                                    progressBar: true,
                                });

                                return false;

                            });
                        }

                    },
                    data_input() {


                        var vm = this;
                        var slug = vm.product_id;
                        //  alert(vm);
                        if (slug) {
                            // vm.results = [];
                            axios.get(this.config.get_item_by_id_url + '/' + slug).then(function(response) {

                                item_details = response.data;
                                console.log(response.data);
                                item_details = response.data;
                                if (!vm.items.some(data => data.item_id === item_details.id)) {
                                    vm.items.push({
                                        item_id: item_details.id,
                                        item_name: item_details.name,
                                        unit: item_details.unit.name,
                                        quantity: 1,
                                        price: 0,
                                        itemtotal: 0,
                                        category: item_details.category.name,

                                    });
                                    vm.paid = 0;
                                    vm.due = 0;
                                    vm.category_id = '';
                                    vm.product_id = '';
                                    vm.results = [];
                                } else {
                                    vm.category_id = '';
                                    vm.product_id = '';
                                    return false;
                                }
                            }).catch(function(error) {

                                toastr.error('Something went to wrong', {
                                    closeButton: true,
                                    progressBar: true,
                                });

                                return false;

                            });
                        }

                    },
                    delete_row: function(row) {
                        this.items.splice(this.items.indexOf(row), 1);
                    },
                    itemtotal: function(index) {
                        if (index.quantity <= 0) {
                            index.quantity = 1;
                        }
                        console.log(index.quantity * index.price);
                        return index.quantity * index.price;


                        // alert(quantity);
                        // var total= row.quantity);
                        // row.itemtotal=total;
                    },

                },
                mounted() {

                    $('#product_id').select2({
                        width: '100%',
                        placeholder: 'Select an Item'
                    });
                    $('#supplier_id').select2({
                        width: '100%',
                        placeholder: 'Select a Supplier'
                    });
                    $('#branch_id').select2({
                        width: '100%',
                        placeholder: 'Select a Branch'
                    });
                    $('#bank_account_id').select2({
                        width: '100%',
                        placeholder: 'Select a Bank Account'
                    }).on('change', (e) => {
                        this.bank_account_id = e.target.value;
                        this.fetch_bank_account();
                    });
                },
                updated() {
                    $('.bSelect').selectpicker('refresh');

                    $('#product_id').select2({
                        width: '100%',
                        placeholder: 'Select an Item'
                    }).on('change', (e) => {
                        this.product_id = e.target.value;
                    });
                    $('#supplier_id').select2({
                        width: '100%',
                        placeholder: 'Select an Supplier'
                    }).on('change', (e) => {
                        this.supplier_id = e.target.value;
                    });
                    $('#branch_id').select2({
                        width: '100%',
                        placeholder: 'Select a Branch'
                    }).on('change', (e) => {
                        this.branch_id = e.target.value;
                    });
                    $('#bank_account_id').select2({
                        width: '100%',
                        placeholder: 'Select a Bank Account'
                    }).on('change', (e) => {
                        this.bank_account_id = e.target.value;
                        this.fetch_bank_account();
                    });
                }
            });

            $('.bSelect').selectpicker({
                liveSearch: true,
                size: 5
            });
        });
    </script>
@endpush
