<?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';
}
?>

<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">Bulk Followup : <?php echo $followup_title;?></h3>
              </div>
              <div class="card-body">

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

				$xcrud->join('service_id','bulk_service','id');
				$xcrud->order_by('bulk_service.invoice_date','desc');
				$xcrud->order_by('bulk_service.id','asc');
				$xcrud->order_by('service_no','asc');
				
				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('bulk_service.status=','active');
				

				$xcrud->relation('bulk_service.product_id','products','id','name');
				$xcrud->relation('bulk_service.city_id','city','id','name');
				$xcrud->relation('user_id','users','id','username');
				$xcrud->relation('bulk_service.institute_id','institute','id','name');
				
				$xcrud->columns('bulk_service.customer_name,bulk_service.mobile_no,bulk_service.chassis_no,bulk_service.registration_no,bulk_service.city_id,bulk_service.institute_id,bulk_service.product_id,bulk_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('bulk_service.customer_name,bulk_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('bulk_service.service_id','Service Id');
				$xcrud->label('user_id','User');
				$xcrud->label('bulk_service.institute_id','Institute');
				$xcrud->label('bulk_service.product_id','Product');
				$xcrud->label('bulk_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'=>'{bulk_service.mobile_no}',
						'data-service_id'=>'{bulk_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('bulk_service.customer_name','300px');
				$xcrud->column_width('bulk_service.product_id,bulk_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">
          <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-4">
						  <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-3">
						  <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-5">
						  <div class="form-group">
							<label>Mobile No | <input type="checkbox" id="change_mobile_no"> Change</label>
							<input type="text" id="primary_ph_no" name="primary_ph_no" readonly class="form-control">
							<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="service_done">Service Done</option>
                                <!--<option value="appointment">Appointment</option>
                                <option value="pickup">Pickup</option>
                                <option value="close">Close</option>
                                <option value="lost">Lost</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" placeholder="Status Date">
						  </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-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-success" onclick="openHistory('appointment')">Appointment</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>

<?php
$bdd->disconnect();
include 'footer.php';
?>
<?php
echo Xcrud::load_js();
?>


<script>
var ACTIVE_XCRUD_CONTAINER = null;

//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";
    }
});

(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','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;
    });

    // 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 || "";
      // secondary phone: if you have extra attr 'secondary' change accordingly
      //document.getElementById("secondary_ph_no").value = extras.secondary || "";

      // 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 = "";
      document.getElementById("service_status_date").value = "";

      // 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("primary_ph_no").readOnly = !this.checked; };
      //c_sph.onchange = function(){ document.getElementById("secondary_ph_no").readOnly = !this.checked; };

      // 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 (!validateServiceFollowupForm()) {
        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 {
            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';
    });
};

})();

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 (remark === "") {
        alert('Enter remark');
        document.getElementById('service_remark').focus();
        return false;
    }

    if (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>
