<?php
if (!defined('ABSPATH')) exit;

/**
 * 🗑 Delete a single completed task.
 * This is called by the dispatcher *after* it has already loaded the task.
 *
 * Wrapped in `function_exists()` so we don’t get redeclaration errors if the
 * file is included more than once.
 */
if (!function_exists('asana_automator_delete_completed_tasks')) {
    function asana_automator_delete_completed_tasks($config, $token, $task = null) {

        $log_file = WP_CONTENT_DIR . '/custom-debug.log';

        if (empty($task) || empty($task['gid'])) {
            file_put_contents($log_file, "⚠️ Delete handler called without task data.\n", FILE_APPEND);
            return;
        }

        $task_gid   = $task['gid'];
        $task_name  = $task['name'] ?? '(unnamed)';
        $completed  = $task['completed'] ?? false;

        file_put_contents(
            $log_file,
            "🧪 Delete handler: task {$task_gid} ({$task_name}) completed = " .
            ($completed ? 'YES' : 'NO') . "\n",
            FILE_APPEND
        );

        if (!$completed) {
            return; // Nothing to do
        }

        $del = wp_remote_request(
            "https://app.asana.com/api/1.0/tasks/{$task_gid}",
            [
                'method'  => 'DELETE',
                'headers' => ['Authorization' => 'Bearer ' . $token],
            ]
        );

        if (is_wp_error($del)) {
            file_put_contents(
                $log_file,
                "❌ Failed to delete task {$task_gid} ({$task_name}): " .
                $del->get_error_message() . "\n",
                FILE_APPEND
            );
        } else {
            $code = wp_remote_retrieve_response_code($del);
            file_put_contents(
                $log_file,
                "✅ Deleted task {$task_gid} ({$task_name}) — HTTP {$code}\n",
                FILE_APPEND
            );
        }
    }
}
