// blogibot-admin.js
// Version: 1.0.6
// Last updated: 2025-05-07
//
// Handles Blogibot admin AJAX, UI, and button logic

document.addEventListener('DOMContentLoaded', function () {
    // Attach event listeners to all Fetch Now buttons
    document.querySelectorAll('button[data-fetch-category]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            btn.disabled = true;
            addSpinner(btn);
            fetchNow(btn.getAttribute('data-fetch-category'), btn);
        });
    });
    // Update AJAX action names and REST route to use blog82ai_ prefix
    // Resume button AJAX
    document.querySelectorAll('a.button[data-resume-id]').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            btn.disabled = true;
            addSpinner(btn);
            const scheduleId = btn.getAttribute('data-resume-id');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blog82ai_resume_schedule&schedule_id=${encodeURIComponent(scheduleId)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    reloadScheduleTable(); // Always reload for consistency
                    displayMessage(data.data.message, 'success');
                } else {
                    displayMessage(data.data.message || 'Failed to resume.', 'error');
                }
                btn.disabled = false;
                removeSpinner(btn);
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                btn.disabled = false;
                removeSpinner(btn);
            });
        });
    });
    // Pause button AJAX
    document.querySelectorAll('a.button[data-pause-id]').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            btn.disabled = true;
            addSpinner(btn);
            const scheduleId = btn.getAttribute('data-pause-id');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blog82ai_pause_schedule&schedule_id=${encodeURIComponent(scheduleId)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    reloadScheduleTable(); // Always reload for consistency
                    displayMessage(data.data.message, 'success');
                } else {
                    displayMessage(data.data.message || 'Failed to pause.', 'error');
                }
                btn.disabled = false;
                removeSpinner(btn);
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                btn.disabled = false;
                removeSpinner(btn);
            });
        });
    });
    // Delete button AJAX
    document.querySelectorAll('a.button[data-delete-id]').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            btn.disabled = true;
            addSpinner(btn);
            const scheduleId = btn.getAttribute('data-delete-id');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blog82ai_delete_schedule&schedule_id=${encodeURIComponent(scheduleId)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    reloadScheduleTable(); // Always reload for consistency
                    displayMessage(data.data.message, 'success');
                } else {
                    displayMessage(data.data.message || 'Failed to delete.', 'error');
                    btn.disabled = false;
                    removeSpinner(btn);
                }
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                btn.disabled = false;
                removeSpinner(btn);
            });
        });
    });
    // AJAX scheduler form submission
    const scheduleForm = document.getElementById('blogibot-scheduler-form');
    if (scheduleForm) {
        scheduleForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const category = scheduleForm.querySelector('[name="blog_category"]').value;
            const date = scheduleForm.querySelector('[name="schedule_date"]').value;
            const runTime = scheduleForm.querySelector('[name="schedule_run_time"]').value;
            const submitBtn = scheduleForm.querySelector('input[name="submit_schedule"]');
            submitBtn.disabled = true;
            addSpinner(submitBtn);
            scheduleBlogViaAjax(category, date, runTime, function(data) {
                if (data.success) {
                    displayMessage(data.data.message, 'success');
                    // Instead of building a row manually, reload the table body via AJAX for consistency
                    reloadScheduleTable();
                    // Optionally, reset the form
                    scheduleForm.reset();
                } else {
                    displayMessage(data.data.message || 'Failed to schedule.', 'error');
                }
                submitBtn.disabled = false;
                removeSpinner(submitBtn);
            });
        });
    }

    // License registration handler
    const registerBtn = document.getElementById('blogibot-register-license');
    if (registerBtn) {
        registerBtn.addEventListener('click', function () {
            const keyInput = document.getElementById('blogibot_api_key');
            const domainInput = document.getElementById('blogibot_domain');
            const licenseMsg = document.getElementById('blogibot-license-message');
            const licenseKey = keyInput ? keyInput.value.trim() : '';
            const domain = domainInput ? domainInput.value.trim() : '';
            if (!licenseKey || !domain) {
                displayMessage('Please enter both license key and domain.', 'error');
                return;
            }
            registerBtn.disabled = true;
            addSpinner(registerBtn);
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blogibot_register_license&license_key=${encodeURIComponent(licenseKey)}&domain=${encodeURIComponent(domain)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    displayMessage(data.data.message || 'License registered successfully.', 'success');
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    displayMessage(data.data.message || 'License registration failed.', 'error');
                }
                registerBtn.disabled = false;
                removeSpinner(registerBtn);
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                registerBtn.disabled = false;
                removeSpinner(registerBtn);
            });
        });
    }

    // License removal handler
    const removeBtn = document.getElementById('blogibot-remove-license');
    if (removeBtn) {
        removeBtn.addEventListener('click', function (e) {
            e.preventDefault();
            if (!confirm('Are you sure you want to remove the license key?')) return;
            removeBtn.disabled = true;
            addSpinner(removeBtn);
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blogibot_remove_license&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    displayMessage(data.data.message || 'License removed successfully.', 'success');
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    displayMessage(data.data.message || 'License removal failed.', 'error');
                }
                removeBtn.disabled = false;
                removeSpinner(removeBtn);
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                removeBtn.disabled = false;
                removeSpinner(removeBtn);
            });
        });
    }
});

function addSpinner(btn) {
    if (!btn.querySelector('.blogibot-spinner')) {
        const spinner = document.createElement('span');
        spinner.className = 'blogibot-spinner';
        spinner.style.display = 'inline-block';
        spinner.style.width = '16px';
        spinner.style.height = '16px';
        spinner.style.marginLeft = '8px';
        spinner.innerHTML = `<svg width="16" height="16" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke="#007cba" stroke-width="5" stroke-linecap="round" stroke-dasharray="31.415, 31.415" transform="rotate(0 25 25)"><animateTransform attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="1s" repeatCount="indefinite"/></circle></svg>`;
        btn.appendChild(spinner);
    }
}

function removeSpinner(btn) {
    const spinner = btn.querySelector('.blogibot-spinner');
    if (spinner) spinner.remove();
}

function fetchNow(category, btn) {
    let apiKey = blog82aiApiData.api_key;
    let domain = blog82aiApiData.domain;

    if (!apiKey) {
        displayMessage('Please set your API Key first from settings.', 'error');
        if (btn) {
            btn.disabled = false;
            removeSpinner(btn);
        }
        return;
    }
    if (!domain) {
        displayMessage('Please set your Domain Name first from settings.', 'error');
        if (btn) {
            btn.disabled = false;
            removeSpinner(btn);
        }
        return;
    }
    displayMessage('Fetching from API...', 'info');
    fetch(blog82aiApiData.api_base_url + '/generate-blog', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            api_key: apiKey,
            domain: domain,
            category: category,
            schedule_id: 'manual_' + Date.now()
        })
    })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'error') {
                displayMessage(data.message || 'An error occurred while fetching the blog.', 'error');
                if (btn) {
                    btn.disabled = false;
                    removeSpinner(btn);
                }
                return;
            }
            return fetch(blog82aiApiData.rest_url.replace('blogibot/v1', 'blog82ai/v1'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': blog82aiApiData.rest_nonce
                },
                body: JSON.stringify({
                    title: data.title,
                    content: data.content,
                    category: category,
                    meta_title: data.meta_title,
                    meta_description: data.meta_description,
                    tags: data.tags, // <-- send tags to backend
                    focus_keywords: data.focus_keywords, // <-- send focus keywords to backend
                    featured_snippet: data.featured_snippet // <-- send featured snippet if needed
                })
            });
        })
        .then(res => res ? res.json() : null)
        .then(result => {
            if (result) {
                displayMessage(result.message || 'Blog created successfully', 'success');
            }
            if (btn) {
                btn.disabled = false;
                removeSpinner(btn);
            }
        })
        .catch(err => {
            displayMessage('Something went wrong.', 'error');
            if (btn) {
                btn.disabled = false;
                removeSpinner(btn);
            }
        });
}

function scheduleBlogViaAjax(category, date, runTime, callback) {
    fetch(ajaxurl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=blog82ai_schedule_blog&category=${encodeURIComponent(category)}&date=${encodeURIComponent(date)}&schedule_run_time=${encodeURIComponent(runTime)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
    })
    .then(res => res.json())
    .then(data => {
        if (callback) callback(data);
    })
    .catch(() => {
        if (callback) callback({ success: false, data: { message: 'AJAX error.' } });
    });
}

function displayMessage(message, type) {
    // Remove any existing notices
    document.querySelectorAll('.wrap .notice').forEach(n => n.remove());
    const alertBox = document.createElement('div');
    alertBox.className = `notice notice-${type} is-dismissible`;
    alertBox.innerHTML = `<p>${message}</p>`;
    const dismissButton = document.createElement('button');
    dismissButton.type = 'button';
    dismissButton.className = 'notice-dismiss';
    dismissButton.innerHTML = '<span class="screen-reader-text">Dismiss this notice.</span>';
    dismissButton.onclick = () => alertBox.remove();
    alertBox.appendChild(dismissButton);
    document.querySelector('.wrap').prepend(alertBox);
}

// Helper to attach AJAX events to new schedule row
function attachScheduleRowEvents(row) {
    // Resume
    row.querySelectorAll('a[data-resume-id]').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            btn.disabled = true;
            addSpinner(btn);
            const scheduleId = btn.getAttribute('data-resume-id');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blog82ai_resume_schedule&schedule_id=${encodeURIComponent(scheduleId)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    reloadScheduleTable(); // Only reload, do not update cells manually
                    displayMessage(data.data.message, 'success');
                } else {
                    displayMessage(data.data.message || 'Failed to resume.', 'error');
                }
                btn.disabled = false;
                removeSpinner(btn);
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                btn.disabled = false;
                removeSpinner(btn);
            });
        });
    });
    // Pause
    row.querySelectorAll('a[data-pause-id]').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            btn.disabled = true;
            addSpinner(btn);
            const scheduleId = btn.getAttribute('data-pause-id');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blog82ai_pause_schedule&schedule_id=${encodeURIComponent(scheduleId)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    reloadScheduleTable(); // Only reload, do not update cells manually
                    displayMessage(data.data.message, 'success');
                } else {
                    displayMessage(data.data.message || 'Failed to pause.', 'error');
                }
                btn.disabled = false;
                removeSpinner(btn);
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                btn.disabled = false;
                removeSpinner(btn);
            });
        });
    });
    // Delete
    row.querySelectorAll('a[data-delete-id]').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            btn.disabled = true;
            addSpinner(btn);
            const scheduleId = btn.getAttribute('data-delete-id');
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=blog82ai_delete_schedule&schedule_id=${encodeURIComponent(scheduleId)}&security=${encodeURIComponent(blog82aiApiData.ajax_nonce)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const row = btn.closest('tr');
                    if (row) row.remove();
                    displayMessage(data.data.message, 'success');
                } else {
                    displayMessage(data.data.message || 'Failed to delete.', 'error');
                    btn.disabled = false;
                    removeSpinner(btn);
                }
            })
            .catch(() => {
                displayMessage('AJAX error.', 'error');
                btn.disabled = false;
                removeSpinner(btn);
            });
        });
    });
    // Fetch Now
    row.querySelectorAll('button[data-fetch-category]').forEach(function(btn) {
        btn.addEventListener('click', function () {
            btn.disabled = true;
            addSpinner(btn);
            fetchNow(btn.getAttribute('data-fetch-category'), btn);
        });
    });
}

// Reload schedule table body via AJAX
function reloadScheduleTable() {
    fetch(ajaxurl + '?action=blog82ai_get_schedules&security=' + encodeURIComponent(blog82aiApiData.ajax_nonce), {
        method: 'GET',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    .then(res => res.text())
    .then(html => {
        const tbody = document.querySelector('table.widefat tbody');
        if (tbody) tbody.innerHTML = html;
        // Re-attach row events
        tbody.querySelectorAll('tr').forEach(attachScheduleRowEvents);
    });
}
