<?php
/**
 * Admin page: Task Comms Portal
 */

function afb_render_comms_admin_page() {
    $tasks = get_posts([
        'post_type'      => 'afb_task',
        'posts_per_page' => -1,
        'meta_query'     => [
            [
                'key'     => 'asana_comms_token',
                'compare' => 'EXISTS',
            ]
        ],
        'orderby'        => 'date',
        'order'          => 'DESC'
    ]);
    ?>
    <div class="wrap">
        <h1>🗨️ Task Comms Portal</h1>
        <p class="description">Below are all tasks submitted via the form that have a public communication link enabled.</p>

        <?php if (empty($tasks)) : ?>
            <div class="notice notice-info"><p>No tasks found with communication tokens.</p></div>
        <?php else : ?>
            <table class="widefat fixed striped" style="margin-top: 1em;">
                <thead>
                    <tr>
                        <th>Request Name</th>
                        <th>Request Number</th>
                        <th>Comms URL</th>
                        <th>Created</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($tasks as $post): 
                        $task_gid = get_post_meta($post->ID, 'asana_task_gid', true);
                        $asana_url = "https://app.asana.com/api/1.0/tasks/{$task_gid}";
                        $asana_response = wp_remote_get($asana_url, [
                            'headers' => ['Authorization' => 'Bearer ' . get_option('asana_access_token')]
                        ]);

                        if (wp_remote_retrieve_response_code($asana_response) !== 200) {
                            continue; // Skip if task doesn't exist in Asana
                        }

                        $token = get_post_meta($post->ID, 'asana_comms_token', true);
                        $url = site_url('/task-comms/' . $token);
                        ?>
                        <tr data-task-post-id="<?= esc_attr($post->ID) ?>">
                            <td><?= esc_html($post->post_title) ?></td>
                            <td><?= esc_html($task_gid) ?></td>
                            <td><a href="<?= esc_url($url) ?>" target="_blank" class="text-blue-600 hover:underline"><?= esc_html($url) ?></a></td>
                            <td><?= esc_html(get_the_date('', $post)) ?></td>
                            <td><button class="delete-task-comms button-link text-red-600">Delete</button></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.delete-task-comms').forEach(button => {
            button.addEventListener('click', async () => {
                if (!confirm('Are you sure you want to delete this task communication entry?')) return;

                const row = button.closest('tr');
                const postId = row.dataset.taskPostId;

                const res = await fetch(ajaxurl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({
                        action: 'afb_delete_task_comms_entry',
                        post_id: postId
                    })
                });

                const json = await res.json();
                if (json.success) {
                    row.remove();
                } else {
                    alert('Failed to delete entry.');
                }
            });
        });
    });
    </script>
<?php
}
