
// Creta Testimonial Showcase plugin activation
document.addEventListener('DOMContentLoaded', function () {
    const cafe_eatery_button = document.getElementById('install-activate-button');

    if (!cafe_eatery_button) return;

    cafe_eatery_button.addEventListener('click', function (e) {
        e.preventDefault();

        const cafe_eatery_redirectUrl = cafe_eatery_button.getAttribute('data-redirect');

        // Step 1: Check if plugin is already active
        const cafe_eatery_checkData = new FormData();
        cafe_eatery_checkData.append('action', 'check_creta_testimonial_activation');

        fetch(installcretatestimonialData.ajaxurl, {
            method: 'POST',
            body: cafe_eatery_checkData,
        })
        .then(res => res.json())
        .then(res => {
            if (res.success && res.data.active) {
                // Plugin is already active → just redirect
                window.location.href = cafe_eatery_redirectUrl;
            } else {
                // Not active → proceed with install + activate
                cafe_eatery_button.textContent = 'Nevigate Getstart';

                const cafe_eatery_installData = new FormData();
                cafe_eatery_installData.append('action', 'install_and_activate_creta_testimonial_plugin');
                cafe_eatery_installData.append('_ajax_nonce', installcretatestimonialData.nonce);

                fetch(installcretatestimonialData.ajaxurl, {
                    method: 'POST',
                    body: cafe_eatery_installData,
                })
                .then(res => res.json())
                .then(res => {
                    if (res.success) {
                        window.location.href = cafe_eatery_redirectUrl;
                    } else {
                        alert('Activation error: ' + (res.data?.message || 'Unknown error'));
                        cafe_eatery_button.textContent = 'Try Again';
                    }
                })
                .catch(error => {
                    alert('Request failed: ' + error.message);
                    cafe_eatery_button.textContent = 'Try Again';
                });
            }
        })
        .catch(error => {
            alert('Check request failed: ' + error.message);
        });
    });
});
