<?php

namespace EasyLinkAutomations\HTTP\Controllers\Actions;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

/**
 * Controller for WordPress-related API calls.
 * Provides field columns for the field_mapping UI.
 */
final class WordPressController
{
    /**
     * Get available post fields for field mapping.
     */
    public function postFields(Request $request): Response
    {
        $postType = $request->get('post_type', 'post');

        $columns = [
            ['value' => 'post_title', 'label' => 'Title', 'required' => true],
            ['value' => 'post_content', 'label' => 'Content'],
            ['value' => 'post_excerpt', 'label' => 'Excerpt'],
            ['value' => 'post_status', 'label' => 'Status (draft/publish/pending/private)'],
            ['value' => 'post_author', 'label' => 'Author ID'],
            ['value' => 'post_date', 'label' => 'Publish Date (Y-m-d H:i:s)'],
            ['value' => 'post_name', 'label' => 'Slug'],
            ['value' => 'post_password', 'label' => 'Password'],
            ['value' => 'post_parent', 'label' => 'Parent Post ID'],
            ['value' => 'menu_order', 'label' => 'Menu Order'],
            ['value' => 'comment_status', 'label' => 'Comment Status (open/closed)'],
            ['value' => 'ping_status', 'label' => 'Ping Status (open/closed)'],
        ];

        // Add taxonomy fields based on post type
        $taxonomies = get_object_taxonomies($postType, 'objects');
        foreach ($taxonomies as $taxonomy) {
            $columns[] = [
                'value' => 'tax_' . $taxonomy->name,
                'label' => $taxonomy->labels->name . ' (comma-separated)',
            ];
        }

        return Response::success(['columns' => $columns]);
    }

    /**
     * Get available user meta fields for field mapping.
     */
    public function userMetaFields(Request $request): Response
    {
        // Common user meta fields
        $columns = [
            ['value' => 'first_name', 'label' => 'First Name'],
            ['value' => 'last_name', 'label' => 'Last Name'],
            ['value' => 'nickname', 'label' => 'Nickname'],
            ['value' => 'description', 'label' => 'Biographical Info'],
        ];

        // Get custom meta keys from existing users (cached)
        $cache_group = 'easylink_automations_wordpress';
        $cache_key   = 'user_meta_keys';
        $customKeys  = wp_cache_get($cache_key, $cache_group);
        if (false === $customKeys) {
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Cached; core usermeta table.
            $customKeys = $wpdb->get_col(
                "SELECT DISTINCT meta_key FROM {$wpdb->usermeta} 
                 WHERE meta_key NOT LIKE '\\_%' 
                 AND meta_key NOT IN ('first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale', 'dismissed_wp_pointers', 'session_tokens')
                 ORDER BY meta_key
                 LIMIT 50"
            );
            wp_cache_set($cache_key, $customKeys, $cache_group, 300);
        }

        foreach ($customKeys as $key) {
            $columns[] = [
                'value' => $key,
                'label' => ucwords(str_replace(['_', '-'], ' ', $key)),
            ];
        }

        return Response::success(['columns' => $columns]);
    }

    /**
     * Get list of public post types.
     */
    public function postTypes(Request $request): Response
    {
        $postTypes = get_post_types(['public' => true], 'objects');

        $options = [];
        foreach ($postTypes as $postType) {
            $options[] = [
                'value' => $postType->name,
                'label' => $postType->labels->singular_name,
            ];
        }

        return Response::success(['post_types' => $options]);
    }

    /**
     * Get list of users.
     */
    public function users(Request $request): Response
    {
        $users = get_users([
            'number'  => 200,
            'orderby' => 'display_name',
        ]);

        $options = [];
        foreach ($users as $user) {
            $options[] = [
                'value' => $user->ID,
                'label' => $user->display_name . ' (' . $user->user_email . ')',
            ];
        }

        return Response::success(['users' => $options]);
    }
}
