<?php
// task-comms/ajax-upload.php
if (!defined('ABSPATH')) exit;

require_once AFB_PLUGIN_DIR . 'task-comms/functions.php';

add_action('wp_ajax_afb_guest_upload',        'afb_guest_upload');
add_action('wp_ajax_nopriv_afb_guest_upload', 'afb_guest_upload');

function afb_guest_upload() {
    // ---- inputs ------------------------------------------------------------
    // Accept token via POST (hidden input) OR query var as fallback
    $token = sanitize_text_field($_POST['dashboard_upload_token'] ?? '');
    if ($token === '' && isset($_GET['asana_comms_token'])) {
        $token = sanitize_text_field($_GET['asana_comms_token']);
    }
    if ($token === '') {
        wp_send_json_error(['message' => 'Missing upload token.']);
    }

    $task_gid = afb_get_task_id_by_token($token);
    if (!$task_gid || !ctype_digit($task_gid)) {
        wp_send_json_error(['message' => 'Invalid or expired token.']);
    }

    if (empty($_FILES['upload_file']) || !is_uploaded_file($_FILES['upload_file']['tmp_name'])) {
        wp_send_json_error(['message' => 'No file uploaded.']);
    }

    // Optional guest name to include in label comment (add a hidden input if you like)
    $guest_name = trim((string)($_POST['guest_name'] ?? ''));

    // ---- pick a PAT that can see the task ---------------------------------
    $pat = (function_exists('afb_pick_pat_for_task') ? afb_pick_pat_for_task($task_gid) : null)
        ?: (function_exists('afb_fallback_pat') ? afb_fallback_pat() : null);

    if (!$pat) {
        wp_send_json_error(['message' => 'No PAT available for this task.']);
    }

    // ---- prepare upload ----------------------------------------------------
    $file     = $_FILES['upload_file'];
    $filename = sanitize_file_name($file['name']);
    $mtype    = function_exists('mime_content_type') ? (mime_content_type($file['tmp_name']) ?: 'application/octet-stream') : ($file['type'] ?: 'application/octet-stream');

    // ---- Asana multipart (must use cURL) ----------------------------------
    $endpoint = "https://app.asana.com/api/1.0/tasks/{$task_gid}/attachments";

    if (!function_exists('curl_init')) {
        wp_send_json_error(['message' => 'Server missing cURL extension for uploads.']);
    }

    $ch = curl_init($endpoint);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ["Authorization: Bearer {$pat}"],
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => [
            'file' => new CURLFile($file['tmp_name'], $mtype, $filename),
        ],
        CURLOPT_TIMEOUT        => 90,
    ]);

    $resp      = curl_exec($ch);
    $status    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_err  = curl_error($ch);
    curl_close($ch);

    $data = json_decode($resp, true);

    // ---- success path ------------------------------------------------------
    if ($status >= 200 && $status < 300 && !empty($data['data']['gid'])) {
        // Post a label comment (non-blocking; failure won’t affect success)
        $label = $guest_name ? "Guest upload by {$guest_name}: {$filename}" : "Guest upload: {$filename}";
        if (function_exists('afb_add_asana_comment')) {
            $c = @afb_add_asana_comment($task_gid, $label, $pat);
            if (empty($c['success'])) {
                // Log, but do not fail the upload
                if (function_exists('afb_debug_log')) {
                    afb_debug_log("Label comment failed ({$task_gid}): " . ($c['error'] ?? 'unknown'));
                }
            }
        }
        wp_send_json_success([
            'message'    => 'Uploaded.',
            'attachment' => $data['data'],
        ]);
    }

    // ---- error normalization ----------------------------------------------
    $asana_msg = isset($data['errors'][0]['message']) ? $data['errors'][0]['message'] : null;
    $message   = $asana_msg ?: ($curl_err ?: 'Asana upload failed.');

    wp_send_json_error([
        'message' => $message,
        'status'  => $status,
        'raw'     => $data ?: $resp,
    ]);
}
