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

.autocomplete{
    position: relative;
}
.accounts-select{
    margin-top: 16px !important;
}
.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;
    }
</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" />

    <!--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> Contra Vouchers</div>
        <div class="ps-3">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 p-0">

                    <li class="breadcrumb-item active" aria-current="page">New Contra Voucher Entry</li>
                </ol>
            </nav>
        </div>
        <div class="ms-auto">
            <div class="btn-group">
                <a href="{{route('contra-vouchers.index')}}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            </div>
        </div>
    </div>
    <!--end breadcrumb-->

    <div class="row auto">
        <form class="create_billing auto-width" id="create_contra_voucher_form" action="{{ route('add-contra-vouchers')}}" method="post" enctype='multipart/form-data'>
            <!-- For validation comment on -->
            <!-- <form class="row g-3 was-validated"> -->
            @csrf
            <div class="col-xl-12 mx-auto">
                <div class="card style_table">
                    <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                        <div class="row align-items-center">
                        <div class="col-md-4">
                            <div>
                                <label class="form-label">Date <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="transaction_date" id="transaction_date" class="doctor-select form-control" id="transaction_date" placeholder="Date" value="" readonly="">
                            </div>
                            <span class="text-danger error_transaction_date" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-4">
                            <div>
                                <label class="form-label">#Voucher No / Reference No</label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="voucher_no" id="voucher_no" class="patient-select form-control" placeholder="Search Voucher No">
                                <ul class="searchResult"></ul>
                            </div>
                            <span class="text-danger error_voucher_no" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-4">
                            <div>
                                <label class="form-label">Financial Year<span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <select class="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' : '' !!} title="{{$list->financial_year_name}}">{{$list->financial_year_name}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <span class="text-danger error_financial_year_id" style="display:none;">This field is required.</span>
                        </div>
                    </div>
                    </div>
                    {{-- <div class="row custom_grid align-items-end gx-0 mt-4 mb-3">
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Accounts <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="account_name" id="account_id" class="accounts-select form-control" placeholder="Search Account">
                                <ul class="searchResult"></ul>
                                <input type="hidden" name="account_id" value="">
                            </div>

                        </div>
                        <div class="col-md-2">
                            <div class="input-group">
                                <label for="debit" class="form-label">Debit Amount</label>
                                <input type="number" name="debit" class="form-control br-0 amount" value="" placeholder="Enter Debit Amount">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="input-group">
                                <label for="credit" class="form-label">Credit Amount</label>
                                <input type="number" name="credit" class="form-control br-0 amount" value="" placeholder="Enter Credit Amount">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="input-group autocomplete">
                                <label class="form-label">Narration</label>
                                <input type="text" name="details_narration" id="details_narration" class="form-control" placeholder="Write Narration">
                            </div>
                            <span class="text-danger error_details_narration" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-primary add_to_cart w-100" type="button"><i class="bx bx-plus"></i></button>
                        </div>
                            <span class="text-danger error_duplicate_voucher_no" style="display:none;">This Item is Already Added to Cart.</span>
                        <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                            <span class="text-danger error_credit" style="display:none;">Please enter Debit or credit amount. Both inputs can not be empty.</span>
                    </div> --}}
                </div>
                <div class="cart_products">
                    <div class="card style_table shadow-none" style="margin-bottom:0.8rem;">
                        <div class="card-body pb-0">
                            <div class="table-responsive">
                                <table id="example" class="table table-bordered align-middle voucher-entries" style="width:100%">
                                    <thead class="table-light">
                                        <tr>
                                            <th class="text-start">Account Name</th>
                                            <th>Narration</th>
                                            <th style="text-align: right;">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="cart-products">
                                            <td class="text-start">
                                                <input type="text" name="debit_account_name" id="debit_account_id" class="accounts-select form-control" placeholder="Debit Account Search">
                                                <ul class="searchResult"></ul>
                                                <input type="hidden" name="debit_account_id" value="">
                                                <span class="text-danger error_debit_account_id" style="display:none;">This field is required.</span>
                                            </td>
                                            <td>
                                                <input type="text" name="debit_details_narration" class="form-control bg-white" value="" placeholder="Narration">
                                            </td>
                                            <td>
                                                <input type="text" name="debit" class="form-control bg-white debit debit_amount" style="text-align: right;" placeholder="Debit Amount">
                                                <span class="text-danger error_debit" style="display:none;">This field is required.</span>
                                            </td>
                                        </tr>
                                        <tr class="cart-products">
                                            <td class="text-start">
                                                <input type="text" name="credit_account_name" id="credit_account_id" class="accounts-select form-control" placeholder="Credit Account Search">
                                                <ul class="searchResult"></ul>
                                                <input type="hidden" name="credit_account_id" value="">
                                                <span class="text-danger error_credit_account_id" style="display:none;">This field is required.</span>
                                            </td>
                                            <td>
                                                <input type="text" name="credit_details_narration" class="form-control bg-white" value="" placeholder="Narration">
                                            </td>
                                            <td>
                                                <input type="text" name="credit" class="form-control bg-white credit credit_amount" style="text-align: right;" placeholder="Credit Amount">
                                                <span class="text-danger error_credit" style="display:none;">This field is required.</span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card style_table">
                <div class="row align-items-end gx-0 mt-4 mb-3">
                    <div class="col-md-12 px-3">
                        <div>
                            <label class="form-label">Note / Description  </label>
                        </div>
                        <div class="input-group">
                            <textarea class="form-textarea" name="description" id="description" rows="3"></textarea>
                        </div>
                        <span class="text-danger error_description" style="display:none;">This field is required.</span>
                    </div>
                    <div class="col-12 mt-4" align="center">
                        <div class="d-grid gap-2" style="width: 20%">
                          <button class="btn btn-md btn-primary save_button" type="button"><i class="bx bx-save"></i> Save Contra Vouchers</button>
                      </div>
                    </div>
                </div>
            </div>

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

@endsection

@section('js')
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>

<script>
     $('#transaction_date').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        }).datepicker("setDate", new Date());

    $(document).on('click','.save_button', function(e) {

        e.preventDefault();
        $('.error_transaction_date').hide();
        $('.error_debit_account_id').hide();
        $('.error_credit_account_id').hide();
        $('.error_credit').hide();
        $('.error_debit').hide();
        var error = 0;

        if ($('[name="financial_year_id"]').val() == null || $('[name="financial_year_id"]').val() == '') {
          $('.error_financial_year_id').show();
          error = 1;
        } else if (validateDate()) {
          toastr.error('Selected date must be in between Financial Years!', 'Error!');
          error = 1;
        }

        if ($('input[name="transaction_date"]').val().trim() == '') {
          // $('.error_transaction_date').show();
          error = 1;
          toastr.error('Transaction Date field is required!', 'Error!');
        }

        if ($('input[name="debit_account_id"]').val().trim() == '') {
          // $('.error_debit_account_id').show();
          toastr.error('Debit account field is required!', 'Error!');
          error = 1;
        }

        if ($('input[name="debit"]').val().trim() == '') {
          toastr.error('Debit amount field is required!', 'Error!');
          error = 1;
        }

        if ($('input[name="credit_account_id"]').val().trim() == '') {
          toastr.error('Credit account field is required!', 'Error!');
          error = 1;
        }

        if ($('input[name="credit"]').val().trim() == '') {
          // $('.error_credit').show();
          error = 1;
          toastr.error('Credit amount field is required!', 'Error!');
        }

        if (error == 0) {
            var form = document.getElementById("create_contra_voucher_form");
            let formdata = new FormData(form);

            $.ajax({
                url: "{!! route('contra-voucher-submit') !!}",
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        //  ;
                        $('#transaction_date').val('');
                        $('#voucher_no').val('');
                        $('#description').val('');
                        $('#financial_year_id').val('');

                        //  ;

                        setTimeout(function() {
                            window.location.href = "{!! route('contra-vouchers.index') !!}";
                        }, 1000);


                        return false;
                    } 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!');
            });
        }
    });

    $(document).on('input','[name="credit"]', function(e) {
        e.preventDefault();
        $('[name="debit"]').val(allNumeric(this.value));
        $('[name="credit"]').val(allNumeric(this.value));
    });
    $(document).on('input','[name="debit"]', function(e) {
        e.preventDefault();

        $('[name="debit"]').val(allNumeric(this.value));
        $('[name="credit"]').val(allNumeric(this.value));
    });

    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }

    $(document).ready(function(){

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

                $.ajax({
                    url: "{{ route('contra-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action      : 'get_accounts_for_contra_voucher',
                        search_text : request.term,
                        account_id  : $('[name="credit_account_id"]').val()
                    },
                    success: function(json) {
                        //  ;
                        if (json.error) {
                            $('[name="debit_account_id"]').val('');
                            return false;
                        }
                        //  ;
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                //  ;
                event.preventDefault();
                $(this).val(ui.item.name + "");
                $('[name="debit_account_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            //  ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

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

                $.ajax({
                    url: "{{ route('contra-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action      : 'get_accounts_for_contra_voucher',
                        search_text : request.term,
                        account_id  : $('[name="debit_account_id"]').val()
                    },
                    success: function(json) {
                        //  ;
                        if (json.error) {
                            $('[name="credit_account_id"]').val('');
                            return false;
                        }
                        //  ;
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                //  ;
                event.preventDefault();
                $(this).val(ui.item.name + "");
                $('[name="credit_account_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            //  ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

    });

    const patientSelect = document.querySelector(".accounts-select");
    const querySelector = document.querySelector(".searchResult");

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


    function validateDate() {
        //debugger;
        // Your date input field ID
        var dateInput = $("#transaction_date").val();
       
        var selectedDate = parseDateString(dateInput);
       
        var selectedOption = $("#financial_year_id option:selected");

        // Get the title attribute of the selected option
        var selectedTitle = selectedOption.attr("title");
        var dateParts = selectedTitle.split('-');

        // Extract individual values
        var startYear = dateParts[0];
        var endYear = dateParts[1];

        // Get the selected date from the input field
       //var selectedDate = new Date(dateInput.val());

        if (selectedDate >= new Date(startYear, 0, 1) && selectedDate <= new Date(endYear, 11, 31)) {
            return false;
        } else {
            return true;
        }
    };

    function parseDateString(dateString) {
    const formats = [
        'MM/DD/YYYY',
        'MM-DD-YYYY',
        'YYYY/MM/DD',
        'YYYY-MM-DD',
        'DD/MM/YYYY',
        'DD-MM-YYYY',
        'dd/mm/YYYY'
        // Add more formats as needed
    ];

    for (const fmt of formats) {
        const date = moment(dateString, fmt, true); // The `true` flag is for strict parsing
        if (date.isValid()) {
            return date.toDate(); // Convert moment object to JavaScript Date object
        }
    }

    console.error("Invalid date format");
    return null;
}
</script>
@endsection
