<?php

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

if (!function_exists('asana_automator_get_pat_accounts')) {
    function asana_automator_get_pat_accounts(): array {
        static $cache = null;

        if ($cache !== null) {
            return $cache;
        }

        global $wpdb;

        $accounts = [];
        $table = isset($wpdb->prefix) ? $wpdb->prefix . 'asana_accounts' : '';

        if ($table !== '') {
            $table_exists = (string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
            if ($table_exists === $table) {
                $rows = $wpdb->get_results("SELECT * FROM {$table} ORDER BY id ASC", ARRAY_A);
                foreach ((array) $rows as $row) {
                    if (array_key_exists('active', $row) && (int) $row['active'] !== 1) {
                        continue;
                    }

                    $label = sanitize_text_field((string) ($row['label'] ?? ''));
                    $raw_token = (string) ($row['pat'] ?? '');
                    $token = function_exists('afb_decrypt') ? (string) afb_decrypt($raw_token) : $raw_token;
                    if ($token === '') {
                        $token = $raw_token;
                    }

                    if ($label !== '' && $token !== '') {
                        $accounts[$label] = $token;
                    }
                }
            }
        }

        $legacy_accounts = get_option('asana_pat_accounts', []);
        if (is_array($legacy_accounts)) {
            foreach ($legacy_accounts as $label => $token) {
                $label = sanitize_text_field((string) $label);
                $token = sanitize_text_field((string) $token);
                if ($label !== '' && $token !== '' && !isset($accounts[$label])) {
                    $accounts[$label] = $token;
                }
            }
        }

        $legacy_single = trim((string) get_option('asana_access_token', ''));
        if ($legacy_single !== '' && empty($accounts['Default PAT'])) {
            $accounts['Default PAT'] = $legacy_single;
        }

        $afb_legacy_single = trim((string) get_option('afb_asana_token', ''));
        if ($afb_legacy_single !== '' && empty($accounts['AFB Legacy PAT'])) {
            $accounts['AFB Legacy PAT'] = $afb_legacy_single;
        }

        $cache = $accounts;

        return $cache;
    }
}

if (!function_exists('asana_automator_get_pat_token')) {
    function asana_automator_get_pat_token(string $label = ''): string {
        $accounts = asana_automator_get_pat_accounts();

        if ($label !== '' && isset($accounts[$label])) {
            return (string) $accounts[$label];
        }

        if (empty($accounts)) {
            return '';
        }

        return (string) reset($accounts);
    }
}

if (!function_exists('asana_automator_get_workspace_gid')) {
    function asana_automator_get_workspace_gid(): string {
        return sanitize_text_field((string) get_option('asana_workspace_gid', ''));
    }
}

if (!function_exists('asana_automator_get_workspace_name')) {
    function asana_automator_get_workspace_name(): string {
        return sanitize_text_field((string) get_option('asana_workspace_name', ''));
    }
}

if (!function_exists('asana_automator_maybe_migrate_pat_accounts_to_afb_table')) {
    function asana_automator_maybe_migrate_pat_accounts_to_afb_table(): void {
        if (get_option('asana_automator_accounts_migrated_to_afb_table')) {
            return;
        }

        $legacy_accounts = get_option('asana_pat_accounts', []);
        if (!is_array($legacy_accounts) || empty($legacy_accounts)) {
            update_option('asana_automator_accounts_migrated_to_afb_table', 1, false);
            return;
        }

        global $wpdb;
        $table = isset($wpdb->prefix) ? $wpdb->prefix . 'asana_accounts' : '';
        if ($table === '') {
            return;
        }

        $table_exists = (string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
        if ($table_exists !== $table) {
            return;
        }

        $columns = array_map('strval', (array) $wpdb->get_col("SHOW COLUMNS FROM {$table}", 0));
        $existing_labels = array_map('strval', (array) $wpdb->get_col("SELECT label FROM {$table}"));

        foreach ($legacy_accounts as $label => $token) {
            $label = sanitize_text_field((string) $label);
            $token = sanitize_text_field((string) $token);

            if ($label === '' || $token === '' || in_array($label, $existing_labels, true)) {
                continue;
            }

            $stored_token = function_exists('afb_encrypt') ? (string) afb_encrypt($token) : $token;
            $row = [
                'label' => $label,
                'pat' => $stored_token,
            ];

            if (in_array('portfolio_gid', $columns, true)) {
                $row['portfolio_gid'] = '';
            }
            if (in_array('created_at', $columns, true)) {
                $row['created_at'] = current_time('mysql');
            }
            if (in_array('active', $columns, true)) {
                $row['active'] = 1;
            }

            $wpdb->insert($table, $row);
        }

        update_option('asana_automator_accounts_migrated_to_afb_table', 1, false);
    }
}