@include('header')

<style>
fieldset {
    border: 1px solid #3b6fa5;
    border-radius: 5px;
    padding: 15px;
    margin-bottom: 15px;
    position: relative;
    background: #f5f8fc;
}
fieldset legend {
    position: absolute;
    top: -12px;
    left: 15px;
    background: #f5f8fc;
    padding: 0 8px;
    font-size: 14px;
    color: #1d4b7f;
    font-weight: bold;
}
.form-control {
    height: 32px;
    font-size: 13px;
}
label {
    font-weight: 500;
    margin-bottom: 5px;
    color: #333;
}
.btn {
    min-width: 90px;
    margin: 0 5px;
}
</style>

<div class="container-fluid flex-grow-1 container-p-y">
    <h4 class="font-weight-bold py-3 mb-0">IPD Investigation Master</h4>

    <form id="investigationForm" method="POST">
        @csrf
        <input type="hidden" name="action" id="action" value="Save">
        <input type="hidden" name="id" id="id" value="">

        <fieldset>
            <legend>Investigation Details</legend>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="TestId">Test ID <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="TestId" id="TestId" 
                                placeholder="Test ID" required readonly>
                            <!-- <div class="input-group-append">
                                <button class="btn btn-secondary" type="button" id="browseTestId" 
                                    title="Browse">
                                    <i class="feather icon-search"></i> ...
                                </button>
                            </div> -->
                        </div>
                    </div>
                </div>

                <div class="col-md-8">
                    <div class="form-group">
                        <label for="TestName">Test Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="TestName" id="TestName" 
                            placeholder="Enter Test Name" required>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="Unit">Unit</label>
                        <input type="text" class="form-control" name="Unit" id="Unit" 
                            placeholder="Enter Unit">
                    </div>
                </div>
            </div>
        </fieldset>

        <div class="row" style="margin-top: 20px; margin-bottom: 20px;">
            <div class="col-md-12">
                <div style="text-align: left; padding: 10px;">
                    <button class="btn btn-primary" type="submit" name="submit" id="submit">Save</button>
                    <button class="btn btn-info" type="button" onclick="refreshForm()">Refresh</button>
                    <button class="btn btn-danger" type="button" id="deletebtn" onclick="deleteInvestigation()" disabled>Delete</button>
                    <button class="btn btn-secondary" type="button" onclick="window.close()" style="float: right;">Exit</button>
                </div>
            </div>
        </div>
    </form>

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive" id="investigationList">
                        <!-- Investigation list will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@include('footerscript')
<script src="{{url('assets/js/jquery-3.6.0.min.js')}}"></script>

<script>
function success_toast(message) {
    if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
        $.growl.notice({
            title: 'Success',
            message: message || 'Operation completed successfully!',
            location: isRtl ? 'tl' : 'tr'
        });
    } else {
        alert('Success: ' + (message || 'Operation completed successfully!'));
    }
}

function error_toast(message) {
    if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
        $.growl.error({
            title: 'Error',
            message: message || 'An error occurred!',
            location: isRtl ? 'tl' : 'tr'
        });
    } else {
        alert('Error: ' + (message || 'An error occurred!'));
    }
}

function loadInvestigationList() {
    $.ajax({
        url: "{{ url('ipdInvestigationList') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}'
        },
        success: function(data) {
            $('#investigationList').html(data);
        },
        error: function(xhr, status, error) {
            console.error('Error loading investigation list:', error);
        }
    });
}

function generateTestId() {
    $.ajax({
        url: "{{ url('generateIpdTestId') }}",
        method: "POST",
        data: {
            _token: '{{csrf_token()}}'
        },
        success: function(data) {
            if(data.test_id) {
                $('#TestId').val(data.test_id);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error generating Test ID:', error);
        }
    });
}

function browseTestId() {
    // Open a modal or window to browse existing investigations
    // For now, we'll show a simple prompt or you can implement a modal
    loadInvestigationList();
    
    // You can implement a modal here to select from existing investigations
    // For simplicity, showing the list below
}

function refreshForm() {
    $('#investigationForm')[0].reset();
    $('#action').val('Save');
    $('#id').val('');
    $('#submit').text('Save');
    $('#deletebtn').attr('disabled', true);
    generateTestId();
}

function deleteInvestigation() {
    var id = $('#id').val();
    if(!id) {
        error_toast('No investigation selected to delete');
        return;
    }

    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this investigation!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes, delete",
        cancelButtonText: "No, cancel",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {
            $.ajax({
                url: "{{ url('deleteIpdInvestigation') }}",
                method: "POST",
                data: {
                    _token: '{{csrf_token()}}',
                    id: id
                },
                success: function(data) {
                    if(data.success) {
                        swal("Deleted!", "Investigation has been deleted.", "success");
                        refreshForm();
                        loadInvestigationList();
                    } else {
                        error_toast(data.error || 'Failed to delete investigation');
                    }
                },
                error: function(xhr, status, error) {
                    var errorMsg = xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : 'Failed to delete investigation';
                    error_toast(errorMsg);
                }
            });
        } else {
            swal("Cancelled", "Investigation is safe :)", "error");
        }
    });
}

$(document).ready(function() {
    generateTestId();
    loadInvestigationList();

    // Bind browse button click event
    $('#browseTestId').on('click', function() {
        browseTestId();
    });

    // Handle form submission
    $('#investigationForm').on('submit', function(e) {
        e.preventDefault();
        
        // Check HTML5 validation
        var form = document.getElementById('investigationForm');
        if(form.checkValidity()) {
            $.ajax({
                url: "{{ url('saveIpdInvestigation') }}",
                method: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('#submit').attr('disabled', 'disabled');
                    $('#submit').text('Please Wait...');
                },
                success: function(data) {
                    if(data.success) {
                        success_toast(data.message || 'Investigation saved successfully!');
                        refreshForm();
                        loadInvestigationList();
                    } else {
                        error_toast(data.error || 'Failed to save investigation');
                    }
                    $('#submit').attr('disabled', false);
                    $('#submit').text('Save');
                },
                error: function(xhr, status, error) {
                    var errorMsg = xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : 'Failed to save investigation';
                    error_toast(errorMsg);
                    $('#submit').attr('disabled', false);
                    $('#submit').text('Save');
                }
            });
        } else {
            // Trigger HTML5 validation display
            form.reportValidity();
        }
    });

    // Handle edit from list
    $(document).on("click", ".editInvestigation", function(event) {
        event.preventDefault();
        var id = $(this).attr("data-id");
        
        $.ajax({
            url: "{{ url('getIpdInvestigation') }}",
            method: "POST",
            data: {
                _token: '{{csrf_token()}}',
                id: id
            },
            dataType: "json",
            success: function(data) {
                $('#TestId').val(data.TestId);
                $('#TestName').val(data.TestName);
                $('#Unit').val(data.Unit);
                $('#action').val('Edit');
                $('#id').val(id);
                $('#submit').text('Update');
                $('#deletebtn').attr('disabled', false);
                
                // Scroll to top
                $('html, body').animate({
                    scrollTop: 0
                }, 500);
            },
            error: function(xhr, status, error) {
                var errorMsg = xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : 'Failed to load investigation';
                error_toast(errorMsg);
            }
        });
    });

    // Handle Test ID input - fetch investigation details
    $('#TestId').on('blur', function() {
        var testId = $(this).val();
        if(testId && testId != '') {
            $.ajax({
                url: "{{ url('getInvestigationByTestId') }}",
                method: "POST",
                data: {
                    _token: '{{csrf_token()}}',
                    testId: testId
                },
                dataType: "json",
                success: function(data) {
                    if(data && !data.error) {
                        $('#TestName').val(data.TestName);
                        $('#Unit').val(data.Unit);
                        $('#action').val('Edit');
                        $('#id').val(data.id);
                        $('#submit').text('Update');
                        $('#deletebtn').attr('disabled', false);
                    }
                },
                error: function(xhr, status, error) {
                    // Test ID not found, allow new entry
                }
            });
        }
    });
});
</script>
