<?php
// task-comms/rest-refresh-dashboard.php
if (!defined('ABSPATH')) exit;

require_once AFB_PLUGIN_DIR . 'includes/lib/asana-client.php';
require_once __DIR__ . '/functions.php'; // ✅ correct path (same folder as this file)

/** Multi-path writer used by refresh */
if (!function_exists('afb__cache_paths_for_token')) {
  function afb__cache_paths_for_token($tok) {
    $root = trailingslashit(AFB_PLUGIN_DIR);
    return array_unique([
      $root . 'cache/tasks-summary-' . $tok . '.json',
      $root . 'includes/cache/tasks-summary-' . $tok . '.json',
      $root . 'includes/task-comms/cache/tasks-summary-' . $tok . '.json',
    ]);
  }
}

add_action('rest_api_init', function () {
  register_rest_route('afb/v1', '/refresh-dashboard', [
    'methods'  => 'GET',
    'callback' => 'afb_rest_refresh_dashboard',
    'permission_callback' => '__return_true',
  ]);
});

function afb_rest_refresh_dashboard(WP_REST_Request $req) {
  $token = sanitize_text_field($req->get_param('token') ?? '');
  if ($token === '') return new WP_REST_Response(['ok'=>false,'error'=>'Missing token'], 400);

  $task_gid = afb_get_task_id_by_token($token);
  if (!$task_gid) return new WP_REST_Response(['ok'=>false,'error'=>'Unknown or expired token'], 404);

  // Resolve a PAT that can read this task
  global $wpdb;
  $acctTbl  = $wpdb->prefix . 'asana_accounts';
  $accounts = (array) $wpdb->get_results("SELECT * FROM $acctTbl ORDER BY id DESC", ARRAY_A);
  if (!$accounts) return new WP_REST_Response(['ok'=>false,'error'=>'No Asana accounts configured'], 403);

  $pat  = '';
  $task = [];
  $opt  = implode(',', [
    'gid','name','notes','completed','start_on','due_on','created_at','modified_at',
    'assignee.name','projects.gid','projects.name','followers.name',
    'custom_fields.gid','custom_fields.name','custom_fields.type',
    'custom_fields.text_value','custom_fields.number_value',
    'custom_fields.enum_value.name','custom_fields.multi_enum_values.name'
  ]);
  $task_url = "https://app.asana.com/api/1.0/tasks/{$task_gid}";

  foreach ($accounts as $acc) {
    $token_pat = afb_decrypt($acc['pat']); if (!$token_pat) continue;
    $probe = afb_asana_request('GET', $task_url.'?opt_fields='.$opt, $token_pat);
    if ((int)($probe['code'] ?? 0) === 200) {
      $pat  = $token_pat;
      $task = json_decode($probe['body'] ?? '', true)['data'] ?? [];
      break;
    }
  }
  if ($pat === '') return new WP_REST_Response(['ok'=>false,'error'=>'No PAT can access task'], 403);

  // Subtasks (paged)
  $subs = [];
  $sf   = urlencode('gid,name,completed,start_on,due_on,resource_subtype,assignee.name');
  $url  = "https://app.asana.com/api/1.0/tasks/{$task_gid}/subtasks?opt_fields={$sf}&limit=100";
  while ($url) {
    $sr   = afb_asana_request('GET', $url, $pat);
    $body = json_decode($sr['body'] ?? '', true);
    foreach (($body['data'] ?? []) as $row) {
      $subs[] = [
        'gid' => $row['gid'] ?? null,
        'name' => $row['name'] ?? '(No name)',
        'completed' => (bool)($row['completed'] ?? false),
        'start_on'  => $row['start_on'] ?? null,
        'due_on'    => $row['due_on'] ?? null,
        'resource_subtype' => $row['resource_subtype'] ?? 'default_task',
        'assignee'  => ['name' => $row['assignee']['name'] ?? 'Unassigned', 'photo' => null],
      ];
    }
    $url = $body['next_page']['uri'] ?? null;
  }

  // Write to ALL cache paths atomically
  $payload = wp_json_encode(['task_gid'=>$task_gid, 'parent'=>$task, 'subtasks'=>$subs], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  $written = [];
  foreach (afb__cache_paths_for_token($token) as $p) {
    $dir = dirname($p);
    if (!file_exists($dir)) wp_mkdir_p($dir);
    $tmp = $p . '.tmp';
    $ok  = (@file_put_contents($tmp, $payload, LOCK_EX) !== false && @rename($tmp, $p));
    $written[] = ['path'=>$p, 'ok'=>$ok ? true : false];
  }

  if (function_exists('afb_log')) {
    afb_log(['where'=>'rest:refresh-dashboard', 'token'=>$token, 'task_gid'=>$task_gid, 'written'=>$written], 'afb-debug.log');
  }

  return new WP_REST_Response(['ok'=>true, 'token'=>$token, 'task_gid'=>$task_gid, 'written'=>$written], 200);
}
