<?php

require_once plugin_dir_path(__DIR__) . '../includes/api.php';
global $wpdb;

// ✅ Fetch PAT from your existing settings
$pat = get_option('asana_access_token');

// ✅ Get workspace GID — for now I will assume you have it stored like this:
$workspace_gid = get_option('asana_workspace_gid');

// If no workspace ID stored yet, we can fetch it from /users/me as fallback
if (!$workspace_gid) {
    $me = afb_fetch_asana('users/me', $pat);
    $workspace_gid = $me['workspaces'][0]['gid'] ?? null;
    if ($workspace_gid) {
        update_option('asana_workspace_gid', $workspace_gid); // store for future use
    }
}

if (!$workspace_gid) {
    echo '<div class="notice notice-error"><p>Workspace GID not found. Please verify your Asana connection.</p></div>';
    return;
}

// ✅ Handle template selection
$template_gid = isset($_GET['template_gid']) ? sanitize_text_field($_GET['template_gid']) : null;

$templates = afb_get_task_templates($workspace_gid, $pat);

?>

<div class="wrap">
    <h1>Task Templates (Experimental)</h1>

    <form method="get">
        <input type="hidden" name="page" value="asana-task-templates" />
        <label for="template_gid">Select Task Template:</label>
        <select name="template_gid" id="template_gid" onchange="this.form.submit()">
            <option value="">-- Select --</option>
            <?php foreach ($templates as $template): ?>
                <option value="<?php echo esc_attr($template['gid']); ?>" <?php selected($template_gid, $template['gid']); ?>>
                    <?php echo esc_html($template['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </form>

    <?php if ($template_gid): ?>
        <?php
        $template = afb_get_task_template($template_gid, $pat);
        ?>
        <h2>Template Preview: <?php echo esc_html($template['name']); ?></h2>

        <h3>Custom Fields</h3>
        <?php if (!empty($template['custom_fields'])): ?>
            <ul>
                <?php foreach ($template['custom_fields'] as $field): ?>
                    <li><strong><?php echo esc_html($field['name']); ?></strong> (<?php echo esc_html($field['type']); ?>)</li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p>No custom fields found in this template.</p>
        <?php endif; ?>
    <?php endif; ?>
</div>
