<?php

// 🔐 Frontend OAuth login initiator
add_action('init', function () {
    if (isset($_GET['asana_frontend_login'])) {
        $client_id     = get_option('asana_oauth_client_id');
        $redirect_uri  = 'https://asana.qh.digital/asana-oauth-callback/';
        $return_url    = isset($_GET['redirect_to']) ? esc_url_raw($_GET['redirect_to']) : home_url('/');
        $state_nonce   = wp_create_nonce('asana_oauth');

        $scope = implode(' ', [
            'attachments:write',
            'projects:read',
            'stories:read',
            'tasks:read',
            'tasks:write',
            'teams:read',
            'users:read',
            'workspaces:read'
        ]);

        $state = base64_encode(json_encode([
            'nonce'       => $state_nonce,
            'return_url'  => $return_url,
        ]));

        $auth_url = 'https://app.asana.com/-/oauth_authorize?' . http_build_query([
            'client_id'     => $client_id,
            'redirect_uri'  => $redirect_uri,
            'response_type' => 'code',
            'state'         => $state,
            'scope'         => $scope,
        ]);

        wp_redirect($auth_url);
        exit;
    }
});

// 🔁 OAuth callback processor
add_action('init', function () {
    if (!isset($_GET['code'], $_GET['state'])) return;

    $state_raw = json_decode(base64_decode($_GET['state']), true);
    if (empty($state_raw['nonce']) || empty($state_raw['return_url'])) {
        wp_die('Invalid OAuth state.');
    }

    if (!wp_verify_nonce($state_raw['nonce'], 'asana_oauth')) {
        wp_die('Invalid OAuth nonce.');
    }

    $client_id     = get_option('asana_oauth_client_id');
    $client_secret = get_option('asana_oauth_client_secret');
    $redirect_uri  = 'https://asana.qh.digital/asana-oauth-callback/';
    $code          = sanitize_text_field($_GET['code']);
    $return_url    = esc_url_raw($state_raw['return_url']);

    $response = wp_remote_post('https://app.asana.com/-/oauth_token', [
        'body' => [
            'grant_type'    => 'authorization_code',
            'client_id'     => $client_id,
            'client_secret' => $client_secret,
            'redirect_uri'  => $redirect_uri,
            'code'          => $code,
        ],
    ]);

    if (is_wp_error($response)) wp_die('OAuth token request failed.');
    $body = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($body['access_token'])) wp_die('No access token returned.');

    $user_response = wp_remote_get('https://app.asana.com/api/1.0/users/me', [
        'headers' => ['Authorization' => 'Bearer ' . $body['access_token']],
    ]);

    $user_data = json_decode(wp_remote_retrieve_body($user_response), true)['data'] ?? [];

    require_once plugin_dir_path(__FILE__) . '/security.php';
    $user_id = get_current_user_id();

    if ($user_id) {
        update_user_meta($user_id, 'asana_token_encrypted', afb_encrypt($body['access_token']));
        update_user_meta($user_id, 'asana_refresh_token_encrypted', afb_encrypt($body['refresh_token']));
        update_user_meta($user_id, 'asana_token_expires', time() + $body['expires_in']);
        update_user_meta($user_id, 'asana_user_info', json_encode($user_data));
    } else {
        session_start();
        $_SESSION['asana_token'] = $body['access_token'];
        $_SESSION['asana_user']  = $user_data;
    }

    wp_redirect($return_url);
    exit;
});
