<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use PloverCRM\Core\Api\AbstractEndpoint;

class GetCRMItemsEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/crm/items';
  }

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

  public function checkPermission(WP_REST_Request $request)
  {
    return $this->checkAuthenticatedCapability($request, 'manage_options');
  }

  public function handle(WP_REST_Request $request)
  {
    $type = $request->get_param('type'); // tags or lists
    $items = [];

    if ($type === 'stages') {
      $crm = \PloverCRM\Core\Plugin::getInstance()->getContainer()->get('crm');
      if ($crm->isAvailable()) {
        $fields = $crm->getAllCustomFields();
        foreach ($fields as $field) {
          if ($field['slug'] === 'stage-plover-crm' && isset($field['options'])) {
            foreach ($field['options'] as $opt) {
              // If options are simple strings
              $items[] = ['id' => $opt, 'title' => $opt];
            }
            break;
          }
        }
      }
    } elseif (function_exists('FluentCrmApi')) {
      if ($type === 'tags') {
        $tags = FluentCrmApi('tags')->all();
        foreach ($tags as $tag) {
          $items[] = ['id' => $tag->id, 'title' => $tag->title];
        }
      } elseif ($type === 'lists') {
        $lists = FluentCrmApi('lists')->all();
        foreach ($lists as $list) {
          $items[] = ['id' => $list->id, 'title' => $list->title];
        }
      }
    } else {
      // Fallback to DB if wrapper missing
      global $wpdb;
      if ($type === 'tags') {
        $items = $wpdb->get_results("SELECT id, title FROM {$wpdb->prefix}fc_tags ORDER BY title ASC");
      } elseif ($type === 'lists') {
        $items = $wpdb->get_results("SELECT id, title FROM {$wpdb->prefix}fc_lists ORDER BY title ASC");
      }
    }

    return [
      'success' => true,
      'items' => $items
    ];
  }
}
