@extends('layouts.app')
@section('title','Test Item')
@section('pages')
<style type="text/css">
    .add_btn {
        height: 30px; width: 30px; border-radius: 100%; padding: 0
    }
    .intl-tel-input {
        width: 100%;
    }
</style>

    <!--breadcrumb-->
    <div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
        <div class="breadcrumb-title pe-3">Test Items</div>
        <div class="ps-3">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 p-0">
                    <li class="breadcrumb-item"><a href="{{ url('dashboard')}}"><i class="bx bx-home-alt"></i></a></li>
                    <li class="breadcrumb-item active" aria-current="page">Edit Test Item</li>
                </ol>
            </nav>
        </div>
        <div class="ms-auto">
            <div class="btn-group">
                <a href="javascript:history.back()" 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">
            <div class=" shadow-none radius-5 min-height">
                <div class="">
                    <div class="">
                        <form class="row g-3 auto-width form" id="test_items_form" method="post" action="{{ route('test-items.update', $data->id) }}">
                            @csrf
                            @method('put')
                            <input type="hidden" class="data_id" value="{{ $data->id }}">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-body g-3 row">
                                        <h5 class="mb-0">Test Item Information</h5>
                                        <hr class="mb-0">

                                        <div class="col-md-12">
                                            <label for="validationCustomUsername" class="form-label">Test Name <span class="text-danger"><b>*</b></span></label>

                                            <input type="text" class="form-control test_name" id="validationCustomUsername" name="name" value="{{ $data->name }}" aria-describedby="inputGroupPrepend" placeholder="test name">
                                            <span class="text-danger error_test_name" style="display:none;">This field is required.</span>
                                        </div>

                                        <div class="col-md-12">
                                            <label for="validationCustomUsername" class="form-label">Test Type </label>

                                            <select class="form-control item_type" name="item_type">
                                                <option {{ ($data->item_type == 'TEST_ITEM') ? 'selected' : '' }} value="TEST_ITEM">TEST ITEM
                                                </option>

                                                <option {{ ($data->item_type == 'TEST_LABEL') ? 'selected' : '' }} value="TEST_LABEL">TEST LABEL
                                                </option>

                                                <option {{ ($data->item_type == 'TEST_COMMENT_FOR_TECHNICIAN') ? 'selected' : '' }}
                                                value="TEST_COMMENT_FOR_TECHNICIAN">TEST COMMENT FOR TECHNICIAN
                                                </option>
                                            </select>
                                        </div>

                                        <div class="col-md-12">
                                            <label for="validationCustomUsername" class="form-label">Short Name</label>

                                            <input type="text" value="{{ $data->short_name }}" class="form-control short_name" id="validationCustomUsername" name="short_name" placeholder="short name" aria-describedby="inputGroupPrepend">
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationCustom01" class="form-label">Test Unit</label>

                                            <div class="input-group mb-3">
                                                <select style="width: 50%" class="form-control primary_unit_id" id="primary_unit_id" name="primary_unit_id">
                                                    <option value=''>Select</option>
                                                    @foreach ($test_units as $test_unit)
                                                        <option
                                                        {{ ($data->primary_unit_id == $test_unit->id) ? 'selected' : '' }}
                                                        value='{{ $test_unit->id }}'>{{ $test_unit->name }}</option>
                                                    @endforeach
                                                </select>

                                                @if(auth()->user()->can('test-unit-create'))
                                                <div class="input-group-append" style="margin: auto 10px;">
                                                    <button class="btn btn-success add_btn" id="create_test_unit" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                                </div>
                                                @endif
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <label class="form-label">Method of Test</label>

                                            <div class="input-group mb-3">
                                                <select style="width: 50%" class="form-control test_method_id" id="test_method_id" name="test_method_id">
                                                    <option value=''>Select</option>
                                                    @foreach ($test_methods as $test_method)
                                                        <option
                                                        {{ ($data->test_method_id == $test_method->id) ? 'selected' : '' }}
                                                        value='{{ $test_method->id }}'>{{ $test_method->name }}</option>
                                                    @endforeach
                                                </select>

                                                @if(auth()->user()->can('test-method-create'))
                                                <div class="input-group-append" style="margin: auto 10px;">
                                                    <button class="btn btn-success add_btn" id="create_test_method" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                                </div>
                                                @endif
                                            </div>
                                        </div>

                                        <div class="col-12 d-flex justify-content-center">
                                            <a class="btn btn-primary w-100 save_button">
                                                <i class="bx bx-plus "></i>Update Test Item
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-body g-3 row">
                                        <h5 class="mb-0">Additional Information</h5>
                                        <hr class="mb-0">

                                        {{-- <div class="col-md-6">
                                            <label class="form-label">Test Code </label>

                                            <input type="text" value="{{ $data->code }}" class="form-control code" placeholder="any test code" name="code"/>
                                        </div> --}}

                                        <div class="col-md-6">
                                            <label for="validationCustomUsername" class="form-label">Style</label>
                                            <select  class="form-control" name="title_style">
                                                <option value="normal" {{ matchSelected($data->title_style, 'normal') }}>Normal</option>
                                                <option value="bold" {{ matchSelected($data->title_style, 'bold') }}>Bold</option>
                                                <option value="italic" {{ matchSelected($data->title_style, 'italic') }}>Italic</option>
                                            </select>
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationCustomUsername" class="form-label">Test ID</label>

                                            <input type="text" value="{{ $data->test_number }}" class="form-control test_number" id="validationCustomUsername" name="test_number" placeholder="test id" aria-describedby="inputGroupPrepend">
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationCustom01" class="form-label">Default Result</label>

                                            <input type="text" value="{{ $data->default_result }}" class="form-control default_result" id="validationCustomUsername" name="default_result" placeholder="default result" aria-describedby="inputGroupPrepend">
                                        </div>

                                        <div class="col-md-6">
                                            <label class="form-label">Formula Code </label>

                                            <input type="text" value="{{ $data->formula_code }}" class="form-control formula_code" placeholder="Any Formula Code" name="formula_code"/>
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationCustomUsername" class="form-label">Hints for Technician</label>

                                            <input type="text" value="{{ $data->result_guide }}" class="form-control result_guide" id="validationCustomUsername" name="result_guide" placeholder="hints" aria-describedby="inputGroupPrepend">
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationTextarea" class="form-label">Test Details </label>

                                            <input type="text" value="{{ $data->details }}" class="form-control details" id="validationCustomUsername" name="details" placeholder="details" aria-describedby="inputGroupPrepend">
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationTextarea" class="form-label">Result Input Type</label>

                                            <select class="form-control input_type" name="input_type" required>
                                                <option
                                                {{ ($data->input_type == 'NUMBER') ? 'selected' : '' }}
                                                value="NUMBER">NUMBER
                                                </option>

                                                <option
                                                {{ ($data->input_type == 'TEXT') ? 'selected' : '' }}
                                                value="TEXT">TEXT
                                                </option>

                                                <option
                                                {{ ($data->input_type == 'TIME') ? 'selected' : '' }}
                                                value="TIME">TIME
                                                </option>

                                                <option
                                                {{ ($data->input_type == 'SUMMER_NOTE') ? 'selected' : '' }}
                                                value="SUMMER_NOTE">SUMMER NOTE
                                                </option>

                                                <option
                                                {{ ($data->input_type == 'IMAGE') ? 'selected' : '' }}
                                                value="IMAGE">IMAGE
                                                </option>

                                                <option
                                                {{ ($data->input_type == 'PDF') ? 'selected' : '' }}
                                                value="PDF">PDF
                                                </option>
                                            </select>
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationCustom01" class="form-label">Reference Value Type</label>

                                            <select class="form-control reference_value_type" onchange="ReferenceValueType()" name="reference_value_type">
                                                <option value="">EMPTY</option>
                                                <option
                                                {{ ($data->reference_value_type == 'RANGE') ? 'selected' : '' }}
                                                value="RANGE">RANGE
                                                </option>

                                                <option
                                                {{ ($data->reference_value_type == 'OPTIONS') ? 'selected' : '' }}
                                                value="OPTIONS">OPTIONS
                                                </option>

                                                <option
                                                {{ ($data->reference_value_type == 'TEXT') ? 'selected' : '' }}
                                                value="TEXT">TEXT
                                                </option>
                                            </select>
                                        </div>

                                        <div class="col-md-6">
                                            <label for="validationCustom01" class="form-label">Result Source</label>

                                            <select class="form-control result_source" onchange="ResultSource()" name="result_source">
                                                <option value="">DEFAULT</option>

                                                <option
                                                {{ ($data->result_source == 'MANUAL') ? 'selected' : '' }}
                                                value="MANUAL">MANUAL
                                                </option>

                                                <option
                                                {{ ($data->result_source == 'CALCULATED') ? 'selected' : '' }}
                                                value="CALCULATED">CALCULATED
                                                </option>

                                                <option
                                                {{ ($data->result_source == 'INTERFACE') ? 'selected' : '' }}
                                                value="INTERFACE">INTERFACE
                                                </option>
                                            </select>
                                        </div>

                                        <div class="col-md-12 reference_value_container" style="display: none;">
                                            <label for="reference_value" class="form-label">Reference Value</label><span class="text-danger"></span>

                                            <input type="text" value="{{ $data->reference_value }}" class="form-control reference_value" name="reference_value" placeholder="reference value" aria-describedby="inputGroupPrepend">
                                            <span class="text-danger error_reference_value" style="display: none;">This field is required.</span>
                                        </div>

                                        <div class="col-md-12 machine-select-option machine_and_equipment_container" style="display: none;">
                                            <label for="validationCustom01" class="form-label">Machine & Equipment</label><span class="text-danger"><b>*</b></span>

                                            <div class="input-group mb-3">
                                                <select style="width: 50%" class="form-control machine_and_equipment" name="machine_id">
                                                    <option value=''>Select</option>
                                                    @foreach ($machines as $machine)
                                                        <option
                                                        {{ ($data->machine_id == $machine->id) ? 'selected' : '' }}
                                                        value='{{ $machine->id }}'>{{ $machine->device_model_name }}
                                                        </option>
                                                    @endforeach
                                                </select>

                                                @if(auth()->user()->can('machine-and-equipment-create'))
                                                <div class="input-group-append" style="margin: auto 10px;">
                                                    <button class="btn btn-success add_btn" id="create_machine" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                                </div>
                                                @endif
                                            </div>
                                            <span class="text-danger error_machine_and_equipment" style="display: none;">This field is required.</span>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('js')
<script>
    ResultSource();
    ReferenceValueType();

    $(document).on('click', '#create_departments', function(){
        $('#commonModalLabel').text('Add New Department');
        $('.save_button_span').text('Save Department');
        $.ajax({
          url:"{!! route('departments.create') !!}",
          success:function(data){
            $('#commonModal').addClass('department');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $(document).on('click', '#create_test_unit', function(){
        $('#commonModalLabel').text('Add New Test Unit');
        $('.save_button_span').text('Save Test Unit');
        $.ajax({
          url:"{!! route('test-units.create') !!}",
          success:function(data){
            $('#commonModal').addClass('unit');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $(document).on('click', '#create_sample_type', function(){
        $('#commonModalLabel').text('Add New Sample Type');
        $('.save_button_span').text('Save Sample Type');
        $.ajax({
          url:"{!! route('sample-types.create') !!}",
          success:function(data){
            $('#commonModal').addClass('sample_type');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $(document).on('click', '#create_test_method', function(){
        $('#commonModalLabel').text('Add New Test Method');
        $('.save_button_span').text('Save Test Method');
        $.ajax({
          url:"{!! route('test-methods.create') !!}",
          success:function(data){
            $('#commonModal').addClass('test_method');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $(document).on('click', '#create_style_type', function(){
        $('#commonModalLabel').text('Add New Style Type');
        $('.save_button_span').text('Save Style Type');
        $.ajax({
          url:"{!! route('style-types.create') !!}",
          success:function(data){
            $('#commonModal').addClass('style_type');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $(document).on('click', '#create_machine', function(){
        $('#commonModalLabel').text('Add New Machine');
        $('.save_button_span').text('Save Machine');
        $.ajax({
          url:"{!! route('machine-and-equipments.create') !!}",
          success:function(data){
            $('#commonModal').addClass('machine');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $('#commonModal').on("hidden.bs.modal", function() {
        $('#commonModal').removeClass('department');
        $('#commonModal').removeClass('unit');
        $('#commonModal').removeClass('sample_type');
        $('#commonModal').removeClass('test_method');
        $('#commonModal').removeClass('style_type');
        $('#commonModal').removeClass('machine');
    });

    $(document).on('click', '.save_button', function(event){
        event.preventDefault();

        if ($('#commonModal').hasClass('department')) {

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_department_name').show();
              return;
            } else {
                let formdata = new FormData($('#department_form')[0]);

                $.ajax({
                    url: "{!! route('departments.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="department_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="department_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').hasClass('unit')) {

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_primary_name').show();
              return;
            } else {
                let formdata = new FormData($('#primary_unit_form')[0]);

                $.ajax({
                    url: "{!! route('test-units.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="primary_unit_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="primary_unit_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').hasClass('sample_type')) {

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              return;
            }
            else {
                let formdata = new FormData($('#sample_type_form')[0]);

                $.ajax({
                    url: "{!! route('sample-types.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="sample_type_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="sample_type_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').hasClass('test_method')) {

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_test_method_name').show();
              return;
            }
            else {
                let formdata = new FormData($('#test_method_form')[0]);

                $.ajax({
                    url: "{!! route('test-methods.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="test_method_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="test_method_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').hasClass('style_type')) {

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_style_type_name').show();
              return;
            }
            else {
                let formdata = new FormData($('#style_type_form')[0]);

                $.ajax({
                    url: "{!! route('style-types.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="style_type_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="style_type_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').hasClass('machine')) {

            if ($('#commonModal').find('form').find('input[name="device_model_name"]').val().trim() == '') {
              $('.error_device_model_name').show();
              return;
            }
            else {
                let formdata = new FormData($('#machine_form')[0]);

                $.ajax({
                    url: "{!! route('machine-and-equipments.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="machine_id"]').append(`<option value="${response.data.id}" selected>${response.data.device_model_name}</option>`);
                            $('[name="machine_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else{
            $('.error_test_name').hide();
            $('.error_reference_value').hide();
            $('.error_machine_and_equipment').hide();
            var error = 0;

            if ($('.test_name').val().trim() == '') {
              $('.error_test_name').show();
              error = 1;
            }

            if ($('.result_source').val() == 'INTERFACE' && $('.machine_and_equipment').val() == '') {
              $('.error_machine_and_equipment').show();
              error = 1;
            }

            /*if ($('.reference_value_type').val() == 'TEXT' && $('.reference_value').val().trim() == '') {
              $('.error_reference_value').show();
              error = 1;
            }*/

            if (error == 0) {
                $('.form').submit();
            }
            error = 1;
        }
    });

    function ReferenceValueType() {

        var value = $('.reference_value_type').val();

        if(value == 'TEXT'){
            $('.reference_value_container').show();
        }else{
            $('.reference_value_container').hide();
        }
    }

    function ResultSource() {

        var value = $('.result_source').val();

        if(value == 'INTERFACE'){
            $('.machine_and_equipment_container').show();
        }else{
            $('.machine_and_equipment_container').hide();
        }
    }
</script>
@endsection
