<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Core\CRM\Schemas\GrowthSchema;
use WP_REST_Request;

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

    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 date range from query parameters (default: last 30 days)
        $from = $request->get_param('from') ?: date('Y-m-d', strtotime('-30 days'));
        $to = $request->get_param('to') ?: date('Y-m-d');
        
        // Validate date format
        $from_time = strtotime($from);
        $to_time = strtotime($to);
        
        if ($from_time === false || $to_time === false) {
            return $this->error('Invalid date format. Use Y-m-d format.', 400);
        }
        
        if ($from_time > $to_time) {
            return $this->error('From date must be before or equal to To date.', 400);
        }
        
        $from = date('Y-m-d', $from_time);
        $to = date('Y-m-d', $to_time);
        
        $growth = $this->getGrowthData($crm, $from, $to);
        
        return $this->success([
            'stats' => $growth
        ]);
    }

    /**
     * Get growth data
     */
    private function getGrowthData($crm, string $from, string $to): array
    {
        $provider = $crm->getName();
        
        if ($provider === 'FluentCRM') {
            return $this->getFluentCRMGrowth($from, $to);
        } elseif ($provider === 'PloverCRM') {
            return $this->getPloverCRMGrowth($from, $to);
        }
        
        return [];
    }

    /**
     * Get FluentCRM growth data
     */
    private function getFluentCRMGrowth(string $from, string $to): array
    {
        if (!class_exists('FluentCrm\App\Services\Reporting')) {
            return [];
        }

        try {
            $reporting = new \FluentCrm\App\Services\Reporting();
            return $reporting->getSubscribersGrowth($from, $to);
        } catch (\Exception $e) {
            $logger = new \PloverCRM\Core\Api\Services\Logger();
            $logger->logApiError('/growth', $e->getMessage());
            return [];
        }
    }

    /**
     * Get PloverCRM growth data
     */
    private function getPloverCRMGrowth(string $from, string $to): array
    {
        global $wpdb;
        
        $data = [];
        $current = strtotime($from);
        $end = strtotime($to);
        
        while ($current <= $end) {
            $date = date('Y-m-d', $current);
            $next_date = date('Y-m-d', strtotime('+1 day', $current));
            
            $count = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->posts} 
                WHERE post_type = 'plover_crm_contact' 
                AND post_status = 'publish'
                AND post_date >= %s 
                AND post_date < %s",
                $date . ' 00:00:00',
                $next_date . ' 00:00:00'
            ));
            
            // Return in same format as FluentCRM: date => count
            $data[$date] = intval($count);
            
            $current = strtotime('+1 day', $current);
        }
        
        return $data;
    }
}
