<?php
global $wpdb;
$table = $wpdb->prefix . 'asana_accounts';

/*─────────────────────────────────────────────*
 * 1) LOAD ACTIVE ACCOUNTS
 *─────────────────────────────────────────────*/
$accounts = $wpdb->get_results(
    "SELECT * FROM $table WHERE active = 1",
    ARRAY_A
);

$selected_projects = get_option('afb_allowed_projects', []);
$selected_sections = get_option('afb_allowed_project_sections', []); // Keep this

$all_projects = [];
$seen           = [];

/*─────────────────────────────────────────────*
 * 2) LOOP ACCOUNTS → PROJECTS
 *─────────────────────────────────────────────*/
foreach ($accounts as $account) {

    /* -- PAT & META -- */
    $pat            = afb_decrypt($account['pat']);
    $portfolio_gid = $account['portfolio_gid'] ?? '';
    $label          = $account['label']            ?: 'Unnamed Account';


    /* -- 1st TRY – via portfolio (if supplied) -- */
    $projects = [];
    $api_code = null;

    if ($portfolio_gid) {
        $projects = afb_fetch_asana("portfolios/{$portfolio_gid}/items", $pat);
        $api_code = afb_last_http_code();   // helper added below
        afb_log("📦 Portfolio items: ".print_r($projects,true));
    }

    /* -- FALLBACK – all /projects if none returned -- */
    if (!$projects) {
        $projects = afb_fetch_asana('projects', $pat);
        $api_code = afb_last_http_code();
        afb_log("📦 Fallback /projects returned ".count($projects)." | HTTP {$api_code}");
    }

    /* -- Bail if API failed -- */
    if ($api_code !== 200) {
        afb_log("❌ Asana API error {$api_code} for {$label}");
        continue;
    }

    /* -- Build master list (dedup by gid) -- */
    foreach ($projects as $p) {
        if (($p['resource_type'] ?? '') !== 'project') continue;
        if (isset($seen[$p['gid']]))        continue;

        $p['__pat']    = base64_encode($pat);
        $p['__label'] = $label;
        $all_projects[]       = $p;
        $seen[$p['gid']] = true;
    }
}

/*─────────────────────────────────────────────*
 * 3) SAVE HANDLER
 *─────────────────────────────────────────────*/
if ( $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['afb_save_project_selector'] ) ) {
    check_admin_referer( 'afb_save_project_selector' );

    // 1) build fresh arrays from POST
    $posted_projects = isset( $_POST['afb_allowed_projects'] )
        ? array_map( 'sanitize_text_field', $_POST['afb_allowed_projects'] )
        : [];

    // The key here is to handle the sections array correctly.
    // afb_project_sections is an associative array, so we need to iterate and sanitize
    $posted_sections = [];
    if (isset($_POST['afb_project_sections']) && is_array($_POST['afb_project_sections'])) {
        foreach ($_POST['afb_project_sections'] as $project_gid => $section_gid) {
            $posted_sections[sanitize_text_field($project_gid)] = sanitize_text_field($section_gid);
        }
    }


    // 2) save to DB
    update_option( 'afb_allowed_projects',          $posted_projects );
    update_option( 'afb_allowed_project_sections', $posted_sections );

    // 3) refresh in-memory copies for this same render pass
    $selected_projects = $posted_projects;
    $selected_sections = $posted_sections; // Refresh this as well

    echo '<div class="notice notice-success is-dismissible"><p>✅ Project selection saved.</p></div>';
}



/*─────────────────────────────────────────────*
 * 4) RENDER PAGE
 *─────────────────────────────────────────────*/
?>
<div class="wrap">
    <h1>Select Allowed Asana Projects & Sections</h1>
    <p class="description">
        Projects below are pulled live from each active PAT.
        If you still see <em>No projects found</em>, check <code>wp-content/afb-debug.log</code> for the API result.
    </p>

<?php if ($all_projects): ?>
<form method="post">
    <input type="hidden" name="afb_save_project_selector" value="1">
    <table class="widefat striped" style="max-width:1000px">
        <thead><tr><th>Select</th><th>Project</th><th>Default Section</th></tr></thead>
        <tbody>
        <?php foreach ($all_projects as $p):
            $gid           = $p['gid'];
            $checked       = in_array($gid, $selected_projects, true) ? 'checked' : '';
            $pat_encoded = $p['__pat'];
            ?>
            <tr>
                <td><input type="checkbox" name="afb_allowed_projects[]" value="<?=esc_attr($gid)?>" <?=$checked?>></td>
                <td>
                    <?=esc_html($p['name'])?>
                    <span class="description" style="display:block;font-size:12px;color:#666">
                        from <?=esc_html($p['__label'])?>
                    </span>
                </td>
                <td class="section-cell"
                    data-gid="<?=esc_attr($gid)?>"
                    data-pat="<?=esc_attr($pat_encoded)?>">
                    <?php

if ($checked) {
    $decoded_pat = afb_decrypt(base64_decode($pat_encoded));
    $sections = afb_get_project_sections($gid, $decoded_pat);
    ?>
    <select name="afb_project_sections[<?= esc_attr($gid) ?>]" style="width:100%">
        <option value="">-- None --</option>
        <?php foreach ($sections as $s):
            // This is correctly selecting the saved section on initial load
            $selected = isset($selected_sections[$gid]) && $selected_sections[$gid] === $s['gid']; ?>
            <option value="<?= esc_attr($s['gid']) ?>" <?= $selected ? 'selected' : '' ?>>
                <?= esc_html($s['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
<?php } else {
    echo '<em>--</em>';
} ?>

                </td>
            </tr>
        <?php endforeach;?>
        </tbody>
    </table>
    <?php wp_nonce_field('afb_save_project_selector'); ?>
    <?php submit_button('Save Changes');?>
</form>
<?php else: ?>
    <div class="notice notice-warning">
        <p>No projects found across any PATs. Check the debug log for details.</p>
    </div>
<?php endif;?>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Pass selected sections data to JavaScript
    const selectedSections = <?= json_encode($selected_sections) ?>;

    // Function to update the section dropdown for a given row
    const updateSectionDropdown = async (row, isChecked) => {
        const cell = row.querySelector('.section-cell');
        const gid  = cell.dataset.gid;
        const pat  = atob(cell.dataset.pat);

        if (!isChecked) {
            cell.innerHTML = '<em>--</em>';
            return;
        }
        cell.innerHTML = '<em>Loading sections…</em>';

        const fd = new FormData();
        fd.append('action'      , 'afb_get_project_sections');
        fd.append('project_gid', gid);
        fd.append('pat'         , pat);

        try {
            const res = await fetch(ajaxurl, { method:'POST', body:fd });
            const js  = await res.json();
            if (!js.success || !js.data.length) {
                cell.innerHTML = '<em>(No Sections)</em>';
                return;
            }

            // Get the previously selected section for this project
            const previouslySelectedSection = selectedSections[gid] || '';

            cell.innerHTML = '<select name="afb_project_sections['+gid+']" style="width:100%">' +
                '<option value="" ' + (previouslySelectedSection === '' ? 'selected' : '') + '>-- None --</option>' +
                js.data.map(s=>`<option value="${s.gid}" ${s.gid === previouslySelectedSection ? 'selected' : ''}>${s.name}</option>`).join('') +
                '</select>';
        } catch(e) {
            cell.innerHTML='<em>Fetch error</em>';
            console.error(e);
        }
    };

    // 1. Attach event listener for checkbox changes
    document.querySelectorAll('input[name="afb_allowed_projects[]"]').forEach(cb => {
        cb.addEventListener('change', function () {
            const row = this.closest('tr');
            updateSectionDropdown(row, this.checked);
        });

        // 2. Initial load: If the checkbox is already checked, update its section dropdown
        // This ensures the correct section is displayed when the page first loads or after a save.
        if (cb.checked) {
            const row = cb.closest('tr');
            // This is crucial: Check if the select element already exists and has options.
            // If it does, and PHP has already rendered it correctly, we don't need to re-fetch.
            // However, if the PHP rendering somehow failed, or the JS overwrites it,
            // then we need to re-render. Given your description, it seems the JS
            // might be implicitly overwriting or the PHP isn't being reflected.
            // To be safe, we'll re-render via JS for checked items on load.
            updateSectionDropdown(row, true);
        }
    });
});
</script>