var NORMALSERVER = "http://localhost:8080/admin/";
$('doucment').ready(function() {

	$(".accept_only_character").keypress(function(event) {

		if ((event.keyCode > 64 && event.keyCode < 91) || (event.keyCode > 96 && event.keyCode < 123)) {

		} else {

			event.preventDefault();
		}
	});
	$('.add_student_fileInput').change(function() {
		if ($(this).get(0).files.length > 0) {// only if a file is selected
			var fileSize = $(this).get(0).files[0].size;
			if (fileSize > 100000) {
				alert('Maximum File size should be 100 KB');
				$('.add_student_fileInput').val('');
			}

		}
	});
	// pattren pattern="\d*" maxlength="3" for mobile NUmber

	$(".number_validation").keypress(function(event) {

		if (event.keyCode == 46 || event.keyCode == 8) {

		} else {

			if (event.keyCode < 48 || event.keyCode > 57) {

				event.preventDefault();

			}
		}
	});

	$('.add_course_button').click(function() {

		var cousre_name = $('#cousre_name').val().trim();

		var course_year = $('#course_year').val().trim();

		if (cousre_name == '') {
			alert('Invalid Coures Name');

			$('#cousre_name').focus();

			return false;
		}
		if (course_year == '') {
			alert('Invalid Number of Years');

			$('#course_year').focus();

			return false;
		}
	});

	$('.add_user_button').click(function() {

		var company_name = $('#company_name').val().trim();

		var mobile = $('#mobile').val().trim();

		var email = $('#email').val().trim();

		var first_name = $('#first_name').val().trim();

		var is_update = $('.is_update').val();

		var user_name = $('#user_name').val().trim();

		var password = $('#password').val().trim();

		var c_password = $('#c_password').val().trim();

		var crs_fee = $('#crs_fee').val().trim();
		if (company_name == '') {
			alert('Invalid Company Name');

			$('#company_name').focus();

			return false;
		}

		if (first_name == '') {
			alert('Invalid Name');

			$('#first_name').focus();

			return false;
		}
		if (mobile == '' || mobile.lenght() != 10) {
			alert('Invalid Mobile Number');

			$('#mobile').focus();

			return false;
		}
		if (email == '') {
			alert('Invalid Email ID');

			$('#email').focus();

			return false;
		}
		if (user_name == '') {
			alert('Invalid User Name');

			$('#user_name').focus();

			return false;
		}
		if (is_update > 0) {
			if (password != '' || c_password != '') {
				if (password != c_password) {

					alert('Password and Confirm Password does not match');

					$('#password').focus();

					$('#c_password').val('');

					return false;
				}
			}
		} else {
			if (password != c_password || password == '') {

				alert('Password and Confirm Password does not match');

				$('#password').focus();

				$('#c_password').val('');

				return false;
			}
		}

		if (crs_fee == '') {
			alert('Invalid CRS Fee % ');

			$('#crs_fee').focus();

			return false;
		}

		return true;
	});
	$('.add_subcourse_button').click(function() {

		var cousre_name = $('#cousre_name').val().trim();

		var course_id = $('#course_id').val().trim();
		var exam_fee = $('#exam_fee').val().trim();
		var crs_fee = $('#crs_fee').val().trim();
		//accepted in %
		var prospectus_fee = $('#prospectus_fee').val().trim();
		var service_charge = $('#service_charge').val().trim();
		var fee = $('#fee').val().trim();

		if (course_id == '') {
			alert('Invalid Course Name');

			$('#course_id').focus();

			return false;
		}

		if (cousre_name == '') {
			alert('Invalid Sub Coures Name');

			$('#cousre_name').focus();

			return false;
		}
		if (exam_fee == '' || crs_fee == '' || prospectus_fee == '' || service_charge == '' || fee == '') {

			alert('Please fill all fileds');

			$('#cousre_name').focus();

			return false;
		}

	});

	$('#course_id').change(function() {

		var course_id = $(this).val();

		var year = $('option:selected', this).attr('year');

		if (course_id == '' || course_id == 0) {
			$("#choose_subcourse").html("<option value='0'>Choose Sub Course</option>");
			return false;
		}
		var formData = "requestType=get_subcourse&course_id=" + course_id + '&redirect_url=1';

		$.ajax({
			type : 'POST',
			url : NORMALSERVER+'get_subcourse_by_courseid',
			data : formData,
			success : function(data) {

				var json_x = $.parseJSON(data);				
				$("#sub_course_id").html(json_x);

				var yearHtml = '<option value="">Select Semester</option><option value="1">First Semester</option>';
				if (year >= 2) {
					yearHtml += '<option value="2">Second Semester</option>';
				}
				if (year >= 3) {
					yearHtml += '<option value="3">Third Semester</option>';
				}
				if (year >= 4) {
					yearHtml += '<option value="4">Fourth Semester</option>';
				}
				if (year >= 5) {
					yearHtml += '<option value="5">Fifth Semester</option>';
				}

				$('#year1').html(yearHtml);
			}
		});

	});

	$('#year').change(function() {

		var year = $(this).val();

		var htmlapp = "";

		if (year == 1) {
			htmlapp += "<option value='Fresher'>Fresher</option>";
		} else {
			htmlapp += "<option value='Credit Transfer'>Credit Transfer</option>";
		}

		$('#category').html(htmlapp);

	});

	$('#admission_type').change(function() {
		var type = $('option:selected', this).attr('type');
		yearHtml = '';
		if (type == 1) {
			yearHtml += '<option value="1">First Semester</option>';
		}
		if (type == 2) {
			yearHtml += '<option value="2">Second Semester</option>';

			yearHtml += '<option value="3">Third Semester</option>';
		}
		if (type == 3) {
			yearHtml += '<option value="2">Second Semester</option>';

			yearHtml += '<option value="3">Third Semester</option>';
		}
		if (type == 0) {
			yearHtml += '<option value="0">Select Semester</option>';
		}

		//$('#year').html(yearHtml);
	});

	$('.add_student_detail').click(function() {
		if ($('#admission_type').val().trim() == 0) {
			alert('Please Enter Admission type');
			return (false);
		}
		if ($('#student_name').val().trim() == '') {
			alert('Please Enter Student Name');
			return (false);
		}
		if ($('#father_name').val().trim() == '') {
			alert('Please Enter Student Father Name');
			return (false);
		}
		if ($('#mother_name').val().trim() == '') {
			alert('Please Enter Student Mother Name');
			return (false);
		}
		if ($('#address').val().trim() == '') {
			alert('Please Enter Student Address');
			return (false);
		}
		if ($('#phone').val().trim() == '') {
			alert('Please Enter Valid Phone Number');
			return (false);
		}
		if ($('#dob').val().trim() == '') {
			alert('Please Select Student Day/Month/Year');
			return (false);
		}
		if ($('#course_id').val().trim() == '') {
			alert('Please select Student course');
			return (false);

		}
		if ($('#sub_course_id').val().trim() == '') {
			alert('Please select sub course');
			return (false);
		}
		if ($('#year').val().trim() == '') {
			alert('Please select Year');
			return (false);
		}
		if ($('#dob').val().trim() == '') {
			alert('Please select Year Catagory');
			return (false);
		}
		if ($('#calender_to').val().trim() == '') {
			alert('Please select Session');
			$('#calender_to').focus();
			return (false);
		}

	});

	$('.calculate_total').click(function() {

		var exam_fee = $('#exam_fee').val();
		var crs_fee = $('#crs_fee').val();
		//accepted in %
		var prospectus_fee = $('#prospectus_fee').val();
		var service_charge = $('#service_charge').val();
		var fee = $('#fee').val();
		var total = parseInt(fee * crs_fee / 100) + parseInt(prospectus_fee) + parseInt(service_charge) + parseInt(exam_fee);
		$('.total_span_count_1').hide();
		$('.total_span_count').html('Rs ' + total);
	});

	$('.search_student_button').click(function() {

		var s = $('.search_student_div_input').val();
		var y = $('.year_student_div_input').val();
		window.location.href = "view_student_list.php?s=" + s + "&y=" + y;

	});

	$('#select_state').change(function() {

		var select_state = $(this).val();

		if (select_state == '' || select_state == 0) {
			$("#select_city").html("<option value='0'>SELECT ONE</option>");
			return false;
		}
		var formData = "requestType=get_city&redirect_url=''&state=" + select_state;

		$.ajax({
			type : 'POST',
			url : NORMALSERVER+'get_city_by_state',
			data : formData,
			success : function(data) {
				var json_x = $.parseJSON(data);
				//console.log();
				$("#select_city").html(json_x);
			}
		});

	});

	$('#last_passout').change(function() {

		var last_passout = $(this).val();		
		if(last_passout=='June 17 & Before'){
			$('#admission_session').val("A 18-19");
		}else if(last_passout=='June 18'){
		$('#admission_session').val("C-19");
	 }else{}

	});

	$('#counselor_name').change(function() {
		var counselor_name = $(this).val();
		if (counselor_name == '' || counselor_name != 0) {	
		var formData = "counselor_name=" + counselor_name;		
		$.ajax({
			type : 'POST',
			url : NORMALSERVER+'get_counselor',
			data : formData,
			success : function(data) {
				var json_x = $.parseJSON(data);					
				if(json_x.mobile!=null && json_x.mobile!=''){
					$("#counselor_mobile").val(json_x.mobile);
				}
				if(json_x.email!=null && json_x.email!=''){
					$("#counselor_email").val(json_x.email);
				}
				
			}
		});
    }
	});
	$('#employment_status').change(function() {
		var employment_status = $('option:selected', this).val();		
		if (employment_status == 'EMPLOYED' || employment_status == 'SELF EMPLOYED') {
			$("#emp-company-name").show();
			$("#emp_designations").show();
			
		}else{
			$("#emp-company-name").hide();
			$("#emp_designations").hide();
		}	
	});
	$('#addActivity').click(function() {
		var lead_id = $('#lead_id').val();
		var user_id = $('#user_id').val();		
		$('#addActivity').addClass('kt-spinner kt-spinner--light kt-spinner--right');
		$.get('/leads/activity?user_id='+user_id+'&lead_id='+lead_id, function (data) {					
					$('#activity').html(data);
					$('#addActivity').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
					$('#datepicker').datepicker({
		                uiLibrary: 'bootstrap4',
		                 format: 'dd-mm-yyyy'
		            });
				});			
	});		
 $('#kt_form').validate({ submitHandler: function(form) {form.submit();}});
 if($('#lead_details').length){
 	 leadActivity();
 	}
});
function closeActivity(){
    $("#kt_modal_4_2").remove();
}
function submitActivity(){   
    var activity_type = $('#activity_type').val(); 
    var comment = $('#comment').val(); 
    var lid = $('#lid').val(); 
    var validate = true;  
    if(activity_type==''){    	
    	validate = false;
    	$('.help-block').html('<p style="color: #dd4b39">Activity Type is required</p>');
    }
    if(validate==true){ 
        $('#submit-activity').addClass('kt-spinner kt-spinner--light kt-spinner--right');	
		$.ajax({
			type : 'POST',
			url : '/leads/add_activity',
			data : $('#activity-form').serialize(),
			success : function(data) {
				var json_x = $.parseJSON(data);	
				$('#submit-activity').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
				if(json_x.activity_type!=null && json_x.activity_type!=''){
					$(".help-block").html(json_x.activity_type);
				}
				if(json_x.status!=null && json_x.status!='' && json_x.status=='pass'){					
					$("#kt_modal_4_2").remove();					
					leadActivity(lid);					
				}
				
			}
		});    
    }
}
function leadActivity(lid){   
    var lead_id = $('#lead_id').val();
    if(lead_id==''){
    	lead_id = lid;
    }			
	//$('#addActivity').addClass('kt-spinner kt-spinner--light kt-spinner--right');
	$('#leadActivity').append('<div class="overlay"><div class="loader"><span></span></div></div>');
	$.get('/leads/leadactivity?lead_id='+lead_id, function (data) {					
		$('#leadActivity').html(data);
		//$('#addActivity').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
    });
   
}
$('#addTask').click(function() {
	var lead_id = $('#lead_id').val();
	var user_id = $('#user_id').val();		
	$('#addTask').addClass('kt-spinner kt-spinner--light kt-spinner--right');
	$.get('/leads/task?user_id='+user_id+'&lead_id='+lead_id, function (data) {					
				$('#activity').html(data);
				$('#addTask').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
				$('#datepicker').datepicker({
	                uiLibrary: 'bootstrap4',
	                 format: 'dd-mm-yyyy'
	            });
			});			
});	
$('#salesActivity').click(function() {
	var lead_id = $('#lead_id').val();
	var user_id = $('#user_id').val();		
	$('#salesActivity').addClass('kt-spinner kt-spinner--light kt-spinner--right');
	$.get('/leads/sales?user_id='+user_id+'&lead_id='+lead_id, function (data) {					
				$('#activity').html(data);
				$('#salesActivity').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
				$('#datepicker').datepicker({
	                uiLibrary: 'bootstrap4',
	                 format: 'dd-mm-yyyy'
	            });
			});			
});	

$('#checkAllLead').on('change', function () {
    $('.row-checkbox').prop('checked', $(this).prop('checked'));
    updateSelectedCount();
});

function updateSelectedCount() {
    let count = $('.row-checkbox:checked').length;
    if (count === 0) {
        //$('#selectedCountLabel').text("0 selected");
        $('#countBox').hide(); 
    } else {
        //$('#selectedCountLabel').text(count + " selected – Click to assign");
        $('#countBox').show(); // show whole div
        $('#selectedCountLabel').text(count + " selected");
    }
}
$('.row-checkbox').on('change', function () {
    $('#checkAll').prop('checked', $('.lead:checked').length === $('.lead').length);
    updateSelectedCount();
});

$('#assignBtn').on('click', function () {
    let selectedIds = $('.row-checkbox:checked').map(function () {
        return $(this).val();
    }).get();
    
     let assigned_to = $('#assigned_to').val();
     if(assigned_to!='' && assigned_to!= undefined && selectedIds.length>0)
     var formData = "assigned_to=" + assigned_to + "&lead_ids=" + selectedIds;
     //var formData = "state=" + select_state;
     $.ajax({
        url: "/leads/assign_lead",
        type: "POST",
        data: formData,
        success: function (response) {
            alert("Leads assigned successfully!");
            location.reload(); 
        },
        error: function (xhr) {
            alert("API error: " + xhr.status);
        }
    });

    // Call API
    //assignLeads(selectedIds);
});

function submitSalesActivity(){   
    var sales_status = $('#sales_status').val(); 
    var sales_date = $('#datepicker').val(); 
    var university = $('#university').val(); 
    var product = $('#product').val(); 
    var lid = $('#lid').val();
    var validate = true;  
    if(sales_status==''){    	
    	validate = false;
    	$('#sales_status').siblings('.help-block').html('<p style="color: #dd4b39">Sales is required.</p>');
    }else{
    	$('#sales_status').siblings('.help-block').html('');
    }
    if(product==''){    	
    	validate = false;
    	$('#product').siblings('.help-block').html('<p style="color: #dd4b39">Product is required.</p>');
    }else{
    	$('#product').siblings('.help-block').html('');
    }
    if(university==''){    	
    	validate = false;
    	$('#university').siblings('.help-block').html('<p style="color: #dd4b39">University is required.</p>');
    }else{
    	$('#university').siblings('.help-block').html('');
    }
    if(sales_date==''){    	
    	validate = false;
    	$('#datepicker').siblings('.help-block').html('<p style="color: #dd4b39">Sales Date is required.</p>');
    }else{
    	$('#datepicker').siblings('.help-block').html('');
    }
    if(validate==true){ 
        $('#submit-activity').addClass('kt-spinner kt-spinner--light kt-spinner--right');	
		$.ajax({
			type : 'POST',
			url : '/leads/sales_activity',
			data : $('#activity-form').serialize(),
			success : function(data) {
				var json_x = $.parseJSON(data);	
				$('#submit-activity').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
				if(json_x.sales_status!=null && json_x.sales_status!=''){
					$('#sales_status').siblings('.help-block').html(json_x.sales_status);
				}
				if(json_x.product!=null && json_x.product!=''){
					$('#product').siblings('.help-block').html(json_x.product);
				}
				if(json_x.university!=null && json_x.university!=''){
					$('#university').siblings('.help-block').html(json_x.university);
				}
				if(json_x.sales_date!=null && json_x.sales_date!=''){
					$('#datepicker').siblings('.help-block').html(json_x.sales_date);
				}
				if(json_x.status!=null && json_x.status!='' && json_x.status=='pass'){					
					$("#kt_modal_4_2").remove();					
					leadActivity(lid);					
				}
				
			}
		});    
    }
}
function submitTask(){   
    var task_type = $('#task_type').val(); 
    var schedule = $('#datepicker').val();     
    var lid = $('#lid').val();
    var validate = true;  
    if(task_type==''){    	
    	validate = false;
    	$('#task_type').siblings('.help-block').html('<p style="color: #dd4b39">Task Type is required.</p>');
    }else{
    	$('#task_type').siblings('.help-block').html('');
    }    
    if(schedule==''){    	
    	validate = false;
    	$('#datepicker').siblings('.help-block').html('<p style="color: #dd4b39">Schedule Date is required.</p>');
    }else{
    	$('#datepicker').siblings('.help-block').html('');
    }
    if(validate==true){ 
        $('#submit-activity').addClass('kt-spinner kt-spinner--light kt-spinner--right');	
		$.ajax({
			type : 'POST',
			url : '/leads/atask',
			data : $('#activity-form').serialize(),
			success : function(data) {
				var json_x = $.parseJSON(data);	
				$('#submit-activity').removeClass('kt-spinner kt-spinner--light kt-spinner--right');
				if(json_x.task_type!=null && json_x.task_type!=''){
					$('#task_type').siblings('.help-block').html(json_x.task_type);
				}				
				if(json_x.schedule!=null && json_x.schedule!=''){
					$('#datepicker').siblings('.help-block').html(json_x.schedule);
				}
				if(json_x.status!=null && json_x.status!='' && json_x.status=='pass'){					
					$("#kt_modal_4_2").remove();					
					leadActivity(lid);					
				}
				
			}
		});    
    }
}