<?php
/**
 * Dashboard page functionality.
 *
 * @package    WPFMJ
 * @subpackage WPFMJ/admin
 */

class WPFMJ_Dashboard {

    /**
     * Add menu page.
     */
    public function add_menu_page() {
        add_menu_page(
            __('Mailjet Automations', 'wpforms-mailjet-automation'),
            __('Mailjet Automations', 'wpforms-mailjet-automation'),
            'manage_options',
            'wpfmj-dashboard',
            array($this, 'render_dashboard'),
            'dashicons-email-alt',
            30
        );

        add_submenu_page(
            'wpfmj-dashboard',
            __('All Automations', 'wpforms-mailjet-automation'),
            __('All Automations', 'wpforms-mailjet-automation'),
            'manage_options',
            'wpfmj-dashboard',
            array($this, 'render_dashboard')
        );

        add_submenu_page(
            'wpfmj-dashboard',
            __('Add New Automation', 'wpforms-mailjet-automation'),
            __('Add New', 'wpforms-mailjet-automation'),
            'manage_options',
            'wpfmj-add-new',
            array($this, 'render_wizard')
        );
    }

    /**
     * Render dashboard page.
     */
    public function render_dashboard() {
        // Verify user has proper capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'wpforms-mailjet-automation'));
        }
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e('Mailjet Automations', 'wpforms-mailjet-automation'); ?></h1>
            <a href="<?php echo esc_url(admin_url('admin.php?page=wpfmj-add-new')); ?>" class="page-title-action">
                <?php esc_html_e('Add New', 'wpforms-mailjet-automation'); ?>
            </a>
            <hr class="wp-header-end">

            <div id="wpfmj-dashboard-root"></div>

            <div id="wpfmj-dashboard-loading" style="padding: 40px; text-align: center;">
                <span class="spinner is-active" style="float: none; margin: 0 auto;"></span>
                <p><?php esc_html_e('Loading automations...', 'wpforms-mailjet-automation'); ?></p>
            </div>

            <script type="text/javascript">
                // Render dashboard table
                jQuery(document).ready(function($) {
                    function loadDashboard() {
                        $.ajax({
                            url: wpfmjData.ajaxUrl,
                            type: 'POST',
                            data: {
                                action: 'wpfmj_get_dashboard_data',
                                nonce: wpfmjData.ajaxNonce
                            },
                            success: function(response) {
                                $('#wpfmj-dashboard-loading').hide();
                                if (response.success) {
                                    renderTable(response.data);
                                } else {
                                    var errorMessage = $('<div>').text(response.data).html();
                                    $('#wpfmj-dashboard-root').html('<div class="notice notice-error"><p>' + errorMessage + '</p></div>');
                                }
                            },
                            error: function() {
                                $('#wpfmj-dashboard-loading').hide();
                                $('#wpfmj-dashboard-root').html('<div class="notice notice-error"><p>Failed to load automations.</p></div>');
                            }
                        });
                    }

                    function renderTable(automations) {
                        if (automations.length === 0) {
                            $('#wpfmj-dashboard-root').html(
                                '<div class="wpfmj-empty-state" style="text-align: center; padding: 60px 20px;">' +
                                '<p style="font-size: 18px; color: #666; margin-bottom: 20px;">No automations yet. Create your first automation to get started!</p>' +
                                '<a href="' + wpfmjData.ajaxUrl.replace('admin-ajax.php', 'admin.php?page=wpfmj-add-new') + '" class="button button-primary button-large">Create Automation</a>' +
                                '</div>'
                            );
                            return;
                        }

                        var html = '<table class="wp-list-table widefat fixed striped">';
                        html += '<thead><tr>';
                        html += '<th>Title</th>';
                        html += '<th>Form</th>';
                        html += '<th>Status</th>';
                        html += '<th>Errors</th>';
                        html += '<th>Created</th>';
                        html += '<th>Actions</th>';
                        html += '</tr></thead><tbody>';

                        automations.forEach(function(automation) {
                            var statusClass = automation.status === 'publish' ? 'active' : 'inactive';
                            var statusText = automation.status === 'publish' ? 'Active' : 'Paused';
                            var errorBadge = automation.error_count > 0 ? '<span class="wpfmj-error-badge">' + parseInt(automation.error_count) + '</span>' : '—';
                            
                            // Escape data for safe HTML output
                            var title = $('<div>').text(automation.title).html();
                            var formName = $('<div>').text(automation.form_name).html();
                            var automationId = parseInt(automation.id);

                            html += '<tr>';
                            html += '<td><strong>' + title + '</strong></td>';
                            html += '<td>' + formName + '</td>';
                            html += '<td><span class="wpfmj-status-badge wpfmj-status-' + statusClass + '">' + statusText + '</span></td>';
                            html += '<td>' + errorBadge + '</td>';
                            html += '<td>' + new Date(automation.created).toLocaleDateString() + '</td>';
                            html += '<td>';
                            html += '<a href="admin.php?page=wpfmj-add-new&edit=' + automationId + '" class="button button-small">Edit</a> ';
                            html += '<button class="button button-small wpfmj-toggle-btn" data-id="' + automationId + '" data-status="' + automation.status + '">' + (automation.status === 'publish' ? 'Pause' : 'Activate') + '</button> ';
                            html += '<button class="button button-small button-link-delete wpfmj-delete-btn" data-id="' + automationId + '">Delete</button>';
                            html += '</td>';
                            html += '</tr>';
                        });

                        html += '</tbody></table>';
                        $('#wpfmj-dashboard-root').html(html);
                    }

                    // Use event delegation to prevent memory leaks
                    // Unbind previous handlers before binding new ones
                    $('#wpfmj-dashboard-root').off('click', '.wpfmj-toggle-btn').on('click', '.wpfmj-toggle-btn', function() {
                        var btn = $(this);
                        var id = btn.data('id');
                        toggleAutomation(id, btn);
                    });

                    $('#wpfmj-dashboard-root').off('click', '.wpfmj-delete-btn').on('click', '.wpfmj-delete-btn', function() {
                        var id = $(this).data('id');
                        if (confirm('Are you sure you want to delete this automation? This cannot be undone.')) {
                            deleteAutomation(id);
                        }
                    });

                    function toggleAutomation(id, btn) {
                        btn.prop('disabled', true);
                        $.ajax({
                            url: wpfmjData.ajaxUrl,
                            type: 'POST',
                            data: {
                                action: 'wpfmj_toggle_automation',
                                nonce: wpfmjData.ajaxNonce,
                                id: id
                            },
                            success: function(response) {
                                if (response.success) {
                                    loadDashboard();
                                } else {
                                    var errorMessage = $('<div>').text(response.data).html();
                                    alert('Error: ' + errorMessage);
                                    btn.prop('disabled', false);
                                }
                            },
                            error: function() {
                                alert('Failed to toggle automation');
                                btn.prop('disabled', false);
                            }
                        });
                    }

                    function deleteAutomation(id) {
                        $.ajax({
                            url: wpfmjData.ajaxUrl,
                            type: 'POST',
                            data: {
                                action: 'wpfmj_delete_automation',
                                nonce: wpfmjData.ajaxNonce,
                                id: id
                            },
                            success: function(response) {
                                if (response.success) {
                                    loadDashboard();
                                } else {
                                    var errorMessage = $('<div>').text(response.data).html();
                                    alert('Error: ' + errorMessage);
                                }
                            },
                            error: function() {
                                alert('Failed to delete automation');
                            }
                        });
                    }

                    loadDashboard();
                });
            </script>
        </div>
        <?php
    }

    /**
     * Render wizard page.
     */
    public function render_wizard() {
        // Verify user has proper capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'wpforms-mailjet-automation'));
        }

        $edit_id = isset($_GET['edit']) ? intval($_GET['edit']) : 0;

        // If editing, verify the post exists and user can edit it
        if ($edit_id) {
            $post = get_post($edit_id);
            if (!$post || $post->post_type !== 'wpfmj_automation') {
                wp_die(__('Invalid automation ID.', 'wpforms-mailjet-automation'));
            }
        }

        $page_title = $edit_id ? __('Edit Automation', 'wpforms-mailjet-automation') : __('Add New Automation', 'wpforms-mailjet-automation');
        ?>
        <div class="wrap">
            <h1><?php echo esc_html($page_title); ?></h1>
            <div id="wpfmj-wizard-root"></div>
        </div>
        <?php
    }
}
