<?php
use Carbon\Carbon;
?>
@extends('template.app')

@section('title', 'Farmer Return Invoice')

@push('css')
    <!-- data tables -->
    <link href="{{ asset('admin/assets/plugins/datatables/plugins/bootstrap/dataTables.bootstrap4.min.css') }} "
        rel="stylesheet" type="text/css" />
@endpush

@section('content')
    <div class="page-bar">
        <div class="page-title-breadcrumb">

        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="btn-group">
                <a href="{{ route('admin.farmer-return.index') }}" id="addRow1" class="btn btn-primary"
                    style="font-size:14px; padding: 6px 12px;">
                    Farmer Return List <i style="color:white;" class="fa fa-plus"></i>
                </a>

            </div>
            <div class="card card-topline-red">
                <div class="card-head" style="text-align: center;">
                    <header>Create Farmer Return Invoice </header>
                    <div class="tools">
                        <a class="fa fa-repeat btn-color box-refresh" href="javascript:;"></a>
                        <a class="t-collapse btn-color fa fa-chevron-down" href="javascript:;"></a>
                        <a class="t-close btn-color fa fa-times" href="javascript:;"></a>
                    </div>
                </div>
                <div class="card-body ">
                    <form action="{{ route('admin.farmer-return.update', ['farmer_return' => $farmerReturnInvoice->id]) }}"
                        method="post">
                        @csrf @method('UPDATE')
                        <div class="form-row">
                            <div class="col-md-4 col-sm-12 form-group">
                                <label for="invoice">Invoice No</label>
                                <input type="text" name="invoice_no" value="{{ $farmerReturnInvoice->invoice_no }}"
                                    id="invoice" placeholder="Invoice No"
                                    class="form-control @error('invoice_no') is-invalid @enderror" />
                                @error('invoice_no')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-4 col-sm-12 form-group">
                                <label for="date">Date*</label>
                                <input type="date" name="date" value="{{ $farmerReturnInvoice->date }}" id="date"
                                    class="form-control @error('date') is-invalid @enderror" required />
                                @error('date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-4 col-sm-12 form-group">
                                <label for="farmer">Farmer*</label>
                                <select name="farmer_id" id="farmer"
                                    class="form-control @error('farmer_id') is-invalid @enderror">
                                    <option value="" hidden>Select a Farmer</option>
                                    @forelse ($farmers as $farmer)
                                        <option value="{{ $farmer->id }}"
                                            @if ($farmerReturnInvoice->farmer_id == $farmer->id) selected @endif>{{ $farmer->name }}</option>
                                    @empty
                                    @endforelse
                                </select>
                                @error('farmer_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="col-md-12 col-sm-12">
                                <table class="table">
                                    <tbody>
                                        <tr>
                                            <td>
                                                <select id="product" class="form-control">
                                                    <option value="" hidden>Select a Product</option>
                                                    @forelse ($products as $product)
                                                        <option value="{{ $product->id }}">{{ $product->product_name }}
                                                            ({{ $product->size }})</option>
                                                    @empty
                                                    @endforelse
                                                </select>
                                            </td>
                                            <td>
                                                <input type="number" class="form-control" id="unit_price"
                                                    placeholder="Unit Price" />
                                            </td>
                                            <td>
                                                <input type="number" class="form-control" id="quantity"
                                                    placeholder="Quantity" />
                                            </td>
                                            <td>
                                                <input type="number" class="form-control" id="total"
                                                    placeholder="Total" readonly />
                                            </td>
                                            <td>
                                                <button type="button" id="addProduct" class="btn btn-primary">Add</button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-md-12 col-sm-12 form-group">
                                <table class="table table-sm" id="selectedProductTable">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Unit Price</th>
                                            <th>Qty.</th>
                                            <th>Total</th>
                                            <th>&nbsp;</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse ($farmerReturnInvoice->farmerReturnInvoiceItems as $item)
                                            <tr>
                                                <input type="hidden" name="product_id[]" value="{{ $item->id }}" />
                                                <td><input type="text" name="product_name" class="form-control"
                                                        value="{{ $item->product->product_name }}" readonly /></td>
                                                <td><input type="number" name="unit_price[]"
                                                        class="unit_price form-control" value="{{ $item->unit_price }}"
                                                        placeholder="Unit Price" /></td>
                                                <td><input type="number" name="quantity[]" class="quantity form-control"
                                                        value="{{ $item->qty }}" placeholder="Quantity" /></td>
                                                <td><input type="number" name="total[]" class="total form-control"
                                                        value="{{ $item->total }}" placeholder="Total" readonly /></td>
                                                <td><button class="remove_btn btn btn-outline-danger"
                                                        type="button">Remove</button></td>
                                            </tr>
                                        @empty
                                        @endforelse
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="2">Total</td>
                                            <td id="total_qty">{{ $farmerReturnInvoice->farmerReturnInvoiceItems->sum("qty") }}</td>
                                            <td id="total_amount">{{ $farmerReturnInvoice->farmerReturnInvoiceItems->sum("total") }}</td>
                                            <td>&nbsp;</td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="note">Note</label>
                            <textarea name="note" class="form-control" id="" cols="10" rows="3"
                                placeholder="Write Note...">{{ $farmerReturnInvoice->note }}</textarea>
                        </div>
                        {{-- hidden column --}}
                        <input type="hidden" value="{{ $farmerReturnInvoice->total }}" name="grand_total" />
                        <input type="hidden" value="{{ $farmerReturnInvoice->qty }}" name="total_qty" />
                        <div class="form-group">
                            <button class="btn btn-primary" type="submit">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('js')
    <!-- data tables -->
    <script src="{{ asset('admin/assets/plugins/select2/js/select2.js') }}"></script>

    <!-- sweet aleart -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            function calculateTotal() {
                let unitPrice = $("#unit_price").val();
                let quantity = $("#quantity").val();
                $("#total").val(unitPrice * quantity);
            }

            $('#unit_price').on("input", calculateTotal);
            $('#quantity').on("input", calculateTotal);

            $("#addProduct").on("click", function() {
                let product_id = $('#product').val();
                let selected_id = [];
                $("input[name='product_id[]']").each(function() {
                    selected_id.push($(this).val());
                })

                let check = selected_id.includes(product_id);
                if (check) {
                    Swal.fire('Product Already Exists!', '', 'success');
                    clear();
                    return;
                }

                let product_name = $("#product option:selected").text();
                let unit_price = $("#unit_price").val();
                let quantity = $("#quantity").val();
                let total = $("#total").val();
                let output = '';
                output += `<tr>`;
                output += `<input type="hidden" name="product_id[]" value="${product_id}" />`
                output +=
                    `<td><input type="text" name="product_name" class="form-control" value="${product_name}" readonly /></td>`
                output +=
                    `<td><input type="number" name="unit_price[]" class="unit_price form-control" value="${unit_price}" placeholder="Unit Price" /></td>`
                output +=
                    `<td><input type="number" name="quantity[]" class="quantity form-control" value="${quantity}" placeholder="Quantity" /></td>`
                output +=
                    `<td><input type="number" name="total[]" class="total form-control" value="${total}" placeholder="Total" readonly /></td>`
                output +=
                    `<td><button class="remove_btn btn btn-outline-danger" type="button" >Remove</button></td>`
                output += `</tr>`;
                $("#selectedProductTable tbody").append(output);
                clear();
                calculateFooterTotal();
            });

            $(document).on("click", ".remove_btn", function() {
                $(this).closest('tr').remove();
                calculateFooterTotal();
            });

            const calculateFooterTotal = () => {
                let total_amount = 0;
                let total_qty = 0;
                $(document).find('.total').each((index, item) => {
                    total_amount += Number($(item).val());
                });
                $(document).find('.quantity').each((index, item) => {
                    total_qty += Number($(item).val());
                });
                $("#total_amount").text(total_amount);
                $("#total_qty").text(total_qty);
                $("input[name='grand_total']").val(total_amount)
                $("input[name='total_qty']").val(total_qty)
            }

            const calculateEditTotal = (evt) => {
                let tr = $(evt.target).closest('tr');
                let unit_price = $($(tr).find('.unit_price')).val();
                let unit_quantity = $($(tr).find(".quantity")).val();
                $($(tr).find('.total')).val(Number(unit_price * unit_quantity));
                calculateFooterTotal();
            };

            $(document).on("input", ".unit_price", calculateEditTotal);
            $(document).on("input", ".quantity", calculateEditTotal);

            function clear() {
                $('#product').val('');
                $('#unit_price').val('');
                $('#quantity').val('');
                $('#total').val('');
            }

        });
    </script>
@endpush
