<?php
// ╭──────────────────────────────────────────────────────────╮
// │ admin/general-settings.php                               │
// ╰──────────────────────────────────────────────────────────╯

// 🔧 Register general settings
function afb_register_general_settings() {

    /* ── SETTINGS ────────────────────────────────────────── */

    register_setting( 'afb_general_settings_group', 'afb_portfolio_gid' );

    /* ── SECTION HEADER ─────────────────────────────────── */

    add_settings_section(
        'afb_general_section',
        'General Plugin Settings',
        function () {
            echo '<p>Configure fallback settings and global task behaviour for the frontend form.</p>';
        },
        'asana-general-settings'
    );

    /* ── FIELD: PORTFOLIO FILTER ────────────────────────── */

    add_settings_field(
        'portfolio_gid',
        'Filter by Portfolio (optional)',
        function () {
            $value = esc_attr( get_option( 'afb_portfolio_gid', '' ) );
            echo "<input type='text' name='afb_portfolio_gid' value='$value' class='regular-text' />";
            echo '<p class="description">Paste the Portfolio GID to limit project lists to that portfolio. Leave blank to show all projects.</p>';
        },
        'asana-general-settings',
        'afb_general_section'
    );
}
add_action( 'admin_init', 'afb_register_general_settings' );

/* ╭─────────────────────────────────────────────────────────╮
   │ Show a success notice with the resolved project /       │
   │ portfolio names after the user clicks “Save Changes”.   │
   ╰─────────────────────────────────────────────────────────╯ */
function afb_general_settings_saved_notice() {
    if ( empty( $_GET['settings-updated'] ) ) return;

    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    if ( ! $screen || $screen->id !== 'asana-form-builder_page_asana-general-settings' ) return;

    $proj_id = get_option( 'afb_default_project_id' );
    $port_id = get_option( 'afb_portfolio_gid' );

    $proj_name = 'None set';
    if ( $proj_id ) {
        $proj = afb_get_project( $proj_id );
        $proj_name = $proj['name'] ?? "Unknown ({$proj_id})";
    }

    $port_name = 'None set';
    if ( $port_id ) {
        $port = afb_get_portfolio( $port_id );
        $port_name = $port['name'] ?? "Unknown ({$port_id})";
    }

    echo '<div class="notice notice-success is-dismissible"><p>';
    echo '✅ Settings saved. ';
    echo 'Default Project: <strong>'  . esc_html( $proj_name ) . '</strong>';
    if ( $proj_id ) echo ' (<code>'   . esc_html( $proj_id  ) . '</code>)';
    echo ' &nbsp;|&nbsp; ';
    echo 'Portfolio Filter: <strong>' . esc_html( $port_name ) . '</strong>';
    if ( $port_id ) echo ' (<code>'   . esc_html( $port_id  ) . '</code>)';
    echo '</p></div>';
}
add_action( 'admin_notices', 'afb_general_settings_saved_notice' );
