<?php 
include 'header.php';

require 'permission.php';
requireView('service-followup');

include('xcrud/xcrud.php');
$xcrud = Xcrud::get_instance();
echo Xcrud::load_css();
$bdd = new DB();

$followup_title='All';
if(isset($_GET['status']) && $_GET['status']=='pending'){
	$followup_title='All Pending';
}else if(isset($_GET['status']) && $_GET['status']=='today_pending'){
	$followup_title='Today Pending';
}else if(isset($_GET['status']) && $_GET['status']=='backdate_pending'){
	$followup_title='Backdate Pending';
}else if(isset($_GET['status']) && $_GET['status']=='today_taken'){
	$followup_title='Today Taken';
}
$service_type_rows = $bdd->getAll("SELECT id,name FROM service_type", []);
$time_slot_rows = $bdd->getAll("SELECT id,name FROM time_slot", []);
?>

<div class="content-wrapper">

	<section class="content-header"><div class="container-fluid"></div></section>

	<section class="content">
		<div class="container-fluid">
			<div class="col-lg-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Followup : <?php echo $followup_title;?></h3>
              </div>
              <div class="card-body">

                <?php
				$xcrud->table('service_followup');

				$xcrud->join('service_id','service','id');
				$xcrud->order_by('service.invoice_date','desc');
				$xcrud->order_by('service.id','asc');
				$xcrud->order_by('service_no','asc');
				
				/*if(isset($_GET['status']) && $_GET['status']=='appointment'){	
					$xcrud->where('appointment_date',$current_date);
				}
				if(isset($_GET['status']) && $_GET['status']=='pickup'){
					$xcrud->where('pickup_date',$current_date);
				}*/
				
				if(isset($_GET['status']) && $_GET['status']=='pending'){
					$xcrud->where("service_followup.followup_status='pending'");
					//$xcrud->where("NOT (service_followup.followup_status='taken' AND service_followup.remark='')");
				}else if(isset($_GET['status']) && $_GET['status']=='today_pending'){
					if(isset($_GET['type']) && $_GET['type']=='free'){
						$xcrud->where("(service_followup.followup_status='pending' AND service_no<4 AND service_followup.next_followup_date='$current_date')");
					}else if(isset($_GET['type']) && $_GET['type']=='paid'){
						$xcrud->where("(service_followup.followup_status='pending' AND service_no>3 AND service_followup.next_followup_date='$current_date')");
					} 
					
				}else if(isset($_GET['status']) && $_GET['status']=='backdate_pending'){
					$xcrud->where("(service_followup.followup_status='pending' AND service_followup.next_followup_date<'$current_date')");
				}else if(isset($_GET['status']) && $_GET['status']=='today_taken'){
					$xcrud->where("(service_followup.followup_status='taken' AND service_followup.next_followup_date='$current_date')");
				}
				
				$xcrud->where('service.status=','active');
				

				$xcrud->relation('service.product_id','products','id','name');
				$xcrud->relation('service.city_id','city','id','name');
				$xcrud->relation('user_id','users','id','username');
				$xcrud->relation('service.institute_id','institute','id','name');
				
				$xcrud->columns('service.customer_name,service.mobile_no,service.chassis_no,service.registration_no,service.city_id,service.institute_id,service.product_id,service.invoice_date,last_followup_date,next_followup_date,service_type,service_no,service_date,service_status,remark,appointment,appointment_date,pickup,pickup_date,user_id,followup_status,service_done_date',false);

				$xcrud->fields('service.customer_name,service.mobile_no',false,'Serives');
				$xcrud->fields('last_followup_date,next_followup_date,service_type,service_no,service_date,service_status,service_done_date,remark,appointment,appointment_date,pickup,pickup_date,user_id,followup_status',false,'Followup');

				$xcrud->label('service.service_id','Service Id');
				$xcrud->label('user_id','User');
				$xcrud->label('service.institute_id','Institute');
				$xcrud->label('service.product_id','Product');
				$xcrud->label('service.city_id','City');
				
				$xcrud->change_type('appointment','select','Yes',',Yes,No');
				$xcrud->change_type('pickup','select','Yes',',Yes,No');
				$xcrud->change_type('service_type','select','Free Service - 3W','Free Service - 3W,Second free service-3W,Third free service-3W,Paid Periodic Service');
				$xcrud->change_type('service_status','select','pending','pending,service_done,appointment,pickup,close');
				$xcrud->change_type('followup_status','select','pending','pending,taken');
				
				
				$values=array($_SESSION['user_id']);
				$calling_type_row = $bdd->getOne("SELECT calling_type from users where id=?",$values);

				$xcrud->create_action('call', 'service_call_action');

				$xcrud->button('#', 'Call', 'fas fa-phone', 'xcrud-action', 
					array(  
						'data-task' => 'action',
						'data-action' => 'call',
						'data-mobile'=>'{service.mobile_no}',
						'data-secondary_ph_no'=>'{service.secondary_ph_no}',
						'data-service_id'=>'{service.id}',
						'data-service_status'=>'{followup_status}',
						'data-nfd'=>'{next_followup_date}',
						'data-service_type'=>'{service_type}',
						'data-service_no'=>'{service_no}',
						'data-user_id'=>$_SESSION['user_id'],
						'data-calling_type'=>$calling_type_row['calling_type'],
						'data-primary' => '{id}',
						'data-toggle'=>'modal',
						'data-target'=>'#service_update_followup')
				);
				
				//for single row data layout
				$xcrud->column_width('service.customer_name','300px');
				$xcrud->column_width('service.product_id,service.institute_id','300px');

				$xcrud->unset_title();
				$xcrud->unset_add();
				if($_SESSION['user_type']!='admin'){
					$xcrud->unset_remove();
				}
				echo $xcrud->render();
			  ?>

                
              </div>
            </div>

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

</div>
	  
<div class="modal fade" id="service_update_followup">
        <div class="modal-dialog modal-dialog-scrollable">
          <div class="modal-content">
            <div class="modal-header">
              <h6 class="modal-title" style="font-weight: bold;">Service Followup Detail</h6>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>

            <!-- MODAL BODY: pure HTML form (no PHP) -->
            <div class="modal-body">
                <form id="service_followup_form" class="form-horizontal">
                    <!-- Hidden Inputs -->
                    <input type="hidden" id="hidden_user_id" name="hidden_user_id">
                    <input type="hidden" id="hidden_service_id" name="hidden_service_id">
                    <input type="hidden" id="hidden_lfd" name="hidden_lfd">
                    <input type="hidden" id="hidden_service_followup_id" name="hidden_service_followup_id">

                    <div class="row">
						<div class="col-sm-12">
						  <div class="form-group">
							<label>Remark</label>
							<textarea id="service_remark" name="remark" class="form-control"></textarea>
						  </div>
						</div>
						
					</div>

                    <div class="row">
						<div class="col-sm-3">
						  <div class="form-group">
							<label>Type</label>
							<input type="text" id="service_type" name="service_type" readonly class="form-control">
						  </div>
						</div>
						<div class="col-sm-2">
						  <div class="form-group">
							<label>Service No</label>
							<input type="text" id="service_no" name="service_no" size="3" readonly class="form-control">
						  </div>
						</div>
						<div class="col-sm-3">
						  <div class="form-group">
							<label>Mobile No </label>
							<input type="text" id="primary_ph_no" name="primary_ph_no" readonly class="form-control">
							<label></label>
						  </div>
						</div>
						<div class="col-sm-3">
						  <div class="form-group">
							<label><input type="checkbox" id="change_mobile_no"> Change</label>
							<input type="text" id="secondary_ph_no" name="secondary_ph_no" class="form-control" readonly>
							<label></label>
						  </div>
						</div>
					</div>

					
                    <div class="row">
						<div class="col-sm-6">
						  <!-- text input -->
						  <div class="form-group">
							<label>Next Followup Date</label>
							<select name="nfd" id="nfd" class="form-control">
                                <option value="-1">Select Day</option>
                                <option value="0">Today</option>
                                <option value="1">Next Day</option>
                                <option value="3">3 days</option>
                                <option value="7">Next Week</option>
                                <option value="30">Next Month</option>
                            </select>
						  </div>
						</div>
						<div class="col-sm-6">
						  <div class="form-group">
							<label>OR</label>
							<input type="date" name="nfd1" id="nfd1" class="form-control">
						  </div>
						</div>
					</div>
					
                    
					<div class="row">
						<div class="col-sm-6">
						  <div class="form-group">
							<label>Status</label>
							<select name="status" id="status" class="form-control">
                                <option value="pending">Pending</option>
								<option value="lost">Lost</option>
                                <!--<option value="service_done">Service Done</option>-->
                                <!--<option value="appointment">Appointment</option>
                                <option value="pickup">Pickup</option>
                                <option value="close">Close</option>
                                -->
                            </select>
						  </div>
						</div>
						
						<div class="col-sm-6">
						  <div class="form-group">
							<label>Status Date</label>
							<input type="date" name="service_status_date" id="service_status_date" class="form-control">
						  </div>
						</div>
					</div>
					
					<div class="row" id="lost_reason_row" style="display:none">
						<div class="col-sm-6">
						  <div class="form-group">
							<label>Reason</label>
							<select name="lost_reason_master" id="lost_reason_master" class="form-control">
								<?php
								$values=array();
								$lost_reason_rows = $bdd->getAll("SELECT id,name FROM lost_reason",$values);
								foreach($lost_reason_rows as $lost_reason_rows){
									echo "<option value='{$lost_reason_rows['id']}'>{$lost_reason_rows['name']}</option>";
								}
								?>
                                
                            </select>
						  </div>
						</div>
					</div>
					
					<!--<div class="row" id="service_type_row" style="display:none">
						<div class="col-sm-6">
						  <div class="form-group">
							<label>Status</label>
							<select name="service_type_master" id="service_type_master" class="form-control">
								<?php
								/*$values=array();
								$service_type_master_rows = $bdd->getAll("SELECT id,name FROM service_type",$values);
								foreach($service_type_master_rows as $service_type_master_row){
									echo "<option value='{$service_type_master_row['id']}'>{$service_type_master_row['name']}</option>";
								}*/
								?>
                                
                            </select>
						  </div>
						</div>
					</div>-->

                    <div class="row">
						<div class="col-sm-3">
							<button type="button" class="btn btn-block bg-gradient-success" onclick="openAppointmentModal('appointment')" data-toggle="modal" data-target="#appointment_modal">Appointment</button>
						</div>
                        
						<!--<div class="col-sm-3">
							<button type="button" class="btn btn-block bg-gradient-primary" onclick="openHistory('call')">Call</button>
						</div>
						<div class="col-sm-3">
							<button type="button" class="btn btn-block bg-gradient-secondary" onclick="openHistory('service')">Service</button>
						</div>
						
						<div class="col-sm-3">
                            <button type="button" class="btn btn-block bg-gradient-info" onclick="openHistory('pickup')">Pickup</button>
                        </div>-->
                    </div>
					
                    
                </form>
            </div>

            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <!-- Save calls update_service_followup() -->
              <button type="button" class="btn btn-primary" id="modal_save_btn" onclick="update_service_followup()">Save</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>

<!-- Appointment modal -->

<div class="modal fade" id="appointment_modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title" style="font-weight: bold;">Appointment</h6>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
        <form id="appointment_form">
			<div style="display:none"><input type="text" id="appointment_user_id" name="appointment_user_id">
			<input type="text" id="appointment_mobile_no" name="appointment_mobile_no">
			<input type="text" id="appointment_product_id" name="appointment_product_id">
			<input type="text" id="appointment_vehicle_no" name="appointment_vehicle_no">
			<input type="text" id="appointment_chassis_no" name="appointment_chassis_no"></div>
			
          <div class="row">
            <!-- Service Type Dropdown -->
            <div class="col-md-6">
              <div class="form-group">
                <label>Service Type</label>
                <select class="form-control" name="appointment_service_type" required>
                  <option value="">Select Service</option>
                  <?php foreach ($service_type_rows as $row) { ?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                  <?php } ?>
                </select>
              </div>
            </div>

            <!-- Date Picker -->
            <div class="col-md-6">
              <div class="form-group">
                <label>Date</label>
                <input type="date" name="appointment_date" class="form-control" required>
              </div>
            </div>
          </div>

          <div class="row">
            <!-- Time Slot Dropdown -->
            <div class="col-md-6">
              <div class="form-group">
                <label>Time Slot</label>
                <select class="form-control" name="appointment_time_slot" required>
                  <option value="">Select Time</option>
                  <?php foreach ($time_slot_rows as $row) { ?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                  <?php } ?>
                </select>
              </div>
            </div>
          </div>
        
      </div>

      <div class="modal-footer justify-content-between">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" id="save_appointment_btn">Save</button>
		</form>
      </div>
    </div>
  </div>
</div>
<?php
$bdd->disconnect();
include 'footer.php';
?>
<?php
echo Xcrud::load_js();
?>


<script>
const loader = document.getElementById("loader-overlay");

function safeXcrudValue(v) {
  if (!v || v === 'null' || v.indexOf('{') !== -1) return '';
  return v;
}


$('#appointment_form').on('submit', function (e) {
    e.preventDefault();
	if(loader) loader.style.display = "flex";

    // Convert form fields to an object: {fieldName: fieldValue, ...}
    var formObj = {};
    $.each($(this).serializeArray(), function (_, item) {
        // if multiple inputs share same name, keep last value (simple case)
        formObj[item.name] = item.value;
    });

    // Add your action
    formObj.action = 'saveAppointment';

    $.ajax({
        url: 'ajax_call.php',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: JSON.stringify(formObj),
        success: function (res) {
			console.log(res);
			if(res.status=='success')
				alert('Appointment saved successfully');
			else
				alert('Something went wrong contact developer');
			closeModal('appointment_modal');
        },
        error: function (xhr) {
            console.error(xhr.responseText);
            alert('Error saving appointment');
        },
		complete: function () {
			if(loader) loader.style.display = "none";
		}
    });
});


function openAppointmentModal(){
	const service_id = document.getElementById("hidden_service_id").value;
	const user_id = document.getElementById("appointment_user_id");
	const mobile_no =	document.getElementById("appointment_mobile_no");
	const product_id = document.getElementById("appointment_product_id");
	const vehicle_no = document.getElementById("appointment_vehicle_no");
	const chassis_no = document.getElementById("appointment_chassis_no");
	
	
	
	user_id.value = "";
	mobile_no.value =	"";
	product_id.value = "";
	vehicle_no.value = "";
	chassis_no.value = "";
	
	if(loader) loader.style.display = "flex";
				
	fetch('ajax_call.php', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		// 3. Send data as JSON string
		body: JSON.stringify({ 
			action: 'getAppointmentUserData', 
			service_id: service_id 
		})
	})
	.then(res => res.text()) // Get text first to safely debug errors
	.then(text => {
		let data;
		try {
			data = JSON.parse(text);
		} catch (e) {
			console.error('Invalid JSON from server:', text);
			return;
		}

		if (data.status === 'success') {
			//console.log(data.result); 
			
			if (data.result) {
				user_id.value = data.result.id;
				mobile_no.value = data.result.mobile_no;
				product_id.value = data.result.product_id;
				vehicle_no.value = data.result.registration_no;
				chassis_no.value = data.result.chassis_no;
			}else{
				console.log('No data found');
			}
		} else {
			alert(data.message || 'No data found');
		}
	}).catch(error => console.error('Fetch error:', error))
	.finally(() => {
        // 2. HIDE LOADER (Runs on both success and error)
        if(loader) loader.style.display = "none";
    }); 
}

var ACTIVE_XCRUD_CONTAINER = null;

window.addEventListener('DOMContentLoaded', () => {
  document.getElementById('service_status_date').focus();
  document.getElementById('service_status_date').blur();
});
  
//toggel service_type_row
/*document.getElementById("status").addEventListener("change", function () {
    var service_type_row = document.getElementById("service_type_row");

    if (this.value === "service_done") {
        service_type_row.style.display = "block";
    } else {
        service_type_row.style.display = "none";
    }
});*/

//toggel service_type_row
document.getElementById("status").addEventListener("change", function () {
    var lost_reason_row = document.getElementById("lost_reason_row");

    if (this.value === "lost") {
        lost_reason_row.style.display = "block";
    } else {
        lost_reason_row.style.display = "none";
    }
});


(function(){
  // delegated handler for the xcrud "Call" button
  document.addEventListener('click', function(e){
    var el = e.target.closest('.xcrud-action[data-action="call"]');
    if (!el) return;

    e.preventDefault();
    e.stopPropagation();

    // find nearest xcrud container for this row (xCRUD multi-instance support)
    var container = el.closest('.xcrud-ajax') || document.querySelector('.xcrud-ajax');
    if (!container) {
      console.warn('xcrud container not found; falling back to global .xcrud-ajax');
      container = document.querySelector('.xcrud-ajax');
      if (!container) return;
    }

    // gather parameters
    var primary = el.getAttribute('data-primary') || el.dataset.primary || '';
    var action  = el.getAttribute('data-action')  || el.dataset.action  || 'call';

    // optional extras you passed in data-*
    var extras = {};
    ['service_id','user_id','mobile','secondary_ph_no','nfd','service_type','service_no','calling_type','service_status'].forEach(function(k){
      var v = el.getAttribute('data-' + k) || el.dataset[k];
      if (typeof v !== 'undefined' && v !== null) extras[k] = v;
    });
	
	extras.secondary_ph_no = safeXcrudValue(extras.secondary_ph_no);



    // prepare the xCRUD request payload using xCRUD helper
    var payload = { task: 'action', action: action, primary: primary };
    for (var key in extras) if (extras.hasOwnProperty(key)) payload[key] = extras[key];

    // call xCRUD request: this will run your create_action() callback server-side
    if (typeof Xcrud !== 'undefined' && typeof Xcrud.request === 'function') {
	  var data = Xcrud.list_data(container, payload);
	  Xcrud.request(container, data);

	  container._last_xcrud_action = payload;

	  // ✅ THIS LINE WAS MISSING
	  ACTIVE_XCRUD_CONTAINER = container;
	}

    // Populate modal form fields from extras BEFORE showing modal
    populateFollowupModal(primary, extras);
	
	console.log(extras.mobile+","+primary);

    // show modal
    var modal = document.getElementById('service_update_followup');
    if (modal) {
      if (window.jQuery && jQuery(modal).modal) jQuery(modal).modal('show');
      else if (typeof bootstrap !== 'undefined' && bootstrap.Modal) new bootstrap.Modal(modal).show();
    }
  }, true);


  // Listen for xCRUD ajax completion — helpful to see server response and to act only after the callback executed.
  jQuery(document).on('xcrudafterrequest', function(event, container){
    try {
      if (typeof Xcrud !== 'undefined' && Xcrud.current_task === 'action') {
        console.log('xcrudafterrequest (action) fired for container:', container);
        var payload = (container && container._last_xcrud_action) ? container._last_xcrud_action : null;
        console.log('last xcrud action payload:', payload);
        // Optionally display/replace content in modal body from server response
        // var modal = document.getElementById('service_update_followup');
        // if(modal) modal.querySelector('.modal-body').innerHTML = '<p>Action executed</p>';
      }
    } catch (err) {
      console.warn('Error handling xcrudafterrequest:', err);
    }
  });


  // populate modal fields (call before showing modal)
  function populateFollowupModal(primary, extras){
    // extras: service_id,user_id,mobile,nfd,service_type,service_no,calling_type,service_status
    try {
		
      document.getElementById("hidden_user_id").value = extras.user_id || "";
      document.getElementById("hidden_service_id").value = extras.service_id || "";
      document.getElementById("hidden_lfd").value = extras.nfd || "";
      document.getElementById("hidden_service_followup_id").value = primary || "";

      document.getElementById("service_type").value = extras.service_type || "";
      document.getElementById("service_no").value = extras.service_no || "";

      document.getElementById("primary_ph_no").value = extras.mobile || "";
	  document.getElementById("secondary_ph_no").value = extras.secondary_ph_no || "";

      // default status from extras.service_status if available
      if (extras.service_status) document.getElementById("status").value = extras.service_status;
      else document.getElementById("status").value = "pending";

      // clear other inputs
      document.getElementById("service_remark").value = "";
      document.getElementById("nfd").value = "-1";
      document.getElementById("nfd1").value = "";
	  
	  const current_date = new Date().toISOString().split('T')[0];
      document.getElementById("service_status_date").value = current_date;

      // checkbox handlers to enable editing phone numbers
      var change_mobile_no = document.getElementById("change_mobile_no");
      //var c_sph = document.getElementById("c_sph_no");
      change_mobile_no.checked = false;
      //c_sph.checked = false;
      //document.getElementById("primary_ph_no").readOnly = true;
      document.getElementById("secondary_ph_no").readOnly = true;

      change_mobile_no.onchange = function(){ document.getElementById("secondary_ph_no").readOnly = !this.checked; };
      //c_sph.onchange = function(){ document.getElementById("secondary_ph_no").readOnly = !this.checked; };
	  
	  var lost_reason_row = document.getElementById("lost_reason_row");
		lost_reason_row.style.display = "none";

      // initialize datepickers if available (Bootstrap datepicker or jQuery UI)
      if (typeof jQuery !== 'undefined' && typeof jQuery.fn.datepicker === 'function') {
        jQuery('.date-picker').each(function(){
          jQuery(this).datepicker({format:'dd-mm-yyyy',autoclose:true});
        });
      } else if (typeof jQuery !== 'undefined' && typeof jQuery.fn.pickadate === 'function') {
        // fallback if using pickadate
        jQuery('.date-picker').pickadate();
      } else {
        // no datepicker plugin available — keep plain text input
      }

    } catch (err) {
      console.warn('populateFollowupModal error', err);
    }
  }

  // helper for opening history (calls your existing getServiceTypeHistory)
  window.openHistory = function(type){
    var sid = document.getElementById("hidden_service_id").value;
    if (typeof getServiceTypeHistory === 'function') getServiceTypeHistory(type, sid);
    else console.warn('getServiceTypeHistory not defined. Type:', type, 'service_id:', sid);
  };

  // Save handler: collects form values and posts to server
  // NOTE: Change the URL 'service_followup_update.php' to your real endpoint.
  window.update_service_followup = function () {
	  
	  if(loader) loader.style.display = "flex";

	if (!validateServiceFollowupForm()) {
		if(loader) loader.style.display = "none";
        return; // stop submission
    }
	
    var form = document.getElementById('service_followup_form');
    var formData = new FormData(form);
	
	var changeMobile = document.getElementById('change_mobile_no').checked ? 1 : 0;
	formData.append('change_mobile_no', changeMobile);

    formData.append('service_followup_update', '1');
	
	/*for (let [key, value] of formData.entries()) {
		console.log(key, value);
	}*/

    var saveBtn = document.getElementById('modal_save_btn');
    saveBtn.disabled = true;
    saveBtn.innerText = 'Saving...';

    fetch('ajax_data.php', {
        method: 'POST',
        credentials: 'same-origin',
        body: formData
    })
    .then(res => res.text())
    .then(text => {
        let data;
        try {
            data = JSON.parse(text);
        } catch (e) {
            console.error('Invalid JSON:', text);
            return;
        }

        if (data.status === 'success') {

			//alert(data.message);  
			showToast('success', data.message);
            // ✅ CLOSE MODAL
			
			document.getElementById("service_remark").value = "";
			document.getElementById("nfd").value = "-1";
			document.getElementById("nfd1").value = "";
			document.getElementById("status").value = "pending";
			document.getElementById("service_status_date").value = "";
			
            closeModal('service_update_followup');

            // ✅ REFRESH ONLY XCRUD TABLE
            if (typeof Xcrud !== 'undefined' && ACTIVE_XCRUD_CONTAINER) {
                Xcrud.reload(ACTIVE_XCRUD_CONTAINER);
            }

        } else {
			console.log(data);
            alert(data.message || 'Something went wrong');
        }
    })
    .catch(err => {
        if (err.name === 'AbortError') return;
        console.error('NETWORK ERROR:', err);
    })
    .finally(() => {
        saveBtn.disabled = false;
        saveBtn.innerText = 'Save';
		if(loader) loader.style.display = "none";
    });
};

})();

function closeModal(modalId) {
    var modal = document.getElementById(modalId);
    if (!modal) return;
	
    // Case 1: Bootstrap 4 + jQuery plugin exists (BEST)
    if (window.jQuery && typeof jQuery(modal).modal === 'function') {
        jQuery(modal).modal('hide');
        return;
    }

    // Case 2: Fallback – force close manually
    modal.classList.remove('show');
    modal.style.display = 'none';
    modal.setAttribute('aria-hidden', 'true');

    document.body.classList.remove('modal-open');
    document.body.style.paddingRight = '';

    var backdrop = document.querySelector('.modal-backdrop');
    if (backdrop) backdrop.remove();
}

function validateServiceFollowupForm() {

    var remark = document.getElementById('service_remark').value.trim();
    var nfd = document.getElementById('nfd').value;
    var date = document.getElementById('nfd1').value.trim();
    var status = document.getElementById('status').value;
    var service_status_date = document.getElementById('service_status_date').value.trim();

    if (status!='lost' && remark === "") {
        alert('Enter remark');
        document.getElementById('service_remark').focus();
        return false;
    }

    if (status!='lost' && nfd === "-1" && date === "") {
        alert('Select date');
        document.getElementById('nfd').focus();
        return false;
    }

    if (service_status_date === "") {
        alert('Select status date');
        document.getElementById('service_status_date').focus();
        return false;
    }
	

    return true; // ✅ validation passed
}

function showToast(type, message) {

    // AdminLTE Toast available
    if (window.jQuery && typeof jQuery(document).Toasts === 'function') {
        jQuery(document).Toasts('create', {
            class: type === 'success' ? 'bg-success' : 'bg-danger',
            title: type === 'success' ? 'Success' : 'Error',
            body: message,
            autohide: true,
            delay: 3000
        });
        return;
    }

    // Fallback
    alert(message);
}


</script>
