<?php

require_once AFB_PLUGIN_DIR . 'includes/api.php'; // ✅ Use central API file

// 🧠 Save project field flow config
if (!empty($_POST['config_project_gid']) && isset($_POST['used_fields'])) {
    $gid = sanitize_text_field($_POST['config_project_gid']);
    $used_fields = array_map('sanitize_text_field', $_POST['used_fields']);
    $all_configs = get_option('afb_project_field_config', []);
    $all_configs[$gid]['used_fields'] = $used_fields;
    update_option('afb_project_field_config', $all_configs);

    echo '<div class="notice notice-success is-dismissible"><p>✅ Field configuration saved for this project.</p></div>';
}

add_action('admin_menu', 'afb_add_settings_page');
add_action('admin_init', 'afb_register_settings');

function afb_add_settings_page() {
    add_menu_page(
        'Asana Form Builder Settings',
        'Asana Forms',
        'manage_options',
        'asana-form-builder',
        'afb_render_settings_page',
        'dashicons-forms',
        80
    );
}

function afb_render_settings_page() {
    $connection = afb_check_asana_connection();
    $projects = afb_get_all_projects();
    $selected_projects = get_option('afb_allowed_projects', []);
    ?>
    <div class="wrap">
        <h1>Asana Form Builder Settings</h1>

        <div style="margin: 1em 0; padding: 1em; background: #fff; border-left: 4px solid <?= $connection['success'] ? '#46b450' : '#dc3232'; ?>;">
            <?= wp_kses_post($connection['message']); ?>
        </div>

        <form method="post" action="options.php">
            <?php
            settings_fields('afb_settings_group');
            do_settings_sections('asana-form-builder');

            echo '<h2>Frontend Project Dropdown</h2>';
            echo '<p class="description">Select which Asana projects should be available to users in the frontend form dropdown.</p>';

            if (!$projects) {
                echo '<div class="notice notice-warning"><p>⚠️ Unable to load Asana projects. Please check your API token.</p></div>';
                $projects = [];
            }

            echo '<select multiple name="afb_allowed_projects[]" class="large-text" size="8" style="max-width: 100%;">';
            foreach ($projects as $project) {
                $selected = in_array($project['gid'], (array) $selected_projects) ? 'selected' : '';
                echo "<option value='{$project['gid']}' $selected>{$project['name']}</option>";
            }
            echo '</select>';
            echo '<p><em>Hold Ctrl (or Cmd on Mac) to select multiple projects.</em></p>';

            submit_button();
            ?>
        </form>

        <hr style="margin: 2em 0;">

        <h2>Configure Project Field Flow</h2>
        <p>Select a project to configure which custom fields to include in the form.</p>

        <form method="post">
            <select name="afb_project_to_configure">
                <?php foreach ($projects as $project): ?>
                    <option value="<?= esc_attr($project['gid']) ?>">
                        <?= esc_html($project['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="button">Load Fields</button>
        </form>

        <?php
        // Show fields for selected project
        if (!empty($_POST['afb_project_to_configure'])) {
            $selected_project_gid = sanitize_text_field($_POST['afb_project_to_configure']);
            $field_config = get_option('afb_project_field_config', []);
            $used_fields = $field_config[$selected_project_gid]['used_fields'] ?? [];

            $fields = afb_get_project_fields($selected_project_gid);

            if (!empty($fields)) {
                echo "<form method='post'>";
                echo "<input type='hidden' name='config_project_gid' value='" . esc_attr($selected_project_gid) . "' />";
                echo "<ul style='list-style:none; padding-left:0;'>";

                foreach ($fields as $field_setting) {
                    $field = $field_setting['custom_field'];
                    $gid = $field['gid'];
                    $name = $field['name'];
                    $type = $field['type'];
                    $checked = in_array($gid, $used_fields) ? 'checked' : '';
                    echo "<li><label><input type='checkbox' name='used_fields[]' value='$gid' $checked> $name ($type)</label></li>";
                }

                echo "</ul>";
                echo "<button type='submit' class='button button-primary'>Save Field Flow</button>";
                echo "</form>";
            } else {
                echo '<div class="notice notice-error"><p>❌ Could not fetch fields from Asana. Check token or project access.</p></div>';
            }
        }
        ?>
    </div>
    <?php
}

function afb_register_settings() {
    register_setting('afb_settings_group', 'afb_asana_token');
    register_setting('afb_settings_group', 'afb_default_project_id');
    register_setting('afb_settings_group', 'afb_project_prefix_map');
    register_setting('afb_settings_group', 'afb_allowed_projects');

    add_settings_section('afb_main_section', 'API Settings', null, 'asana-form-builder');

    add_settings_field('asana_token', 'Asana API Token', function () {
        $value = esc_attr(get_option('afb_asana_token'));
        echo "<input type='text' name='afb_asana_token' value='$value' class='regular-text' />";
    }, 'asana-form-builder', 'afb_main_section');

    add_settings_field('default_project_id', 'Default Project ID', function () {
        $value = esc_attr(get_option('afb_default_project_id'));
        echo "<input type='text' name='afb_default_project_id' value='$value' class='regular-text' />";
    }, 'asana-form-builder', 'afb_main_section');

    add_settings_section('afb_prefix_section', 'Project Prefixes', null, 'asana-form-builder');

    add_settings_field('project_prefix_map', 'Task Prefixes per Project', function () {
        $value = esc_textarea(get_option('afb_project_prefix_map'));
        echo "<p class='description'>Enter one per line: <code>project_id = PREFIX</code></p>";
        echo "<textarea name='afb_project_prefix_map' rows='6' class='large-text code' placeholder=\"1208219536311273 = TEST\">$value</textarea>";
    }, 'asana-form-builder', 'afb_prefix_section');
}
