<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Common\LicenseChecker;
use PloverCRM\Common\Permissions;
use PloverCRM\Core\Services\BusinessInformationService;
use PloverCRM\Core\Services\CurrentUserPayloadBuilder;
use PloverCRM\Core\Services\WorkspaceSetupService;
use WP_REST_Request;

/**
 * Workspace Endpoint
 * 
 * GET /wp-json/plover-crm/v1/workspace
 * 
 * Returns workspace details including:
 * - Current user info with role and permissions
 * - Standard fields and custom fields
 * - Lists and tags
 */
class WorkspaceEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/workspace';
    }

    public function getMethod()
    {
        return 'GET';
    }

    public function handle(WP_REST_Request $request)
    {
        $crm = $this->container->get('crm');

        if (!$crm->isAvailable()) {
            return $this->error('CRM not available', 503);
        }

        // Get current user info with role
        $user = $this->getCurrentUserInfo($crm);

        // Get standard fields
        $standard_fields = $this->getStandardFields($crm);

        // Get all lists
        $lists_data = $crm->getAllLists();
        $lists = [];
        foreach ($lists_data as $list) {
            $lists[$list['title']] = (int) $list['id'];
        }

        // Get all tags
        $tags_data = $crm->getAllTags();
        $tags = [];
        foreach ($tags_data as $tag) {
            $tags[$tag['title']] = (int) $tag['id'];
        }

        // Get custom fields
        $custom_fields = $crm->getAllCustomFields();
        
        // Enhance stage field with colors
        if (is_array($custom_fields)) {
            foreach ($custom_fields as &$field) {
                $field = \PloverCRM\Common\Utils::enhanceStageFieldWithColors($field);
            }
        }

        $workspace = [
            'user' => $user,
            'standard_fields' => $standard_fields,
            'lists' => $lists,
            'tags' => $tags,
            'custom_fields' => $custom_fields,
            'license' => LicenseChecker::getStatus(),
            'setup' => WorkspaceSetupService::getState(),
            'business_information' => Permissions::canAccessSetting('business_information', 'view')
                ? BusinessInformationService::get()
                : null,
        ];

        return $this->success($workspace);
    }

    /**
     * Get current user info with the effective role used by the app.
     */
    private function getCurrentUserInfo($crm): array
    {
        return CurrentUserPayloadBuilder::build() ?? [];
    }

    /**
     * Get standard fields for contacts table
     */
    private function getStandardFields($crm): array
    {
        $fields = [];
        
        if ($crm->getName() === 'FluentCRM') {
            global $wpdb;
            $table_name = $wpdb->prefix . 'fc_subscribers';
            
            $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
            
            if ($table_exists) {
                $query = "SELECT COLUMN_NAME 
                          FROM INFORMATION_SCHEMA.COLUMNS 
                          WHERE TABLE_NAME = '" . $table_name . "'
                          AND TABLE_SCHEMA = '" . DB_NAME . "'";
                
                $fields = $wpdb->get_col($query);
            }
        } else {
            // For PloverCRM
            $standardFields = $crm->getStandardFields();
            $fields = array_merge(
                ['id'],
                array_keys($standardFields),
                ['status', 'hash', 'created_at', 'updated_at']
            );
        }
        
        // Add virtual fields
        $fields[] = 'lists';
        $fields[] = 'tags';
        $fields[] = 'last_note';
        $fields[] = 'plover_crm_avatar';
        
        return $fields;
    }
}
