<?php
// includes/actions-delete-attachments.php

if (!defined('ABSPATH')) exit;

/**
 * Delete all file attachments from a completed task.
 * Used by both the cron dispatcher (polling) and the webhook handler (real-time).
 *
 * @param array  $config  Rule/webhook config (not used but kept for handler signature consistency).
 * @param string $token   Asana PAT.
 * @param array  $task    Task data array, must include 'gid' and 'completed'.
 */
function asana_automator_delete_attachments_on_complete($config, $token, $task) {
    if (empty($task['completed']) || empty($task['gid'])) return;

    $task_gid  = $task['gid'];
    $task_name = $task['name'] ?? '(unnamed)';
    $log_file  = WP_CONTENT_DIR . '/custom-debug.log';

    // Fetch all attachments for this task
    $res = wp_remote_get(
        "https://app.asana.com/api/1.0/attachments?parent={$task_gid}&opt_fields=gid,name,resource_type",
        ['headers' => ['Authorization' => 'Bearer ' . $token]]
    );

    if (is_wp_error($res)) {
        file_put_contents($log_file,
            date('c') . " ❌ Attachments fetch failed for {$task_gid}: " . $res->get_error_message() . "\n",
            FILE_APPEND);
        return;
    }

    $code = wp_remote_retrieve_response_code($res);
    if ($code !== 200) {
        file_put_contents($log_file,
            date('c') . " ❌ Attachments fetch HTTP {$code} for {$task_gid}\n",
            FILE_APPEND);
        return;
    }

    $attachments = json_decode(wp_remote_retrieve_body($res), true)['data'] ?? [];

    if (empty($attachments)) {
        file_put_contents($log_file,
            date('c') . " ℹ️ No attachments for task {$task_gid} ({$task_name})\n",
            FILE_APPEND);
        return;
    }

    file_put_contents($log_file,
        date('c') . " 🗑 Deleting " . count($attachments) . " attachment(s) for task {$task_gid} ({$task_name})\n",
        FILE_APPEND);

    foreach ($attachments as $attachment) {
        $att_gid  = $attachment['gid'];
        $att_name = $attachment['name'] ?? $att_gid;

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

        if (is_wp_error($del)) {
            file_put_contents($log_file,
                date('c') . " ❌ Delete attachment {$att_name} ({$att_gid}) failed: " . $del->get_error_message() . "\n",
                FILE_APPEND);
        } else {
            $del_code = wp_remote_retrieve_response_code($del);
            file_put_contents($log_file,
                date('c') . " ✅ Deleted attachment {$att_name} ({$att_gid}) — HTTP {$del_code}\n",
                FILE_APPEND);
        }
    }
}
