<?php
/* ──────────────────────────────────────────────────────────────
 *  includes/api.php – Asana REST helpers
 * ──────────────────────────────────────────────────────────── */

require_once __DIR__ . '/security.php';

/*--------------------------------------------------------------*
 * 1. LOW-LEVEL HTTP WRAPPER                                     *
 *--------------------------------------------------------------*/

/**
 * Build Authorization headers from a PAT.
 */
function afb_get_asana_headers( $pat = null ) {

    /* 1) guard-rail */
    if ( empty( $pat ) ) {
        error_log( '❌ afb_get_asana_headers: PAT missing.' );
        return [];                           // caller will see empty headers
    }

    /* 2) decrypt if stored encrypted */
    $decrypted  = afb_decrypt( $pat );
    $auth_token = $decrypted ?: $pat;       // use decrypted or raw

    /* 3) return headers */
    return [
        'Authorization: Bearer ' . $auth_token,
        'Content-Type: application/json',
    ];
}


/**
 * Perform a GET request to the Asana API.
 *
 * @param string $endpoint Asana API endpoint.
 * @param string|null $pat Encrypted PAT (optional).
 * @return array|null Decoded response or null on failure.
 */
function afb_fetch_asana($endpoint, $pat = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://app.asana.com/api/1.0/' . ltrim($endpoint, '/'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, afb_get_asana_headers($pat));

    $response  = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $GLOBALS['afb_last_http_code'] = $http_code; 
    
    curl_close($ch);

    if ($http_code !== 200 || !$response) {
        error_log("❌ Asana API error {$http_code} for {$endpoint}");
        return false;
    }

    $data = json_decode($response, true);
    return $data['data'] ?? null;
}


/*--------------------------------------------------------------*
 * 2. PROJECT LIST HELPERS                                       *
 *--------------------------------------------------------------*/

/**
 * Get all projects for a given PAT and (optionally) a portfolio.
 */
function afb_get_all_projects($pat = null, $portfolio_gid = null) {
    $portfolio_gid = $portfolio_gid ?: get_option('afb_portfolio_gid');
    if ($portfolio_gid) {
        return afb_get_portfolio_projects($portfolio_gid, $pat);
    }
    return afb_fetch_asana('projects', $pat) ?: [];
}

/**
 * Get projects from a specific portfolio.
 */
function afb_get_portfolio_projects($portfolio_gid, $pat = null) {
    $items = afb_fetch_asana("portfolios/{$portfolio_gid}/items", $pat);
    if (!is_array($items)) return [];

    return array_values(array_filter($items, function ($item) {
        return ($item['resource_type'] ?? '') === 'project';
    }));
}


/*--------------------------------------------------------------*
 * 3. OTHER READ-ONLY HELPERS                                    *
 *--------------------------------------------------------------*/

/**
 * Get custom fields for a project.
 */
function afb_get_project_fields($project_id, $pat = null) {
    return afb_fetch_asana("projects/{$project_id}/custom_field_settings?opt_expand=custom_field", $pat) ?: [];
}

/**
 * Get sections for a project.
 */
function afb_get_project_sections($project_id, $pat = null) {
    return afb_fetch_asana("projects/{$project_id}/sections", $pat) ?: [];
}

/**
 * Get Asana users for the account.
 */
function afb_get_asana_users($pat = null) {
    return afb_fetch_asana('users', $pat) ?: [];
}

/**
 * Get full project info.
 */
function afb_get_project($project_id, $pat = null) {
    return afb_fetch_asana("projects/{$project_id}", $pat) ?: null;
}

/**
 * Get portfolio info.
 */
function afb_get_portfolio($portfolio_id, $pat = null) {
    return afb_fetch_asana("portfolios/{$portfolio_id}", $pat) ?: null;
}


/*--------------------------------------------------------------*
 * 4. CONNECTION TEST                                            *
 *--------------------------------------------------------------*/

/**
 * Test if a PAT is valid by requesting user info.
 */
function afb_check_asana_connection($pat = null) {
    $me = afb_fetch_asana('users/me', $pat);
    if (!$me) {
        return [
            'success' => false,
            'message' => '❌ Unable to connect to Asana. Please check your API token.',
        ];
    }

    $project_id = get_option('afb_default_project_id');
    $project = $project_id ? afb_get_project($project_id, $pat) : null;

    $project_txt = $project
        ? '📁 Default Project: <strong>' . esc_html($project['name']) . '</strong>'
        : ($project_id
            ? '⚠️ Could not fetch project details for ID: <code>' . esc_html($project_id) . '</code>'
            : '');

    return [
        'success' => true,
        'message' => '✅ Connected to Asana as <strong>' . esc_html($me['name']) . '</strong> (' . esc_html($me['email']) . ')<br>' . $project_txt,
        'user'    => $me,
        'project' => $project,
    ];
}

function afb_last_http_code() {
    return $GLOBALS['afb_last_http_code'] ?? null;
}
