<?php

namespace PloverCRM\Core\Api\V1;

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

/**
 * Stats Endpoint
 * 
 * GET /wp-json/plover-crm/v1/stats
 */
class StatsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/stats';
    }

    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);
        }

        $stats = $this->getStats($crm);

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

    /**
     * Get CRM statistics
     */
    private function getStats($crm): array
    {
        $provider = $crm->getName();

        if ($provider === 'FluentCRM') {
            return $this->getFluentCRMStats();
        } elseif ($provider === 'PloverCRM') {
            return $this->getPloverCRMStats();
        }

        return [];
    }

    /**
     * Get FluentCRM statistics
     */
    private function getFluentCRMStats(): array
    {
        if (!class_exists('FluentCrm\App\Models\Subscriber')) {
            return [];
        }

        try {
            return [
                'total_contacts' => \FluentCrm\App\Models\Subscriber::count(),
                'lists_count' => \FluentCrm\App\Models\Lists::count(),
                'tags_count' => \FluentCrm\App\Models\Tag::count(),
                'list_summaries' => $this->getFluentCRMListSummaries(),
            ];
        } catch (\Exception $e) {
            $logger = new \PloverCRM\Core\Api\Services\Logger();
            $logger->logApiError('/stats', $e->getMessage());
            return [];
        }
    }

    /**
     * Get PloverCRM statistics
     */
    private function getPloverCRMStats(): array
    {
        $total = wp_count_posts('plover_crm_contact');

        return [
            'total_contacts' => $total->publish ?? 0,
            'lists_count' => wp_count_terms(['taxonomy' => 'plover_crm_list', 'hide_empty' => false]),
            'tags_count' => wp_count_terms(['taxonomy' => 'plover_crm_tag', 'hide_empty' => false]),
            'list_summaries' => $this->getPloverCRMListSummaries(),
        ];
    }

    private function getFluentCRMListSummaries(): array
    {
        global $wpdb;

        $listsTable = $wpdb->prefix . 'fc_lists';
        $pivotTable = $wpdb->prefix . 'fc_subscriber_pivot';
        $objectType = 'FluentCrm\\App\\Models\\Lists';

        $query = $wpdb->prepare(
            "
            SELECT lists.id, lists.title, COALESCE(counts.contacts_count, 0) AS contacts_count
            FROM {$listsTable} AS lists
            LEFT JOIN (
                SELECT object_id, COUNT(*) AS contacts_count
                FROM {$pivotTable}
                WHERE object_type = %s
                GROUP BY object_id
            ) AS counts ON counts.object_id = lists.id
            ORDER BY lists.title ASC
            ",
            $objectType
        );

        $results = $wpdb->get_results($query, ARRAY_A);

        if (!is_array($results)) {
            return [];
        }

        return array_map(static function ($list) {
            return [
                'id' => (int) ($list['id'] ?? 0),
                'title' => (string) ($list['title'] ?? ''),
                'contacts_count' => (int) ($list['contacts_count'] ?? 0),
            ];
        }, array_filter($results, static function ($list) {
            return !empty($list['id']) && !empty($list['title']);
        }));
    }

    private function getPloverCRMListSummaries(): array
    {
        $terms = get_terms([
            'taxonomy' => 'plover_crm_list',
            'hide_empty' => false,
        ]);

        if (is_wp_error($terms) || empty($terms)) {
            return [];
        }

        return array_map(static function ($term) {
            return [
                'id' => (int) $term->term_id,
                'title' => (string) $term->name,
                'contacts_count' => (int) $term->count,
            ];
        }, $terms);
    }
}
