Rapport-Laravel/resources/views/form/rapport-team4/1774621694-60538ad9-1e71-4a...

982 lines
47 KiB
PHP

<!DOCTYPE html>
<html lang="en">
<head>
@include('layouts.shared/title-meta', ['title' => "Form"])
@include('layouts.shared/head-css', ["mode" => $mode ?? '', "demo" => $demo ?? ''])
<link href="{{asset('assets/libs/sweetalert2/sweetalert2.min.css')}}" rel="stylesheet" type="text/css" />
</head>
<div id="pageloader">
<img src="http://cdnjs.cloudflare.com/ajax/libs/semantic-ui/0.16.1/images/loader-large.gif" alt="processing..." />
</div>
<body class="loading">
<div class="account-pages">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8 col-lg-6 col-xl-5 p-0">
<div class="card bg-pattern">
<div class="card-body p-3 row">
@if(Session::has('error'))<div class="alert alert-danger">{{Session::get('error')}}</div>
<br>@endif
@if(session('success'))<div class=" alert alert-success">{{ session('success') }}
</div>
<br>@endif
<div class="col-8">
<h4 class="page-title">{{$form->title}}</h4>
</div>
@if(!isset($form->is_approval) || (isset($form->is_approval) && $form->is_approval != 'yes' ) )
<div class="col-4">
@if($form->link_type == 'form')
<a href="/form/history" class="float-end pt-1">View History</a>
@else
<a href="{{url()->previous()}}" class="float-end pt-1">Back</a>
@endif
</div>
@endif
@if(isset($form->user_info))
<div class="col-12">
<h6>Submitted By: {{$form->user_info->name}}</h6>
</div>
@endif
@php
$submissions = Formhelper::getMultiformData( $form->partition, $form_id, $form->user_id);
$submissions = $submissions->data->submissions;
// echo "<pre>";
// print_r($submissions);
@endphp
@php
$alreadySubmitted = false;
$currentMonth = date('m');
$currentYear = date('Y');
if (!empty($submissions)) {
$alreadySubmitted = true;
// foreach ($submissions as $submission) {
// if (!empty($submission->record_date)) {
// $submittedDate = strtotime($submission->record_date);
// if (
// date('m', $submittedDate) == $currentMonth &&
// date('Y', $submittedDate) == $currentYear
// ) {
// $alreadySubmitted = true;
// break;
// }
// }
// }
}
@endphp
@if(count($submissions) < 3 )
<form method="POST" action="/form/submit" id="report-form" enctype="multipart/form-data">
<input type="hidden" name="form_id" value="{{$form_id}}">
<input type="hidden" name="user_id" value="{{$form->user_id}}">
@csrf
@if($id)
<input type="hidden" name="id" value="{{$id}}">
@endif
@if(isset($form->manager_can_submit) && $form->manager_can_submit == true)
<div class="col-md-12 mb-2">
<label for="field-user_id" class="form-label"> Select User / Territory <span class="text-danger">*</span> </label>
<select class="form-control" id="field-user_id" name="user_id" required>
<option value=""> -- Select -- </option>
@foreach($form->users as $option)
<option value="{{$option->value}}" hierarchy="{{$option->hierarchy_id}}" {{isset($question->value) && $question->value == $option->value ? 'selected':''}}>{{$option->display}}</option>
@endforeach
</select>
<input type="hidden" id="field-hierarchy_id" name="hierarchy_id" value="">
</div>
@endif
@foreach($questions as $question)
<div class="col-md-12 mb-2">
<label for="field-{{$question->code}}" class="form-label">{{$question->question}} {!!$question->required == 'yes' ? '<span class="text-danger">*</span>':''!!} </label>
@switch($question->type)
@case('hidden')
<input type="{{$question->type}}" id="field-{{$question->code}}" name="{{$question->code}}" value="{{isset($question->value)?$question->value:''}}">
@break
@case('text')
@case('email')
@case('tel')
@case('date')
<input type="{{$question->type}}" id="field-{{$question->code}}" name="{{$question->code}}" class="form-control" {{$question->required == 'yes'?'required':'' }} value="{{isset($question->value)?$question->value:''}}">
@break
@case('number')
<input type="{{$question->type}}" min="0" max="9999999999" step="1" id="field-{{$question->code}}" name="{{$question->code}}" class="form-control" {{$question->required == 'yes'?'required':'' }} value="{{isset($question->value)?$question->value:0}}">
@break
@case('textarea')
<textarea id="field-{{$question->code}}" name="{{$question->code}}" class="form-control" {{$question->required == 'yes'?'required':'' }}>{{isset($question->value)?$question->value:''}}</textarea>
@break
@case('dropdown')
@if ($question->code == 'contact_id')
<select class="form-control" id="field-{{ $question->code }}"
name="{{ $question->code }}"
{{ $question->required == 'yes' ? 'required' : '' }}>
<option value=""> -- Select -- </option>
@foreach ($question->options as $option)
@php $spec = $option->contact->speciality ?? ''; @endphp
@if (in_array($spec, ['ANAESTHETIST','CARDIOLOGIST','Chemist','Chemist/Pharmacy','CHEST PHYSICIAN','Consultant Physician','Consulting Physician','CVTS','DENTIST','DERMATOLOGIST','DIABETOLOGIST','ENT SURGEON','GASTROENTEROLOGIST','GENERAL PHYSICIAN','GP NON MBBS','GYNAECOLOGIST','INTENSIVE CARE','Intensivist','Nephrologist','NEUROLOGIST','ONCOLOGIST','OPHTHALMOLOGIST','ORTHOPEDICIAN','OTHERS SPECIALITIES','PAEDIATRICIAN','PEAD CARDIOLOGIST','PEDIATRICIAN','Physician Consulting','POST GRADUATE','PRACTICING DIABETOLOGIST','PSYCHIATRIST','PULMONOLOGIST','RHEUMATOLOGIST','SURGEON','Test DIABETOLOGIST','UROLOGIST']))
<option value="{{ $option->value }}"
{{ isset($question->value) && $question->value == $option->value ? 'selected' : '' }}
legacy_code="{{ $option->contact->legacy_code ?? '' }}"
speciality="{{ $spec }}">
{{ $option->display }}
</option>
@endif
@endforeach
</select>
@else
<select class="form-control" id="field-{{ $question->code }}"
name="{{ $question->code }}"
{{ $question->required == 'yes' ? 'required' : '' }}>
<option value=""> -- Select -- </option>
@foreach ($question->options as $option)
<option value="{{ $option->value }}"
{{ isset($question->value) && $question->value == $option->value ? 'selected' : '' }}>
{{ $option->display }}</option>
@endforeach
</select>
@endif
@break
@case('checkbox')
@foreach($question->options as $option)
<div class="form-check mb-2 form-check-primary">
<input class="form-check-input" type="checkbox" id="field-{{$question->code}}-{{$option->value}}" name="{{$question->code}}[]" value="{{$option->value}}" {{isset($question->value) && $question->value != '' && in_array($option->value, $question->value) ? 'checked':''}}>
<label class="form-check-label" for="field-{{$question->code}}-{{$option->value}}">{{$option->display}}</label>
</div>
@endforeach
@break
@case('file')
@if(!isset($form->is_approval) || (isset($form->is_approval) && $form->is_approval != 'yes' ) )
<input type="file" id="field-{{$question->code}}" name="{{$question->code}}" class="form-control" value="" {{$question->required == 'yes'?'required':'' }}>
@elseif(isset($question->value))
<img src="{{$question->value}}" class="img-fluid">
@endif
@break
@case('multitextbox')
<div class="row">
@foreach($question->options as $option)
<div class="col-6">{{$option->display}}</div>
<div class="col-6 mb-1">
<input type="number" id="field-{{$option->value}}" name="{{$option->value}}" class="form-control" required value="{{isset($option->val)?$option->val:0}}">
</div>
@endforeach
</div>
@break
@case('time')
<input type="time"
id="field-{{$question->code}}"
name="{{$question->code}}"
class="form-control"
{{$question->required == 'yes' ? 'required' : ''}}
value="{{isset($question->value) ? $question->value : ''}}">
@break
@endswitch
</div>
@endforeach
@if((!isset($form->is_approval) || $form->is_approval != 'yes'))
<div class="text-center d-grid mt-3">
<button class="btn btn-primary" type="submit" id="submit-btn"> Submit </button>
</div>
{{-- @else
<div class="alert alert-warning text-center mt-3">
You have already submitted this form for this month.
</div> --}}
@endif
</form>
@elseif($submissions[0]->workflow_status=='rejected')
@if(!request()->has('edit'))
<p class="text-center text-danger">
Your previous entry was rejected , please edit your previous entry by clicking edit button in view history
</p>
<script>
console.log("inside rej")
document.addEventListener("DOMContentLoaded", function () {
document.getElementById('report-form').style.display = 'none';
});
</script>
@endif
<form method="POST" action="/form/submit" id="report-form" enctype="multipart/form-data">
<input type="hidden" name="form_id" value="{{$form_id}}">
<input type="hidden" name="user_id" value="{{$form->user_id}}">
@csrf
@if($id)
<input type="hidden" name="id" value="{{$id}}">
@endif
{{-- TM Contact: common field, outside doctor wrappers --}}
<div class="col-md-12 mb-2">
<label class="form-label">TM Contact Number <span class="text-danger">*</span></label>
<input type="tel" id="field-tm_contact" name="tm_contact" class="form-control"
value="{{ $submissions[0]->formdata->tm_contact ?? '' }}">
</div>
{{-- Manager select if applicable --}}
@if(isset($form->manager_can_submit) && $form->manager_can_submit == true)
<div class="col-md-12 mb-2">
<label for="field-user_id" class="form-label"> Select User / Territory <span class="text-danger">*</span> </label>
<select class="form-control" id="field-user_id" name="user_id" required>
<option value=""> -- Select -- </option>
@foreach($form->users as $option)
<option value="{{$option->value}}" hierarchy="{{$option->hierarchy_id}}"
{{isset($question->value) && $question->value == $option->value ? 'selected':''}}>
{{$option->display}}
</option>
@endforeach
</select>
<input type="hidden" id="field-hierarchy_id" name="hierarchy_id" value="">
</div>
@endif
{{-- Doctor Wrappers --}}
@for($i = 1; $i <= 3; $i++)
<div class="doctor-wrapper mb-4 p-2 border" data-index="{{$i}}">
<h5>Doctor {{$i}}</h5>
@foreach($questions as $question)
@php
$fieldName = $question->code;
if($i > 1){
$fieldName = $question->code . '_' . $i;
}
// Special case: first wrapper contact_id is stored as cont_id in formdata
$lookupName = $fieldName;
if($i == 1 && $question->code == 'contact_id'){
$lookupName = 'cont_id';
}
// Skip tm_contact because it's outside
if($question->code == 'tm_contact') continue;
$value = isset($submissions[0]->formdata->{$lookupName})
? $submissions[0]->formdata->{$lookupName}
: '';
@endphp
<div class="col-md-12 mb-2">
<label class="form-label">{{$question->question}}</label>
@switch($question->type)
@case('text')
@case('email')
@case('tel')
@case('date')
@case('time')
@case('number')
<input type="{{$question->type}}"
id="field-{{$fieldName}}"
name="{{$fieldName}}"
class="form-control"
value="{{$value}}">
@break
@case('textarea')
<textarea id="field-{{$fieldName}}"
name="{{$fieldName}}"
class="form-control">{{$value}}</textarea>
@break
@case('dropdown')
<select id="field-{{$fieldName}}" name="{{$fieldName}}" class="form-control">
<option value="">-- Select --</option>
@foreach ($question->options as $option)
@php
$optionValue = $option->value; // default ID
if($i > 1 && $question->code == 'contact_id') {
$optionValue = $option->display; // use name for wrapper 2 & 3
}
@endphp
<option value="{{ $optionValue }}"
{{ $value == $optionValue ? 'selected' : '' }}
legacy_code="{{ $option->contact->legacy_code ?? '' }}"
speciality="{{ $option->contact->speciality ?? '' }}">
{{$option->display}}
</option>
@endforeach
</select>
@break
@endswitch
</div>
@endforeach
</div>
@endfor
{{-- Submit button --}}
{{-- @if(!$alreadySubmitted && (!isset($form->is_approval) || $form->is_approval != 'yes')) --}}
<div class="text-center d-grid mt-3">
<button class="btn btn-primary" type="submit" id="submit-btn"> Submit </button>
</div>
{{-- @endif --}}
</form>
@else
<div class="alert alert-warning text-center mt-3">
You have already submitted this forms
</div>
@endif
</div> <!-- end card-body -->
</div>
<!-- end card -->
<!-- end row -->
</div> <!-- end col -->
</div>
<!-- end row -->
</div>
<!-- end container -->
</div>
<!-- end page -->
<style type="text/css">
#pageloader {
background: rgba( 255, 255, 255, 0.8 );
display: none;
height: 100%;
position: fixed;
width: 100%;
z-index: 9999;
}
#pageloader img {
left: 50%;
margin-left: -32px;
margin-top: -32px;
position: absolute;
top: 50%;
}
</style>
@include('layouts.shared/footer-script')
<script src="{{asset('assets/libs/sweetalert2/sweetalert2.min.js')}}"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#field-user_id').change(function(){
let hierarchy = $('option:selected', this).attr('hierarchy');
$('#field-hierarchy_id').val(hierarchy)
event.preventDefault();
$("#pageloader").fadeIn();
$.ajax({
type: "GET",
url: '/form/getdoctorlist?partition={{$form->partition}}&hierarchy='+hierarchy,
processData: false,
contentType: false,
success: function( data ) {
$("#pageloader").fadeOut();
$('#field-contact_id').html('')
$('#field-contact_id').append($("<option></option>").attr("value",'').text('-- Select --'));
for (let itm of data) {
$('#field-contact_id').append($("<option></option>").attr("value",itm.value).text(itm.display).attr("legacy_code", itm.contact.legacy_code).attr('speciality',itm.contact.speciality));
}
$('#field-contact_id').change(function() {
$('#field-legacy_code').val($('option:selected', this).attr('legacy_code'))
})
$('#field-contact_id').change(function() {
$('#field-speciality').val($('option:selected', this).attr('speciality'))
})
},
});
console.log(hierarchy)
})
// $('#field-contact_id').change(function() {
// $('#field-speciality').val($('option:selected', this).attr('speciality'))
// })
// $('#field-contact_id').change(function() {
// $('#field-legacy_code').val($('option:selected', this).attr('legacy_code'))
// })
// $('#field-legacy_code,#field-speciality,#field-current_value_total,#field-expecteed_value_total').attr('readonly',true);
$('#field-other_doctor_name,#field-other_speciality,#field-other_legacy_code').prop({"required":false});
$('#field-other_doctor_name,#field-other_speciality,#field-other_legacy_code').parent().hide();
$('#field-contact_id').on('change',function(){
let dropDown=$('#field-contact_id').val();
if(dropDown==='others'){
$('#field-other_doctor_name,#field-other_speciality,#field-other_legacy_code').parent().show();
$('#field-other_doctor_name,#field-other_speciality,#field-other_legacy_code').prop({"required":true});
$('#field-speciality,#field-legacy_code').parent().hide();
$('#field-speciality,#field-legacy_code').prop({"required":false});
}
else{
$('#field-other_doctor_name,#field-other_speciality,#field-other_legacy_code').parent().hide();
$('#field-other_doctor_name,#field-other_speciality,#field-other_legacy_code').prop({"required":false});
$('#field-speciality,#field-legacy_code').parent().show();
$('#field-speciality,#field-legacy_code').prop({"required":true});
}
})
$('#field-month').val('August');
$('#field-month').css({'pointer-events': 'none','background-color': '#e9ecef'}).attr('tabindex', '-1');
// $('#field-contact_id').append('<option value="others">Others</option>');
$('#field-current_value_kid_tab,#field-current_value_kid_syrup').on('input', function() {
var total=(
(parseInt($('#field-current_value_kid_tab').val())||0)+
(parseInt($('#field-current_value_kid_syrup').val())||0)
);
$('#field-current_value_total').val(total)
})
$('#field-expected_value_kid_tab,#field-expected_value_kid_syrup').on('input', function() {
var total=(
(parseInt($('#field-expected_value_kid_tab').val())||0)+
(parseInt($('#field-expected_value_kid_syrup').val())||0)
);
$('#field-expecteed_value_total').val(total)
})
$('#field-tm_contact').on('input', function () {
let mobile = $(this).val();
// Allow only digits
mobile = mobile.replace(/\D/g, '');
// Limit to 10 digits
if (mobile.length > 10) {
mobile = mobile.slice(0, 10);
}
$(this).val(mobile);
});
$('#report-form').on('submit', function(event){
event.preventDefault();
let mobile = $('#field-tm_contact').val();
// 🚫 Block submission if invalid
if (mobile.length !== 10) {
Swal.fire({
icon: 'error',
title: 'Invalid Mobile Number',
text: 'Please enter a valid 10-digit mobile number'
});
return;
}
let totalWrappers = $('.doctor-wrapper').length;
if (totalWrappers < 3) {
event.preventDefault();
Swal.fire({
icon: 'error',
title: 'Incomplete Form',
text: 'Please add all 3 doctors before submitting.'
});
return false;
}
const formData = new FormData($('#report-form')[0]);
// Log form data to console
for (let [key, value] of formData.entries()) {
console.log(key, value);
}
$("#pageloader").fadeIn();
$.ajax({
type: "POST",
url: '/form/ajaxsubmit',
data: new FormData($('#report-form')[0]),
processData: false,
contentType: false,
success: function( data ) {
$("#pageloader").fadeOut();
if(data.status == 'success') {
Swal.fire({
title: 'Great!',
text: 'Your data is successfully submitted!',
icon: 'success'
}).then(() => {
location.reload(); // 🔥 page refresh here
});
$('#report-form').trigger("reset");
} else {
Swal.fire({
icon: 'error',
title: 'Data not submitted',
text: 'Something went wrong, please try again after some time!'
})
}
},
});
});
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
var plandateField = document.getElementById('field-record_date');
//plandateField.setAttribute('max', today);
});
</script>
@if(!$id)
<script>
$(document).ready(function () {
let maxSections = 3;
// 👉 Wrap from Doctor Name till end
let $start = $('#field-month').closest('.col-md-12');
let $allFields = $start.nextAll().addBack();
$allFields.wrapAll('<div class="doctor-wrapper" data-index="1"></div>'); // first wrapper index = 1
// 👉 Function to set indexed names
function setIndexedNames($wrapper, index) {
$wrapper.find('input, select, textarea').each(function () {
let name = $(this).attr('name');
if (!name || name === '_token') return;
if (index === 1) {
// first wrapper has no suffix
name = name.replace(/_\d+$/, '');
} else {
// other wrappers: add _2, _3, ...
name = name.replace(/_\d+$/, '');
name = name + '_' + index;
}
$(this).attr('name', name);
});
}
// 👉 Set first wrapper names
setIndexedNames($('.doctor-wrapper').first(), 1);
// 👉 Style wrapper
$('.doctor-wrapper').css({
'border': '2px solid #cce5ff',
'padding': '15px',
'margin-bottom': '15px',
'border-radius': '8px',
'background-color': '#f4faff',
'position': 'relative'
});
// 👉 Move submit button outside wrapper
let $submitBtn = $('#submit-btn').closest('.text-center');
$('.doctor-wrapper').last().after($submitBtn);
$('.doctor-wrapper .text-center').remove();
// 👉 Make readonly initially
$('[id^=field-legacy_code], [id^=field-speciality], [id^=field-current_value_total], [id^=field-expecteed_value_total]')
.prop('readonly', true)
.css('background-color', '#e9ecef');
// 👉 Create wrappers 2 and 3
// 👉 Create wrappers 2 and 3
for (let i = 2; i <= 3; i++) { // numbering starts at 2
let $clone = $('.doctor-wrapper').first().clone();
$clone.attr('data-index', i);
// 👉 Set indexed names
setIndexedNames($clone, i);
// 👉 Reset values + unique IDs
$clone.find('input, select, textarea').each(function () {
let id = $(this).attr('id');
if (id) $(this).attr('id', id + '_' + i);
if ($(this).is('input')) $(this).val($(this).attr('type') === 'number' ? 0 : '');
else $(this).val('');
});
// 👉 Convert <select> option values to names
$clone.find('select').each(function() {
$(this).find('option').each(function() {
if ($(this).val() !== '') { // skip empty placeholder
$(this).val($(this).text().trim()); // set value = option text
}
});
});
// 👉 Apply readonly
$clone.find('[id^=field-legacy_code], [id^=field-speciality], [id^=field-current_value_total], [id^=field-expecteed_value_total]')
.prop('readonly', true)
.css('background-color', '#e9ecef');
// 👉 Append clone
$clone.insertAfter($('.doctor-wrapper').last());
$('#field-month_2').val('August');
$('#field-month_3').val('August');
$('#field-month_2, #field-month_3').css({'pointer-events': 'none','background-color': '#e9ecef'}).attr('tabindex', '-1');
}
// 👉 Remove add button completely
$('#add-more').remove();
});
// 👉 Prevent manual typing
$(document).on('keydown paste', '[id^=field-current_value_total], [id^=field-expecteed_value_total], [id^=field-legacy_code], [id^=field-speciality]', function(e) {
e.preventDefault();
});
// 👉 Doctor change → autofill
$(document).on('change', '[id^=field-contact_id]', function () {
let $wrapper = $(this).closest('.doctor-wrapper');
let selected = $('option:selected', this);
$wrapper.find('[id^=field-speciality]').val(selected.attr('speciality') || '');
$wrapper.find('[id^=field-legacy_code]').val(selected.attr('legacy_code') || '');
});
// 👉 CURRENT VALUE calculation
$(document).on('input', '[id^=field-current_value_kid_tab], [id^=field-current_value_kid_syrup]', function () {
let $wrapper = $(this).closest('.doctor-wrapper');
let tab = parseInt($wrapper.find('[id^=field-current_value_kid_tab]').val()) || 0;
let syrup = parseInt($wrapper.find('[id^=field-current_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-current_value_total]').val(tab + syrup).prop('readonly', true);
});
// 👉 EXPECTED VALUE calculation
$(document).on('input', '[id^=field-expected_value_kid_tab], [id^=field-expected_value_kid_syrup]', function () {
let $wrapper = $(this).closest('.doctor-wrapper');
let tab = parseInt($wrapper.find('[id^=field-expected_value_kid_tab]').val()) || 0;
let syrup = parseInt($wrapper.find('[id^=field-expected_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-expecteed_value_total]').val(tab + syrup).prop('readonly', true);
});
</script>
{{-- <script>
// 👉 Prevent duplicate doctor selection
$(document).on('change', '[id^=field-contact_id]', function () {
let selectedValues = [];
let isDuplicate = false;
$('[id^=field-contact_id]').each(function () {
let val = $(this).val();
if (val) {
if (selectedValues.includes(val)) {
isDuplicate = true;
return false; // break loop
}
selectedValues.push(val);
}
});
if (isDuplicate) {
Swal.fire({
icon: 'error',
title: 'Duplicate Doctor',
text: 'You cannot select the same doctor multiple times.'
});
// reset current dropdown
$(this).val('');
// clear autofill fields in this wrapper
let $wrapper = $(this).closest('.doctor-wrapper');
$wrapper.find('[id^=field-speciality]').val('');
$wrapper.find('[id^=field-legacy_code]').val('');
}
});
</script> --}}
<script>
// =========================================================
// New CODE: DUPLICATE DOCTOR CHECK & '(Already Added)' TEXT
// =========================================================
// 1. Function: All dropdowns options dynamic update
function updateDoctorDropdownOptions() {
let selectedDoctors = [];
// Currently selected doctors shodha
$('[id^=field-contact_id]').each(function () {
let val = $(this).val();
let text = $(this).find('option:selected').text().replace(' (Already Added)', '').trim();
if (val && text !== '-- Select --') {
selectedDoctors.push({ val: val, text: text });
}
});
// Update status in every wrappers dropdown
$('[id^=field-contact_id]').each(function () {
let $currentSelect = $(this);
let currentVal = $currentSelect.val();
$currentSelect.find('option').each(function () {
let $opt = $(this);
let optVal = $opt.val();
let cleanText = $opt.text().replace(' (Already Added)', '').trim();
if (!optVal || optVal === '') return;
// Check in other wheter this doctor is selected in previous wrapper
let isSelectedElsewhere = selectedDoctors.some(d =>
(d.val === optVal || d.text === cleanText) && d.val !== currentVal
);
if (isSelectedElsewhere) {
$opt.text(cleanText + ' (Already Added)');
} else {
$opt.text(cleanText);
}
});
});
}
// 2. Change Event: Selection change after validate & update
$(document).on('change', '[id^=field-contact_id]', function () {
let currentSelect = $(this);
let currentWrapper = currentSelect.closest('.doctor-wrapper');
let selectedOption = currentSelect.find('option:selected');
let currentText = selectedOption.text();
if (currentText.includes('(Already Added)')) {
Swal.fire({
icon: 'error',
title: 'Duplicate Doctor',
text: 'Ha doctor aadhich dusrya wrapper madhye add kela aahe.'
});
currentSelect.val('');
currentWrapper.find('[id^=field-speciality]').val('');
currentWrapper.find('[id^=field-legacy_code]').val('');
}
// Update in eevry dropdown
updateDoctorDropdownOptions();
});
$(document).ready(function() {
updateDoctorDropdownOptions();
});
</script>
@endif
@if($id)
<script>
$(document).ready(function () {
console.log("EDIT MODE START");
// ✅ Get backend formdata
let formData = @json(isset($data[0]->formdata) ? $data[0]->formdata : []);
console.log("FORM DATA:", formData);
// ✅ Style wrappers
$('.doctor-wrapper').css({
border: '2px solid #cce5ff',
padding: '15px',
marginBottom: '15px',
borderRadius: '8px',
backgroundColor: '#f4faff'
});
// ✅ Make readonly
$('[id^=field-legacy_code], [id^=field-speciality], [id^=field-current_value_total], [id^=field-expecteed_value_total]')
.prop('readonly', true)
.css('background-color', '#e9ecef');
// 🔥 FIX FIRST WRAPPER VALUE (MAIN FIX)
$('.doctor-wrapper').each(function (index) {
let $wrapper = $(this);
let $doctor = $wrapper.find('[id^=field-contact_id]');
let val = '';
if (index === 0) {
val = formData.cont_id || ''; // ✅ correct key
} else if (index === 1) {
val = formData.contact_id_2 || '';
} else if (index === 2) {
val = formData.contact_id_3 || '';
}
console.log('Setting wrapper', index + 1, 'to value:', val);
if (val) {
$doctor.val(val); // ✅ just set value, no trigger
// ✅ manually autofill without triggering change
let selected = $doctor.find('option[value="' + val + '"]');
console.log('Matched option text:', selected.text());
$wrapper.find('[id^=field-speciality]').val(selected.attr('speciality') || '');
$wrapper.find('[id^=field-legacy_code]').val(selected.attr('legacy_code') || '');
}
// ✅ Always recalculate totals
let tab = parseInt($wrapper.find('[id^=field-current_value_kid_tab]').val()) || 0;
let syrup = parseInt($wrapper.find('[id^=field-current_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-current_value_total]').val(tab + syrup);
let etab = parseInt($wrapper.find('[id^=field-expected_value_kid_tab]').val()) || 0;
let esyrup = parseInt($wrapper.find('[id^=field-expected_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-expecteed_value_total]').val(etab + esyrup);
});
// ✅ AUTOLOAD (after fix)
$('.doctor-wrapper').each(function(index) {
let $wrapper = $(this);
let $doctor = $wrapper.find('[id^=field-contact_id]');
// pick correct key from formData
let val = '';
if(index === 0) val = formData.cont_id || '';
else if(index === 1) val = formData.contact_id_2 || '';
else if(index === 2) val = formData.contact_id_3 || '';
if(val) {
$doctor.val(val);
// For Doctor 1 (ID-based), find option by value (ID)
// For Doctor 2 & 3 (name-based), find option by value (name)
let selected = $doctor.find('option[value="' + val + '"]');
$wrapper.find('[id^=field-speciality]').val(selected.attr('speciality') || '');
$wrapper.find('[id^=field-legacy_code]').val(selected.attr('legacy_code') || '');
}
// recalc totals
let tab = parseInt($wrapper.find('[id^=field-current_value_kid_tab]').val()) || 0;
let syrup = parseInt($wrapper.find('[id^=field-current_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-current_value_total]').val(tab + syrup);
let etab = parseInt($wrapper.find('[id^=field-expected_value_kid_tab]').val()) || 0;
let esyrup = parseInt($wrapper.find('[id^=field-expected_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-expecteed_value_total]').val(etab + esyrup);
});
});
// ✅ Doctor change → autofill
$(document).on('change', '[id^=field-contact_id]', function () {
console.log('--- CHANGE TRIGGERED ---');
let $wrapper = $(this).closest('.doctor-wrapper');
let val = $(this).val();
console.log('Changed VALUE:', val);
let selected = $(this).find('option[value="' + val + '"]');
console.log('Selected attrs:', {
speciality: selected.attr('speciality'),
legacy_code: selected.attr('legacy_code')
});
$wrapper.find('[id^=field-speciality]')
.val(selected.attr('speciality') || '');
$wrapper.find('[id^=field-legacy_code]')
.val(selected.attr('legacy_code') || '');
});
// ✅ CURRENT VALUE calculation
$(document).on('input', '[id^=field-current_value_kid_tab], [id^=field-current_value_kid_syrup]', function () {
let $wrapper = $(this).closest('.doctor-wrapper');
let tab = parseInt($wrapper.find('[id^=field-current_value_kid_tab]').val()) || 0;
let syrup = parseInt($wrapper.find('[id^=field-current_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-current_value_total]').val(tab + syrup);
});
// ✅ EXPECTED VALUE calculation
$(document).on('input', '[id^=field-expected_value_kid_tab], [id^=field-expected_value_kid_syrup]', function () {
let $wrapper = $(this).closest('.doctor-wrapper');
let tab = parseInt($wrapper.find('[id^=field-expected_value_kid_tab]').val()) || 0;
let syrup = parseInt($wrapper.find('[id^=field-expected_value_kid_syrup]').val()) || 0;
$wrapper.find('[id^=field-expecteed_value_total]').val(tab + syrup);
});
// ✅ Prevent duplicate doctor
$(document).on('change', '[id^=field-contact_id]', function () {
let selectedValues = [];
let isDuplicate = false;
$('[id^=field-contact_id]').each(function () {
let val = $(this).val();
if (val) {
if (selectedValues.includes(val)) {
isDuplicate = true;
return false;
}
selectedValues.push(val);
}
});
if (isDuplicate) {
Swal.fire({
icon: 'error',
title: 'Duplicate Doctor',
text: 'You cannot select the same doctor multiple times.'
});
let $wrapper = $(this).closest('.doctor-wrapper');
$(this).val('');
$wrapper.find('[id^=field-speciality]').val('');
$wrapper.find('[id^=field-legacy_code]').val('');
}
});
</script>
@endif
</body>
</html>