<?php
// Check admin permission
if (!current_user_can('manage_options')) {
    wp_die('Unauthorized');
}

// Initialize save tracker
$settings_saved = false;

global $wpdb;
$account_table = $wpdb->prefix . 'asana_accounts';
$accounts = $wpdb->get_results("SELECT * FROM $account_table ORDER BY active DESC, id DESC", ARRAY_A);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['afb_save_multi_home'])) {
    check_admin_referer('afb_save_multi_home_settings');

    $known_account_ids = isset($_POST['multi_home_accounts'])
        ? array_map('absint', (array) $_POST['multi_home_accounts'])
        : [];
    $posted_map = isset($_POST['multi_home_projects_by_account']) && is_array($_POST['multi_home_projects_by_account'])
        ? $_POST['multi_home_projects_by_account']
        : [];

    $settings_by_account = [];
    foreach ($known_account_ids as $account_id) {
        if ($account_id <= 0) {
            continue;
        }

        $selected = isset($posted_map[$account_id]) && is_array($posted_map[$account_id])
            ? $posted_map[$account_id]
            : [];

        $selected = array_values(array_filter(array_map('sanitize_text_field', $selected)));
        $settings_by_account[(string) $account_id] = $selected;
    }

    update_option('afb_multi_home_projects_by_account', $settings_by_account);
    $settings_saved = true;
}

// Load existing per-account selections. Keep legacy global option for backward compatibility in runtime code.
$saved_by_account = get_option('afb_multi_home_projects_by_account', []);
if (!is_array($saved_by_account)) {
    $saved_by_account = [];
}
$legacy_multi_home = get_option('afb_multi_home_projects', []);
if (!is_array($legacy_multi_home)) {
    $legacy_multi_home = [];
}

$projects_by_account = [];
foreach ($accounts as $account) {
    $account_id = (int) ($account['id'] ?? 0);
    if ($account_id <= 0) {
        continue;
    }

    $pat = $account['pat'];
    $portfolio_gid = trim((string) ($account['portfolio_gid'] ?? ''));
    $projects = $portfolio_gid
        ? afb_get_portfolio_projects($portfolio_gid, $pat)
        : afb_fetch_asana('projects', $pat);

    if (!is_array($projects)) {
        $projects = [];
    }

    $seen = [];
    $normalized = [];
    foreach ($projects as $project) {
        $gid = sanitize_text_field((string) ($project['gid'] ?? ''));
        if ($gid === '' || isset($seen[$gid])) {
            continue;
        }

        $seen[$gid] = true;
        $normalized[] = [
            'gid'  => $gid,
            'name' => sanitize_text_field((string) ($project['name'] ?? $gid)),
        ];
    }

    usort($normalized, static function ($a, $b) {
        return strcasecmp((string) ($a['name'] ?? ''), (string) ($b['name'] ?? ''));
    });

    $projects_by_account[$account_id] = $normalized;
}
?>

<div class="wrap">
    <h1 class="text-2xl font-bold mb-6">Multi-Home Settings</h1>

    <!-- ✅ Success Notice -->
    <?php if ($settings_saved): ?>
        <div class="notice notice-success is-dismissible" style="margin-bottom: 20px;">
            <p><strong>Settings saved successfully.</strong></p>
        </div>
    <?php endif; ?>

    <!-- ✅ Form -->
    <form method="post">
        <input type="hidden" name="afb_save_multi_home" value="1">
        <?php wp_nonce_field('afb_save_multi_home_settings'); ?>

        <?php if (!empty($accounts)) : ?>
            <table class="widefat striped" style="max-width: 1200px;">
                <thead>
                    <tr>
                        <th style="width: 28%;">PAT Account</th>
                        <th>Secondary Projects (for this account only)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($accounts as $account) : ?>
                        <?php
                        $account_id = (int) ($account['id'] ?? 0);
                        if ($account_id <= 0) {
                            continue;
                        }

                        $account_label = sanitize_text_field((string) ($account['label'] ?? ''));
                        if ($account_label === '') {
                            $account_label = 'Unnamed Account';
                        }

                        $is_active = !empty($account['active']);
                        $account_projects = $projects_by_account[$account_id] ?? [];
                        $selected_projects = [];
                        if (isset($saved_by_account[(string) $account_id]) && is_array($saved_by_account[(string) $account_id])) {
                            $selected_projects = $saved_by_account[(string) $account_id];
                        } elseif (!empty($legacy_multi_home)) {
                            // First-run bridge from old global option to per-account UI.
                            $selected_projects = $legacy_multi_home;
                        }
                        ?>
                        <tr>
                            <td>
                                <input type="hidden" name="multi_home_accounts[]" value="<?= esc_attr($account_id); ?>">
                                <strong><?= esc_html($account_label); ?></strong>
                                <div class="description">ID: <?= esc_html((string) $account_id); ?><?php if (!$is_active) : ?> · Inactive<?php endif; ?></div>
                            </td>
                            <td>
                                <?php if (!empty($account_projects)) : ?>
                                    <select
                                        name="multi_home_projects_by_account[<?= esc_attr($account_id); ?>][]"
                                        multiple
                                        style="width: 100%; max-width: 740px; height: 220px;"
                                    >
                                        <?php foreach ($account_projects as $project) : ?>
                                            <?php $gid = (string) ($project['gid'] ?? ''); ?>
                                            <option value="<?= esc_attr($gid); ?>" <?= selected(true, in_array($gid, $selected_projects, true), false); ?>>
                                                <?= esc_html((string) ($project['name'] ?? $gid)); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php else : ?>
                                    <em>No projects found for this account.</em>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <p class="description" style="margin-top: 10px;">
                Hold CTRL (Windows) or CMD (Mac) to select multiple projects. Tasks will be multi-homed into the selected projects for the PAT account that owns the selected primary project.
            </p>
        <?php else : ?>
            <p>No Asana accounts found. Add an account first.</p>
        <?php endif; ?>

        <?php submit_button('Save Settings'); ?>
    </form>
</div>
