@extends('layouts.app')
@section('title','Container Details')
@section('pages')

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<link rel="stylesheet" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.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">Booking Container Details</div>
      <div class="ps-3">
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb mb-0 p-0">
            <li class="breadcrumb-item active" aria-current="page">Container Details</li>
        </ol>
        </nav>
       </div>
    <div class="ms-auto">
        <div class="btn-group">
          <a href="{{route('booking-register.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">
    <div class="col-xl-12 mx-auto">
        <div class="shadow-none radius-5 min-height">
            <form class="row g-3" action="{{ route('updatecontainer', $containerDetails->id) }}" method="post" enctype="multipart/form-data">

                <div class="card col-md-12  mb-2  ">
                    <div class="card-body">
                        <h5 class="mb-2">Container  Details</h5>
                        <hr class="mb-2">
                        @csrf

                        <div class="row g-3">
                            <div class="col-md-2 mx-3">
                                <label for="container_no" class="form-label">Container No</label>
                                <input type="text" id="container_no" name="container_no" class="form-control" value="{{ $containerDetails->container_no }}">
                            </div>

                            <div class="col-md-2 mx-3">
                                <label for="seal_no" class="form-label">Seal Number</label>
                                <input type="text" name="seal_no" id="seal_no" class="form-control" value="{{ $containerDetails->seal_no }}">
                            </div>

                            <div class="col-md-2 mx-3">
                                <label for="container_size_id" class="form-label">Container Size </label>
                                <select name="container_size_id" id="container_size_id" class="form-control">
                                    @foreach($container_sizes as $container_size)
                                    <option value="{{$container_size->id}}">{{$container_size->code}}</option>
                                    @endforeach
                              </select>
                            </div>

                            <div class="col-md-2 mx-3">
                                <label for="container_type_id" class="form-label">Container Type </label>
                                <select name="container_type_id" id="container_type_id" class="form-control">
                                    @foreach($container_types as $container_type)
                                    <option value="{{$container_type->id}}">{{$container_type->code}}</option>
                                    @endforeach
                              </select>
                            </div>

                            <div class="col-md-2 mx-3">
                                <label for="tracking_number" class="form-label">Tracking Number</label>
                                <input type="text" name="tracking_number" id="tracking_number" class="form-control" value="{{ $containerDetails->tracking_number }}">
                            </div>

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

                <div class="card col-md-12  mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Vessel Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">

                            <div class="col-md-3">
                                <label for="unique_vessel_no" class="form-label">Unique Vessel No</label>
                                <input type="text" name="unique_vessel_no" id="unique_vessel_no" class="form-control" value="{{ $containerDetails->unique_vessel_no }}">
                            </div>

                            <div class="col-md-3">
                                <label for="vessel_name" class="form-label">Vessel Name</label>
                                <input type="text" name="vessel_name" id="vessel_name" class="form-control" value="{{ $containerDetails->vessel_name }}">
                            </div>

                            <div class="col-md-3">
                                <label for="bill_of_landing_no" class="form-label">Bill Of Landing No</label>
                                <input type="text" name="bill_of_landing_no" id="bill_of_landing_no" class="form-control" value="{{ $containerDetails->bill_of_landing_no }}">
                            </div>

                            <div class="col-md-3">
                                <label for="voyage_no" class="form-label">Voyage No</label>
                                <input type="text" name="voyage_no" id="voyage_no" class="form-control" value="{{ $containerDetails->voyage_no }}">
                            </div>

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



                 <div class="card col-md-12  mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Cargo Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">

                            <div class="col-md-3">
                                <label for="cargo_type_id " class="form-label">Cargo Type </label>
                                <select name="cargo_type_id" id="cargo_type_id" class="form-control">
                                    @foreach($cargo_types as $cargo_type)
                                    <option value="{{$cargo_type->id}}">{{$cargo_type->code}}</option>
                                    @endforeach
                              </select>
                            </div>

                            <div class="col-md-3">
                                <label for="cargo_weight" class="form-label">Cargo Weight</label>
                                <input type="text" name="cargo_weight" id="cargo_weight" class="form-control" value="{{ $containerDetails->cargo_weight }}">
                            </div>

                            <div class="col-md-3">
                                <label for="cargo_volume" class="form-label">Cargo Volume</label>
                                <input type="text" name="cargo_volume" id="cargo_volume" class="form-control" value="{{ $containerDetails->cargo_volume }}">
                            </div>

                            <div class="col-md-3">
                                <label for="cargo_shipping_line_id" class="form-label">Cargo Shipping Line Id</label>
                                <input type="text" name="cargo_shipping_line_id" id="cargo_shipping_line_id" class="form-control" value="{{ $containerDetails->cargo_shipping_line_id }}">
                            </div>

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

                <div class="card col-md-8 mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Letter of Credit Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="lc_no" class="form-label">Letter of Credit (LC) Number</label>
                                <input type="text" name="lc_no" id="lc_no" class="form-control" value="{{ $containerDetails->lc_no }}">
                            </div>

                            <div class="col-md-4">
                                <label for="lc_date" class="form-label">Letter of Credit (LC) Date</label>
                                <input type="text" name="lc_date" id="lc_date" class="form-control" value="{{ $containerDetails->lc_date }}">
                            </div>

                            <div class="col-md-4">
                                <label for="lc_authority_id" class="form-label"><b> Letter of Credit (LC) Issued By</b><span class="text-danger"><b>*</b></span></label>
                                <div class="input-group autocomplete">
                                    <input type="text" id="lc_authority_id" class="lc_issued_by-select form-control" placeholder="Search LC Issued By" value="{{ $account->name ?? '' }}">
                                    <ul class="searchResult"></ul>
                                    <input type="hidden" name="lc_authority_id" value="{{ $account->id ?? '' }}">
                                    <button class="btn btn-secondary add_btn" id="create_lc_issued_by" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                    <button class="btn btn-sm btn-primary" style="margin-left: 4px; width:45px" type="button" id="edit_lc_issued_by" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i></button>
                                </div>
                            </div>

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

                <div class="card col-md-4  mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Port Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="loading_port_id " class="form-label">Loading Port Id </label>
                                <input type="text" name="loading_port_id" id="loading_port_id" class="form-control" value="{{ $containerDetails->loading_port_id }}">
                            </div>

                            <div class="col-md-6">
                                <label for="destination_port_id" class="form-label">Destination Port Id </label>
                                <input type="text" name="destination_port_id" id="destination_port_id" class="form-control" value="{{ $containerDetails->destination_port_id }}">
                            </div>

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

                <div class="card col-md-6  mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Insurance Compliance Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="insurance_value" class="form-label">Insurance Value</label>
                                <input type="text" name="insurance_value" id="insurance_value" class="form-control" value="{{ $containerDetails->insurance_value }}">
                            </div>

                            <div class="col-md-4">
                                <label for="customs_clearance_status_id">Customs Clearance Status</label>
                                <select name="customs_clearance_status_id" id="customs_clearance_status_id" class="form-control">
                                    @foreach($custom_returns as $custom_return)
                                    <option value="{{$custom_return->id}}">{{$custom_return->code}}</option>
                                    @endforeach
                              </select>
                            </div>

                            <div class="col-md-4">
                                <label for="security_compliance" class="form-label">Security Compliance</label>
                                <input type="text" name="security_compliance" id="security_compliance" class="form-control" value="{{ $containerDetails->security_compliance  }}">
                            </div>

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

                 <div class="card col-md-6  mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Return Information Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">
                            <div class="col-md-4">
                                <label for="return_expiry_date" class="form-label">Return Expiry Date</label>
                                <input type="text" name="container_return_date" id="container_return_date" class="form-control" value="{{ $containerDetails->container_return_date }}">
                            </div>

                            <div class="col-md-4">
                                <label for="container_return_expiry_date" class="form-label">Container Return Expiry Date</label>
                                <input type="text" name="container_return_expiry_date" id="container_return_expiry_date" class="form-control" value="{{ $containerDetails->container_return_expiry_date }}">
                            </div>

                            <div class="col-md-4">
                                <label for="container_return_status_id" class="form-label">Container Return Status</label>
                                <select name="container_return_status_id" id="container_return_status_id" class="form-control">
                                    @foreach($custom_clearances as $custom_clearance)
                                    <option value="{{$custom_clearance->id}}">{{$custom_clearance->code}}</option>
                                    @endforeach
                              </select>
                            </div>


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

                <div class="card col-md-12  mb-2 ">
                    <div class="card-body">
                        <h5 class="mb-2">Other Details</h5>
                        <hr class="mb-2">

                        <div class="row g-3">
                            <div class="col-md-3">
                                <label for="delivery_order_no" class="form-label">Delivery Order (DO) Number</label>
                                <input type="text" name="delivery_order_no" id="delivery_order_no" class="form-control" value="{{ $containerDetails->delivery_order_no }}">
                            </div>

                            <div class="col-md-3">
                                <label for="delivery_order_validity_date" class="form-label">Delivery Order (DO) Validity Date</label>
                                <input type="text" name="delivery_order_validity_date" id="delivery_order_validity_date" class="form-control" value="{{ $containerDetails->delivery_order_validity_date }}">
                            </div>

                            <div class="col-md-3">
                                <label for="cfs_agent" class="form-label"><b>CFS Agent</b><span class="text-danger"><b>*</b></span></label>
                                <div class="input-group autocomplete">
                                    <input type="text" id="cfs_agent_id" class="cfs_agent-select form-control" placeholder="Search CFS Agent" value="{{ $agent->name }}">
                                    <ul class="searchResult"></ul>
                                    <input type="hidden" name="cfs_agent_id" value="{{ $agent->id ?? '' }}">
                                    <button class="btn btn-secondary add_btn" id="create_cfs_agent" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                    <button class="btn btn-sm btn-primary" style="margin-left: 4px; width:45px" type="button" id="edit_cfs_agent" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i></button>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <label for="temperature_control" class="form-label">Temperature Control</label>
                                <input type="text" name="temperature_control" id="temperature_control" class="form-control" value="{{ $containerDetails->temperature_control }}">
                            </div>

                            <div class="col-md-3">
                                <label for="temperature_range" class="form-label">Temperature Range</label>
                                <input type="text" name="temperature_range" id="temperature_range" class="form-control" value="{{ $containerDetails->temperature_range }}">
                            </div>

                            <div class="col-md-3">
                                <label for="estimated_arrival_date" class="form-label">Estimated Arrival Date</label>
                                <input type="text" name="estimated_arrival_date" id="estimated_arrival_date" class="form-control" value="{{ $containerDetails->estimated_arrival_date  }}">
                            </div>

                            <div class="col-md-3">
                                <label for="offload_destination_date" class="form-label">Offload Destination Date</label>
                                <input type="text" name="offload_destination_date" id="offload_destination_date" class="form-control" value="{{ $containerDetails->offload_destination_date  }}">
                            </div>

                            <div class="col-md-3">
                                <label for="remarks" class="form-label">Remarks</label>
                                <input type="text" name="remarks" id="remarks" class="form-control" value="{{ $containerDetails->remarks  }}">
                            </div>

                            <div class="col-md-12 text-center mt-3">
                                <button class="btn btn-primary w-40 mt-3">Save Container Details</button>
                            </div>

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

            </form>
        </div>
    </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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>

function isNumber(value) 
    {
    return typeof value === 'number';
    }

    function reinitializeTelInput(countryCode) {
        var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no');
        telInput.intlTelInput('destroy'); // Destroy the existing instances

        telInput.intlTelInput({
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
            initialCountry: countryCode || '{!! $countryCode ?? '' !!}',
            separateDialCode: true
        });
    }

    function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }

$(function () {
        $('#container_return_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

$(function () {
        $('#return_expiry_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

$(function () {
        $('#delivery_order_validity_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#container_return_expiry_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#offload_destination_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#estimated_arrival_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });
    $(function () {
        $('#lc_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })
    });

    // search LC issued By
    $(document).ready(function(){
        $('.lc_issued_by-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="lc_issued_by_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('customer-account-search') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="lc_issued_by_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="lc_issued_by_id"]').val(ui.item.id);
                $('.lc_issued_by_id').hide();
                $('#lc_date').focus();
                return false;

            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {

            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

  const customerSelect = document.querySelector(".consignor-select");

  const querySelector = document.querySelector(".searchResult");


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

    // search CFS
    $(document).ready(function(){
        $('.cfs_agent-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="cfs_agent_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('customer-account-search') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="cfs_agent_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="cfs_agent_id"]').val(ui.item.id);
                $('.cfs_agent_id').hide();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {

            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

    const customerSelect = document.querySelector(".consignor-select");

    const querySelector = document.querySelector(".searchResult");


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

    function isNumber(value) {
    return typeof value === 'number';
    }

    function reinitializeTelInput(countryCode) {
        var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no');
        telInput.intlTelInput('destroy'); // Destroy the existing instances

        telInput.intlTelInput({
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
            initialCountry: countryCode || '{!! $countryCode ?? '' !!}',
            separateDialCode: true
        });
    }

    // creating accounts
    $(document).on('click', '#create_lc_issued_by', function(){
        $('#commonModalLabel').text('Add New LC Issued By');
        $('.save_button_span').text('Save LC Issued BY');
        $('.save_button').addClass('save-lc_issued_by');
         var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajax({
          url:"{!! route('booking.createconsignor') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

            $(".consignor_columns").remove();
            $(".consignee_columns").remove();
            $(".vendor_columns").remove();
            $(".cfs_agent_columns").remove();
            $('#quality_form').append('<input type="hidden" name="accounting_group_id" value="'+accounting_group_id+'">')
            $('#quality_form').append('<input type="hidden" name="account_type_id" value="'+account_type_id+'">')
            reinitializeTelInput();
          }
        });
    }); 

    $(document).on('click', '#create_cfs_agent', function(){
        $('#commonModalLabel').text('Add New CFS Agent');
        $('.save_button_span').text('Save CFS Agent');
        $('.save_button').addClass('save-cfs_agent');
         var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajax({
          url:"{!! route('booking.createconsignor') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $(".consignor_columns").remove();
            $(".consignee_columns").remove();
            $(".vendor_columns").remove();
            $(".lc_issued_by_columns").remove();
            $('#quality_form').append('<input type="hidden" name="accounting_group_id" value="'+accounting_group_id+'">')
            $('#quality_form').append('<input type="hidden" name="account_type_id" value="'+account_type_id+'">')
            reinitializeTelInput();
          }
        });
    });

 $(document).on('click', '#edit_lc_issued_by', function() {
        $('.save_button').addClass('save-lc_issued_by');
        var customerName = $('[name="lc_issued_by_id"]').val();
        if (customerName.trim() === "") {
            $('.error_patient_id').show();
        } else {
            $('.error_patient_id').hide();

            $('#commonModalLabel').text('Edit LC Issued By');
            $('.save_button_span').text('Update LC Issued By');
            var id = $('[name="lc_issued_by_id"]').val();
            var url = `{!! route('booking.editconsignor', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $(".consignor_columns").remove();
                    $(".consignee_columns").remove();
                    $(".vendor_columns").remove();
                    $(".cfs_agent_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });

    $(document).on('click', '#edit_cfs_agent', function() {
        $('.save_button').addClass('save-cfs_agent');
        var customerName = $('[name="cfs_agent_id"]').val();
        if (customerName.trim() === "") {
            $('.error_patient_id').show();
        } else {
            $('.error_patient_id').hide();

            $('#commonModalLabel').text('Edit CFS Agent');
            $('.save_button_span').text('Update CFS Agent');
            var id = $('[name="cfs_agent_id"]').val();
            var url = `{!! route('booking.editconsignor', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $(".consignor_columns").remove();
                    $(".consignee_columns").remove();
                    $(".vendor_columns").remove();
                    $(".lc_issued_by_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });

    // save lc issued by 
    $(document).on('click', '.save-lc_issued_by', function(event){
       event.preventDefault();
         if ($('#phone_no').val().trim() != '') {
            var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
            var dailcode_array = dailcode_title.split("+");
            $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
        }

        if ($('#whatsapp_no').val().trim() != '') {
            var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
            var dailcode_array = dailcode_title.split("+");
            $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
        }

      $('.error_name').hide();
      var error = 0;

      if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
      $('.error_name').show();
      error = 1;
      setTimeout(function () {
      $('.error_name').hide();
      }, 3000);
      }

       if (error == 0) {
              let formdata = new FormData($('#commonModal').find('form')[0]);
              $.ajax({
                  url: $('#commonModal').find('form').attr('action'),
                  data: formdata,
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  success: function (response) {
                      if (response.success === true) {
                          toastr.success(response.message, 'Success.');
                          $('[name="lc_issued_by_id"]').val(response.data.id);
                          $('#lc_issued_by_id').val(response.data.name);
                          $('.vendor').hide();
                          $('#edit_lc_issued_by').prop('disabled', false);
                          $('.save_button').removeClass('save-lc_issued_by');
                          // hide modal
                          $('#commonModal').modal('hide');
                          $('#commonModal').find('.modal-body').html('');
                      } 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!');

      // hide modal
      $('#commonModal').modal('hide');
      $('#commonModal').find('.modal-body').html('');
    });
    }
    error = 1;
    });

    // save cfs agent 
    $(document).on('click', '.save-cfs_agent', function(event){
   event.preventDefault();
     if ($('#phone_no').val().trim() != '') {
        var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
        var dailcode_array = dailcode_title.split("+");
        $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
    }

    if ($('#whatsapp_no').val().trim() != '') {
        var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
        var dailcode_array = dailcode_title.split("+");
        $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
    }

  $('.error_name').hide();
  var error = 0;

  if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
  $('.error_name').show();
  error = 1;
  setTimeout(function () {
  $('.error_name').hide();
  }, 3000);
  }

   if (error == 0) {
          let formdata = new FormData($('#commonModal').find('form')[0]);
          $.ajax({
              url: $('#commonModal').find('form').attr('action'),
              data: formdata,
              processData: false,
              contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      $('[name="cfs_agent_id"]').val(response.data.id);
                      $('#cfs_agent_id').val(response.data.name);
                      $('.cfs_agent_id').hide();
                      $('#edit_cfs_agent').prop('disabled', false);
                      $('.save_button').removeClass('save-cfs_agent_id');
                      // hide modal
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');
                  } 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!');

  // hide modal
  $('#commonModal').modal('hide');
  $('#commonModal').find('.modal-body').html('');
});
}
error = 1;
    });

    // Disabling & Enabling edit button of LC Issued By 
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="lc_issued_by_id"]').val();
            $('#edit_lc_issued_by').prop('disabled', patientId.trim() === "");
        }

        toggleEditButton();

        $('#lc_issued_by_id').on('input', function() {
            toggleEditButton();
        });

        $('#lc_issued_by_id').on('change', function() {
            toggleEditButton();
        });


        function enableEditButton() {
            $('#edit_lc_issued_by').prop('disabled', false);
        }

    });

    // Disabling & Enabling edit button of CFS Agent 
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="cfs_agent_id"]').val();
            $('#edit_cfs_agent').prop('disabled', patientId.trim() === "");
        }

        toggleEditButton();

        $('#cfs_agent_id').on('input', function() {
            toggleEditButton();
        });

        $('#cfs_agent_id').on('change', function() {
            toggleEditButton();
        });


        function enableEditButton() {
            $('#edit_cfs_agent').prop('disabled', false);
        }
    });
</script>
@endsection

