<?php
/**
 * admin/pages/form-urls-page.php
 * Renders the “Form URLs” admin screen.
 */

if (!current_user_can('manage_options')) {
    wp_die('You do not have permission to view this page.');
}

$selected = get_option('afb_allowed_projects', []);
?>
<div class="wrap">
    <h1>Public Form URLs</h1>

    <?php if (empty($selected)) : ?>
        <p>No projects selected yet. Go to <strong>Project Selector</strong> to enable some forms.</p>
    <?php else : ?>
        <p>Copy or click these links to open each project’s form:</p>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th>Project Name</th>
                    <th>Form URL</th>
                </tr>
            </thead>
            <tbody>
                <?php
                global $wpdb;
                $account_table = $wpdb->prefix . 'asana_accounts';
                $accounts = $wpdb->get_results("SELECT * FROM $account_table", ARRAY_A);

                foreach ($selected as $gid) {
                    $proj = null;

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

                        foreach ($projects as $p) {
                            if ($p['gid'] === $gid) {
                                $proj = $p;
                                break 2;
                            }
                        }
                    }

                    $name = $proj['name'] ?? $gid;
                    $url  = home_url("/asana-form/{$gid}/");
                    ?>
                    <tr>
                        <td><?php echo esc_html($name); ?></td>
                        <td>
                            <a href="<?php echo esc_url($url); ?>" target="_blank">
                                <?php echo esc_html($url); ?>
                            </a>
                        </td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
