@extends('layouts.app')
@section('title','Book Return')
@section('pages')
<style type="text/css">
    .clear {
        clear: both;
        margin-top: 20px;
    }

    .autocomplete {
        position: relative;
    }

    .autocomplete .searchResult {
        list-style: none;
        padding: 0px;
        width: 78%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 5;
    }

    .autocomplete .searchResult li {
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even) {
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover {
        cursor: pointer;
        background: #CACFD2;
    }

    #add_reference i {
        height: 20px;
        width: 20px;
        background: #0d6efd25;
        color: #0d6efd;
        text-align: center;
        border-radius: 50px;
        line-height: 20px;
    }

    .add_btn {
        height: 40px;
        width: 40px;
        font-size: 16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }

    .custom_grid {
        padding-left: 1rem;
        padding-right: 1rem;
    }

    .custom_grid .input-group {
        position: relative;
    }

    .custom_grid .input-group .form-label {
        position: absolute;
        top: -10px;
        left: 5px;
        font-size: 12px;
        padding: 0px 8px;
        background-color: #f7f8fa;
        z-index: 5;
    }

    .custom_grid .input-group .form-control.br-0 {
        border-radius: 0;
    }

    .custom_grid .btn {
        font-size: 22px;
        padding: 0.15rem 0.75rem;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
    }

    .select2-container--bootstrap4 .select2-selection {
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
    }

    .error {
        border: solid red 1px;
    }

    .checkbox {
        display: block !important;
    }

    .ui-switcher {
        display: none !important;
    }

    .select2-selection__arrow {
        display: none;
    }
</style>

<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Book Return</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Add New Book Return</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('book-return.index')}}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">


        <form class="auto-width create_billing ajaxformfileupload" action="{{route('book-return.store')}}" method="post" enctype='multipart/form-data'>
            <!-- For validation comment on -->
            <!-- <form class="row g-3 was-validated"> -->
            @csrf

            <div class="card style_table">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="mb-0">Book Issue Information</h6>
                </div>
                <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div>
                                <label> Student (Roll No/Admission No/Name)<span class="text-danger">*</span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="student_id" class="studen-select form-control" placeholder="Student (Roll No/Admission No/Name)" onkeypress="handleEnter(event)">
                                <input type="hidden" name="student_name" id="student_id" value="">

                            </div>
                            <span class="text-danger error_student_id" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Issue Date <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" class="form-control datepickerss" placeholder="return_date" id="return_date" aria-label="return_date" name="return_date" value="{{date('d/m/Y')}}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Finacial Year<span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <select class="single-select form-control br-0" id="financial_year_id" name="financial_year_id" required>
                                    @foreach($financialYears as $list)
                                    <option value="{{ $list->financialyearid}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->financial_year_name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <button type="button" class="btn btn-outline-primary mt-3" onclick="getbooksData()"><i class="bi bi-search"></i> Search Book</button>
                        </div>
                    </div>
                </div>
            </div>


            <div class="cart_products">
                <div class="card style_table" style="margin-bottom:0.8rem;">
                    <div class="card-header d-flex align-items-center justify-content-between">
                        <h6 class="mb-0">Total Item in Cart <i class="bi bi-cart"></i> ({!! isset($data) ? count($data) : '0' !!})</h6>
                        <button type="submit" class="btn btn-outline-primary" id="checkout"><i class="bx bx-plus"></i> Add New</button>
                    </div>
                    <div class="card-body pb-0">

                        <div class="table-responsive">
                            <table id="example" class="table table-bordered align-middle" style="width:100%">
                                <thead class="table-light">
                                    <tr>
                                        <th class="thbutton"><input type="checkbox" class="checkbox" id="selectAll"> All</th>
                                        <th class="text-start">ITEM NAME</th>
                                        <th scope="col">Return Qty</th>
                                        <th scope="col">Damage Qty</th>
                                        <th scope="col">Amount</th>
                                        <th scope="col" class="thbutton">Damage</th>
                                    </tr>
                                </thead>
                                <tbody id="bookslist">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>




            </div>
        </form>
    </div>
</div>
<!--end row-->

@endsection

@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>

<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#checkout').html('Submit To Book Return')
    });
</script>
<script>

    $("#selectAll").click(function() {
        $('.checkbox').not(this).prop('checked', this.checked);
    });

    $("body").on("change", '.changetoDamage', function(event) {
        var id = $(this).data('id');
        if ($(this).prop('checked')) {
            //$('#exampleModaldamage').modal('show');
            //$('#book_return_id').val(id);
            $("#damageqty" + id).prop("readonly", false);
            $('#damage_amount' + id).prop("readonly", false);
        } else {
            $("#damageqty" + id).prop("readonly", true);
            $('#damage_amount' + id).prop("readonly", true);
            $('#return_qty' + id).prop("readonly", false);
            $("#damageqty" + id).val(0);
            $("#return_qty" + id).val(1);
        }
    });

    /*********delete data**********/
    $("body").on("keyup", '.return_qty', function(event) {
        var id = $(this).data('id');
        var issue_qty = $('#issue_qty' + id).val();
        var return_qty = $('#return_qty' + id).val();
        var html = '';
        if (issue_qty < return_qty) {
            //alert('Return Qauntity is greater then issue quantity');

            var ErroMsg = 'Return Qauntity is greater then issue quantity'
            $(this).Toastshow('error', ErroMsg);

            var return_qty = $('#return_qty' + id).val(html);
        }
    });

    $("body").on("keyup", '.damage_qty', function(event) {
        var id = $(this).data('id');
        var damageqty = $('#damageqty' + id).val();
        var return_qty = $('#return_qty' + id).val();
        //var html='';
        // if(return_qty<damageqty)
        // {
        //alert('Return Qauntity is smaller then damage quantity');
        // var ErroMsg = 'Return Qauntity is smaller then damage quantity'
        // $(this).Toastshow('error',ErroMsg);

        //var return_qty= $('#damageqty'+id).val(html);

        $('#return_qty' + id).val(0);
        $('#return_qty' + id).prop("readonly", true);
        $("#damageqty" + id).prop("required", true);
        // }
    });

    $(document).ready(function() {

        $('[name="issue_date"]').datepicker({
            "dateFormat": "dd-mm-yy",
            "maxDate": '0',
            "changeMonth": true,
            "changeYear": true
        }).datepicker("setDate", 'now')
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })



    });
    $('#issue_date').datepicker().on('changeDate', function(ev) {
        $(this).datepicker('hide');
    });

    function getbooksData() {
        let student_id = $('#student_id').val();

        $.ajax({
            type: "POST",
            url: "{{ route('return.returnBooksearch') }}",
            data: {
                student_id: student_id
            },
            success: function(data) {
                $('#bookslist').html(data);
            },
            error: function(data) {
                //console.log(data);
            }
        });
    }

    function fetch_cart() {
        $.ajax({
            url: "{!! route('getissueCart') !!}",
            success: function(data) {
                $('.cart_products').html('');
                $('.cart_products').html(data);
            }
        })
    }





    $('.studen-select').autocomplete({
        autoFocus: true,
        minLength: 0,
        source: function(request, response) {
            if (request.term.length < 2) {
                $('[name="student_name"]').val('');
                return false;
            }

            $.ajax({
                url: "{{ route('autocomplete.studentssearch') }}",
                type: 'GET',
                dataType: 'json',
                data: {
                    q: request.term
                },
                success: function(json) {
                    console.log(json.result);
                    if (json.error) {
                        $('[name="student_name"]').val('');
                        return false;
                    }
                    response($.map(json.result, function(item) {
                        //console.log(item);
                        return {
                            id: item.id,
                            name: item.name,
                        };
                    }));
                }
            });
        },
        select: function(event, ui) {
            console.log(ui);
            event.preventDefault();
            var class_name = ui.item.class_name != null ? ', ' + ui.item.class_name : '';

            $(this).val(ui.item.name + class_name + "");
            $('[name="student_name"]').val(ui.item.id);
            getbooksData();
            return false;
        }
    }).data("ui-autocomplete")._renderItem = function(ul, item) {
        var class_name = item.class_name != null ? ', ' + item.class_name : '';
        return $("<li>")
            .append("<a>" + item.name + class_name + "</a>")
            .appendTo(ul);
    };



    $('.livebooks').autocomplete({
        autoFocus: true,
        minLength: 0,
        source: function(request, response) {
            if (request.term.length < 2) {
                $('[name="book_name"]').val('');
                return false;
            }

            $.ajax({
                url: "{{ route('autocomplete.bookssearch') }}",
                type: 'GET',
                dataType: 'json',
                data: {
                    q: request.term
                },
                success: function(json) {
                    console.log(json.result);
                    if (json.error) {
                        $('[name="book_name"]').val('');
                        return false;
                    }
                    response($.map(json.result, function(item) {
                        //console.log(item);
                        return {
                            id: item.id,
                            name: item.name,
                            shortcode: item.shortcode,
                        };
                    }));
                }
            });
        },
        select: function(event, ui) {
            console.log(ui);
            event.preventDefault();
            $(this).val(ui.item.name + "");
            $('[name="book_name"]').val(ui.item.id);
            $('#isbn').val(ui.item.shortcode);
            return false;
        }
    }).data("ui-autocomplete")._renderItem = function(ul, item) {
        return $("<li>")
            .append("<a>" + item.name + "</a>")
            .appendTo(ul);
    };


    const bookSelect = document.querySelector(".livebooks");

    document.addEventListener("click", (event) => {
        if (event.target !== bookSelect) {
            $(".searchResult").empty();
        }
    });


    $(document).ready(function() {
        $(document).on('keyup change input', '[name="student_id"]', function(event) {
            if (event.keyCode === 13) {
                getbooksData();
            }
        });


    });

    function handleEnter(event) {
        if (event.key === "Enter") {
            event.preventDefault(); // Prevent form submission (if any)
            // Your code to execute when the "Enter" key is pressed
            getbooksData();
            // Add any other functionality you want here
        }
    }


    $(document).on('click', '.add_to_cart', function(e) {
        e.preventDefault();

        $('.error_book_id').hide();
        $('.error_student_id').hide();
        var error = 0;

        if ($('input[name="book_name"]').val().trim() == '') {
            $('.error_book_id').show();
            error = 1;
        }

        if ($('[name="student_name"]').val().trim() == '') {
            $('.error_student_id').show();
            error = 1;
        }

        if (error == 0) {
            let student_id = $('[name="student_name"]').val();
            let book_id = $('[name="book_name"]').val();
            $.ajax({
                    url: "{{ route('add.to.issue.cart') }}",
                    data: {
                        student_id: student_id,
                        book_id: book_id
                    },
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            $('.livebooks').val('');
                            $('#isbn').val('');
                            fetch_cart();
                            toastr.success(response.message, 'Success.');


                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
        }

        error = 1;
    })

    const patientSelect = document.querySelector(".patient-select");
    const doctorSelect = document.querySelector(".doctor-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== patientSelect && event.target !== doctorSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });



    /*********delete data**********/
    $("body").on("click", '.deleteDataCustom', function(event) {
        dataString = {
            "id": $(this).data('id')
        };
        var UrlValue = $(this).data('url');
        var btn = $(this);

        Swal.fire({
            title: 'Are you sure you want to delete this?',
            icon: 'warning',
            showDenyButton: true,
            showCancelButton: false,
            confirmButtonText: 'Yes',
            denyButtonText: 'No',
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    url: UrlValue,
                    method: 'post',
                    data: {
                        "_token": $('meta[name="csrf-token"]').attr('content'),
                        "id": $(this).data('patient_id')
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    beforeSend: function(xhr) {
                        // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },
                    success: function(response) {
                        if (response.success) {
                            var ErroMsg = $(this).printErrorMsg(response.message);

                            $(this).Toastshow('success', ErroMsg);
                            fetch_cart();
                        } else {
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', ErroMsg);
                        }
                    },
                    error: function(data) {
                        console.log("error ", data);
                    }
                });
            }
        });
    });
</script>
@endsection
