$(document).ready(function(){
    $('#addlead').click(function(e){
        e.preventDefault();
        
        // Gather form data
        var formData = new FormData($('#add_lead')[0]);

        var email = $('#email').val().trim();
        var fname = $('#fname').val().trim();
        var lname = $('#lname').val().trim();
        var contact1 = $('#contact1').val().trim();
        var contact2 = $('#contact2').val().trim();

        if (fname === '') {
            $('#err-msg').html('First Name Required.');
            return;
        }


        if (lname === '') {
            $('#err-msg').html('Last Name field required.');
            return;
        }

   // Regular expression for validating phone number format (simple validation)
   var phoneRegex = /^\d{10}$/;
   // Regular expression for validating email format
   var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

           // Validate email if it's not empty
           if (email !== '' && !emailRegex.test(email)) {
            $('#err-msg').html('Invalid email address');
            return;
        }



   // Validate contact1
   if (contact1 === '') {
       $('#err-msg').html('Contact Number Required');
       return;
   } else if (!phoneRegex.test(contact1)) {
       $('#err-msg').html('Contact 1 is not in valid phone number format');
       return;
   }

   // Validate contact2 if it is not empty
   if (contact2 !== '' && !phoneRegex.test(contact2)) {
       $('#err-msg').html('Contact 2 is not in valid phone number format');
       return;
   }



        $.ajax({
            url: './script_addlead.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'html',
            success: function(response){
                $('#addresp').html(response);
                $('#err-msg').html('');
            },
            error: function(xhr, status, error){
                console.error(status, error);
            }
        });
    });
});