
//NEW FIELD AGENT
$('.trigger-unblock').click(function(){
   var agentId = $(this).attr('data-agentId');
 // alert(agentId);
    $('#unblock').val(agentId);
   
   
});

//UNBLOCKING FIELD AGENT
$('.trigger-block').click(function(){
    var agentId = $(this).attr('data-agentId');
  
    $('#block').val(agentId);
   
});

//BLOCKING FIELD AGENT
$('#add-field-agent').click(function(){
   var rcnumber = $(this).attr('data-rcnumber');
   var tin = $(this).attr('data-tin');
    $('#companyRc').val(rcnumber);
    $('#companyTin').val(tin);
   
});

// CHECK UNIQ FIELDS
$(document).ready(function() {
    function checkAvailability(field, value, callback) {
        $.ajax({
            url: 'availabilityChecker.php',
            type: 'POST',
            data: { field: field, value: value },
            success: function(response) {
                if (response.trim() === 'exists') {
                    alert(field.toUpperCase() + ' already exists!');
                    $('#' + field).addClass('is-invalid');
                    callback(false);
                } else {
                    $('#' + field).removeClass('is-invalid');
                    callback(true);
                }
            }
        });
    }

    $('#submit-btn').on('click', function(event) {
        event.preventDefault(); // Prevent default submission

        // Validate required fields
        var title = $('#title').val().trim();
        var surname = $('#surname').val().trim();
        var firstname = $('#firstname').val().trim();
        var othername = $('#othername').val().trim();
        var gender = $('#gender').val().trim();
        var commandCode = $('#commandCode').val().trim();
        var address = $('#address').val().trim();
        var phone = $('#phone').val().trim();
        var nin = $('#nin').val().trim();
        var email = $('#email').val().trim();

        if (!title || !surname || !firstname || !gender || !commandCode || !address) {
            alert('Please fill out all required fields.');
            return;
        }

        if (phone.length !== 11 || nin.length !== 11 || email === '') {
            alert('Please enter valid details: Phone & NIN must be 11 digits, Email must not be empty.');
            return;
        }

        // Check database for duplicates before allowing form submission
        checkAvailability('phone', phone, function(phoneValid) {
            checkAvailability('nin', nin, function(ninValid) {
                checkAvailability('email', email, function(emailValid) {
                    if (phoneValid && ninValid && emailValid) {
                        $('#field-agent-form').submit(); // Submit the form if everything is valid
                    }
                });
            });
        });
    });
});
//USER UPDATE
