// user tracker
function userTracker(visited_type, sub_type, primary_id)
{
	if (visited_type !== '' && vcardId > 0) {		
		$.ajax({
			url:  trackerUrl,
			type: "POST",
			data: {
				'vcard_id': vcardId,
				'visited_type': visited_type,
				'sub_type': sub_type,
				'primary_id': primary_id,
				'_token':$('meta[name="csrf-token"]').attr('content')
			},
			success: function(response) {
				console.log(response);
			},
			error: function(xhr, status, error) {
				console.log('error');
				console.log(xhr.responseText);
			}
		});
	}
}

$(document).on('submit', '.contactHomeform', function(e){
	e.preventDefault();
	// validate request
	if(checkValidation(this)==false)
	{
		return false;
	}

	if ($('input[name="enqurytype"]:checked').val() === "sendInquiry") {
		$("#formsubmitbtn").prop("disabled", !0);
		var prevButtonText = $('#formsubmitbtn').text();
		$('#formsubmitbtn').html('<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> Please wait...');
		$.ajax({
			url: enquiryUrl,
			type: "POST",
			data: $(this).serialize(),
			success: function(e) {
				if (e.success) {
					messageFire('success', e.message);
					$("#contactHomeform")[0].reset();
					$('#contactHomeform').trigger("reset");
					$('#formsubmitbtn').text(prevButtonText);
					$("#formsubmitbtn").prop("disabled", false);
				}
			},
			error: function(e) {
				messageFire('error', e.responseJSON.message);
				$('#formsubmitbtn').text(prevButtonText);
				$("#formsubmitbtn").prop("disabled", false);
			}
		});
	}else{
		$("#formsubmitbtn").prop("disabled", !0);
		var prevButtonText = $('#formsubmitbtn').text();
		$('#formsubmitbtn').html('<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> Please wait...');
		$.ajax({
			url: appointmentUrl,
			type: "POST",
			data: $(this).serialize(),
			success: function(e) {
				if (e.success) {            
					messageFire('success', e.message);
					$("#contactHomeform")[0].reset();
					$('#contactHomeform').trigger("reset");
					$('#formsubmitbtn').text(prevButtonText);
					$("#formsubmitbtn").prop("disabled", false);
					$('.formSendInquiry').hide();
					$("#slotData").html('<option value="">Choose Time</option>');
					$("#pickUpDate").val("");
					$("#timeSlot").val("");
					$("#toTime").val("");
					$("#Date").val("");
				}
			},
			error: function(e) {
				messageFire('error', e.responseJSON.message);
				$('#formsubmitbtn').text(prevButtonText);
				$("#formsubmitbtn").prop("disabled", false);
			}
		});
	}
});


$(document).on('submit', '.desktopblogcontactform, .mobileblogcontactform', function(e) {
    e.preventDefault();
    
    // Validate request
    if (checkValidation(this) === false) {
        return false;
    }

    if ($('input[name="enqurytype"]:checked').val() === "sendInquiry") {
        // Disable submit button and change text
        const $submitButton = $('.blogsendbtn');
        const prevButtonText = $submitButton.text();
        $submitButton.prop("disabled", true).html('<span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> Please wait...');
        
        $.ajax({
            url: enquiryUrl,
            type: "POST",
            data: $(this).serialize(),
            success: function(response) {
                if (response.success) {
                    messageFire('success', response.message);

                    // Reset both forms
                    $('.desktopblogcontactform, .mobileblogcontactform').each(function() {
                        this.reset();
                    });

                    // Restore button state
                    $submitButton.text(prevButtonText).prop("disabled", false);
                }
            },
            error: function(error) {
                messageFire('error', error.responseJSON.message);

                // Restore button state in case of error
                $submitButton.text(prevButtonText).prop("disabled", false);
            }
        });
    }
});

function checkValidation(ths){
	let inquryBrif = $(ths).find('input[name="message"]').val();
	if (inquryBrif == '') {
		messageFire('error', 'Please enter your message.');
		return false;
	}

	let name = $(ths).find('input[name="name"]').val();
	if (name == '') {
		messageFire('error', 'Please enter your name.');
		return false;
	}

	var phoneInput = $(ths).find("input[name='phone']").val();
	var phoneRegex = /^\d{10}$/;
	if (!phoneRegex.test(phoneInput)) {
		messageFire('error', 'Please enter a 10-digit numeric phone number.');
		return false;
	}

	let email = $(ths).find('input[name="email"]').val();
	if (email == '') {
		messageFire('error', 'Please enter your email id.');
		return false;
	}

	return true;
}

function messageFire(type, message)
{
    if(type=='success')
    {
        toastr.success(message);
    }

    if(type=='error')
    {
        toastr.error(message);
    }

    if(type=="info")
    {
        toastr.info(message);
    }

    if(type=="warning")
    {
        toastr.warning(message);
    }
}

/**COPY-VCARD-CLIPBOARD ***/
$(document).on('click', ".copy-vcard-clipboard", function() {
    var id = $(this).data("id");
    var vcardUrl = $("#vcardUrlCopy" + id).text();

    // Use the Clipboard API
    navigator.clipboard.writeText(vcardUrl).then(function() {
        messageFire('success', 'Copied to clipboard!');
    }).catch(function(err) {
        messageFire('error', 'Failed to copy text: ' + err);
    });
});

//download vcf-card
window.downloadMyVcard = function (filename, cardId) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/vcards/" + cardId, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            if (response.success) {
                var data = response.data;
                var vcardContent = "BEGIN:VCARD\nVERSION:3.0\n";
                if (data.first_name && data.last_name) {
                    vcardContent += "N;CHARSET=UTF-8:" + data.last_name + ";" + data.first_name + ";;;\n";
                }
                if (data.dob) {
                    vcardContent += "BDAY;CHARSET=UTF-8:" + new Date(data.dob) + "\n";
                }
                if (data.email) {
                    vcardContent += "EMAIL;CHARSET=UTF-8:" + data.email + "\n";
                }
                if (data.alternative_email) {
                    vcardContent += "EMAIL;CHARSET=UTF-8:" + data.alternative_email + "\n";
                }
                if (data.job_title) {
                    vcardContent += "TITLE;CHARSET=UTF-8:" + data.job_title + "\n";
                }
                if (data.company) {
                    vcardContent += "ORG;CHARSET=UTF-8:" + data.company + "\n";
                }
                if (data.region_code && data.phone) {
                    vcardContent += "TEL;TYPE=WORK,VOICE:+" + data.region_code + " " + data.phone + "\n";
                }
                if (data.region_code && data.alternative_phone) {
                    vcardContent += "TEL;TYPE=WORK,VOICE:+" + data.region_code + " " + data.alternative_phone + "\n";
                }
                if (data.url_alias) {
                    var urlAlias = appUrl + "/" + data.url_alias;
                    vcardContent += "URL;TYPE=VYAPARIFY,CHARSET=UTF-8:" + urlAlias + "\n";
                }
                if (data.social_link && data.social_link.website) {
                    vcardContent += "URL;TYPE=SOCIAL,CHARSET=UTF-8:" + data.social_link.website + "\n";
                }
                if (data.description) {
                    vcardContent += "NOTE;CHARSET=UTF-8:" + data.description + "\n";
                }
                if (data.location) {
                    vcardContent += "ADR;CHARSET=UTF-8:" + data.location + "\n";
                }
                if (data.profile_url) {
                    var profileType = data.profile_url.split(".").pop().toUpperCase();
                    vcardContent += "PHOTO;ENCODING=BASE64;TYPE=" + profileType + ":" + data.profile_url_base64 + "\n";
                }
                vcardContent += "REV:" + new Date().toISOString() + "\n";
                vcardContent += "END:VCARD";

                var blob = new Blob([vcardContent], { type: "text/vcard;charset=utf-8" });
                var url = URL.createObjectURL(blob);
                var link = document.createElement("a");
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        } else if (xhr.readyState === 4) {
            var errorMessage = xhr.responseJSON ? xhr.responseJSON.message : "Error downloading vCard.";
            displayError("#enquiryError", errorMessage);
        }
    };
    xhr.send();

    userTracker('vcard_download', 'download', cardId);
};

/****APPOINTMENT****/
$(document).on("change", "#pickUpDate", function() {
	$('.send-enquiry').attr('disabled', true);
	if($(this).val() == '')
	{
		messageFire('error', 'Please select a date.');
		return false;
	}

    $("#slotData").empty();
    r = $(this).val(), $("#Date").val(r), $.ajax({
        url: slotUrl,
        type: "GET",
        data: {
            date: r,
            vcardId
        },
        success: function(a) {
            a.success && $.each(a.data, (function(a, n) {
                var r = [{
                    value: n
                }];
                var htmlFile = '<option data-id="'+n+'" value="'+n+'">'+n+'</option>';
                $("#slotData").append(htmlFile);
                slotData();
                $('.formSendInquiry').show();
				$('.send-enquiry').attr('disabled', false);
            }))
        },
        error: function(e) {
            var response = JSON.parse(e.responseText);
            if (response.message) {
                messageFire('error', response.message);
                slotData();
				$('.formSendInquiry').hide();
            } else {
                messageFire('error', 'An error occurred.');
                slotData();
				$('.formSendInquiry').hide();
            }
        }
    })
});

function slotData(){
    var dateSelected = $("#pickUpDate").val();
    var timeSlotSelected = $("#slotData").val();
    $("#timeSlot").val("");
	$("#toTime").val("");
    if (dateSelected && timeSlotSelected) {
		var e = $('#slotData').val().split("-"),
        a = e[0],
        n = e[1];
		$("#timeSlot").val(a),
		$("#toTime").val(n);
        $('.appointment-form').removeClass('d-none');
    }else{
        $('.appointment-form').addClass('d-none');
    }
}

$(document).on('submit', '#newOfferNotification', function(e){
	e.preventDefault();

    var phoneInput = $(this).find("input[name='whatsapp']").val();

    // Define regex patterns
    var phoneRegex = /^\d{10}$/;  // 10-digit phone number
    var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;  // Basic email pattern

    // Check if input is a valid phone number or a valid email
    if (!phoneRegex.test(phoneInput) && !emailRegex.test(phoneInput)) {
        messageFire('error', 'Please enter a valid 10-digit phone number or email address.');
        return false;
    }

    $("#subscriptionofferbtn").prop("disabled", !0);
    $.ajax({
        url: offersubscriptionUrl,
        type: "POST",
        data: $(this).serialize(),
        success: function(e) {
            if (e.success) {
                messageFire('success', e.message);
                $("#newOfferNotification")[0].reset();
                $('#newOfferNotification').trigger("reset");
                $("#subscriptionofferbtn").prop("disabled", false);
            }
        },
        error: function(e) {
            messageFire('error', e.responseJSON.message);
            $("#subscriptionofferbtn").prop("disabled", false);
        }
    });
});

$(document).on('click', '.buyNowBtn', function(){
    var productId = $(this).data('productid');
    var productName = $(this).data('productname');
    var productAmount = $(this).data('productamount');
    var productURL = $(this).data('url');
    var productImage = $(this).data('img');
    $('#buyNowModal').find('#product_id').val(productId);
    $('#buyNowModal').find('#product_name').val(productName);
    $('#buyNowModal').find('.productName').text(productName);
    $('#buyNowModal').find('.pricing').text('₹ '+productAmount);
    $('#buyNowModal').find('.btnViewProDetail').attr('href', productURL);
    $('#buyNowModal').find('.productImg').attr('src', productImage);
    $('#buyNowModal').find('#buyer_name').val('');
    $('#buyNowModal').find('#buyer_phone').val('');
    $('#buyNowModal').find('#buyer_email').val('');
    $('#buyNowModal').find('#buyer_state').val('');
    $('#buyNowModal').find('#buyer_city').val('');
    $('#buyNowModal').find('#buyer_zipcode').val('');
    $('#buyNowModal').find('#buyer_address').val('');

    //show modal
    $('#buyNowModal').modal('show');
});

$('#buyNowForm').submit(function(event) {
    event.preventDefault();
    var name = $('#buyer_name').val();
    var contact = $('#buyer_phone').val();
    var email = $('#buyer_email').val();
    var state = $('#buyer_state').val();
    var city = $('#buyer_city').val();
    var zipcode = $('#buyer_zipcode').val();
    var address = $('#buyer_address').val();
    var quantity = $('#product_quantity').val();
    var product_id = $('#product_id').val();
    // Validation for contact (mobile)
    if (!/^(?!0)([0-9]{10})$/.test(contact)) {
        $('#buyer_phone').addClass('border border-danger').focus();
        messageFire('error', 'Invalid contact. Please enter a 10-digit numeric value.');
        return false;
    }

    // Validation for name, state, and city
    if (!/^[A-Za-z ]+$/.test(name) || !/^[A-Za-z ]+$/.test(state) || !/^[A-Za-z ]+$/.test(city)) {
        messageFire('error', 'Name, state, and city should only contain letters and spaces.');
        return false;
    }

    // Validation for zip code (zipcode)
    if (!/^[1-9]\d{5}(\s\d{3})?$/.test(zipcode)) {
        $('#buyer_zipcode').addClass('border border-danger').focus();
        messageFire('error', 'Invalid zip code. Please enter a valid zip code.');
        return false;
    }

    // Validation for product quantity
    if (!/^[1-9]\d*$/.test(quantity)) {
        messageFire('error', 'Invalid product quantity. Please enter a non-zero numeric value.');
        return false;
    }
    if (name && contact && email && address && quantity && state && city && zipcode){
        $("#buyNowFormButton").prop("disabled",1);
        $.ajax({
            url:orderUrl,
            type:"POST",
            data:$(this).serialize(),
            success:function(e){
                $("#buyNowForm")[0].reset(),
                $("#buyNowFormButton").prop("disabled",!1);
                $('#buyNowModal').modal('hide');
                messageFire('success', 'Order successfully placed.');
                userTracker('orderplaced', 'product', product_id);
            },
            error:function(e){
                messageFire('error', e.responseJSON.message);
                $("#buyNowFormButton").prop("disabled",!1);
            }
        })
    } else {
        messageFire('error', 'Please fill all required fields.');
    }
});