<?php
// Load all projects from all PAT accounts
global $wpdb;
$account_table = $wpdb->prefix . 'asana_accounts';
$accounts = $wpdb->get_results("SELECT * FROM $account_table", ARRAY_A);

$projects = [];
foreach ($accounts as $account) {
    $pat = $account['pat'];
    $portfolio_gid = $account['portfolio_gid'] ?? null;
    $items = $portfolio_gid
        ? afb_get_portfolio_projects($portfolio_gid, $pat)
        : afb_fetch_asana('projects', $pat);
    foreach ($items as $project) {
        $projects[] = $project;
    }
}

// Load existing prefixes
$prefix_map = get_option('afb_project_prefix_map', []);
$prefix_lines = explode("\n", trim($prefix_map));
$prefixes = [];

// Support legacy string format (gid = prefix)
foreach ($prefix_lines as $line) {
    if (strpos($line, '=') !== false) {
        list($gid, $prefix) = array_map('trim', explode('=', $line, 2));
        $prefixes[$gid] = $prefix;
    }
}

// Handle form submission
if (!empty($_POST['afb_prefix_update'])) {
    $submitted = $_POST['prefixes'] ?? [];
    $cleaned = [];

    foreach ($submitted as $gid => $prefix) {
        $cleaned[sanitize_text_field($gid)] = sanitize_text_field($prefix);
    }

    $lines = [];
    foreach ($cleaned as $gid => $prefix) {
        if ($prefix !== '') {
            $lines[] = "$gid = $prefix";
        }
    }

    update_option('afb_project_prefix_map', implode("\n", $lines));
    echo '<div class="notice notice-success is-dismissible"><p>Prefixes saved successfully.</p></div>';
}
?>

<div class="wrap">
    <h1>Task Prefixes per Project</h1>
    <p class="description">Define custom prefixes for each Asana project. These prefixes will appear in the auto-generated <strong>Request Number</strong> on the frontend.</p>

    <form method="post">
        <input type="hidden" name="afb_prefix_update" value="1" />

        <table class="widefat fixed striped" style="margin-top: 1em; max-width: 800px;">
            <thead>
                <tr>
                    <th>Project</th>
                    <th style="width: 200px;">Task Prefix</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($projects as $project):
                    $gid = $project['gid'];
                    $name = $project['name'];
                    $prefix = $prefixes[$gid] ?? '';
                ?>
                    <tr>
                        <td><strong><?= esc_html($name) ?></strong></td>
                        <td>
                            <input type="text" name="prefixes[<?= esc_attr($gid) ?>]" value="<?= esc_attr($prefix) ?>" class="regular-text" style="width: 100%;" />
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <p style="margin-top: 1em;">
            <button type="submit" class="button button-primary">Save Prefixes</button>
        </p>
    </form>
</div>
