<?php

namespace PloverCRM\Core\Services;

use PloverCRM\Common\LicenseChecker;

/**
 * Email Verification Service
 * 
 * Verifies email addresses against external API to prevent sending to unsafe addresses.
 */
class EmailVerificationService
{
    /**
     * API endpoint for email verification
     */
    private const API_ENDPOINT = 'https://plovercrm.com/api/verify-email/';

    /**
     * Request timeout in seconds
     */
    private const TIMEOUT = 20;

    /**
     * Check if an email is safe to send to
     *
     * @param string $email Email address to verify
     * @return bool True if safe to send, false otherwise
     */
    public static function isSafeToSend(string $email): bool
    {
        // Validate email format first
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return false;
        }

        // Block @wpr.com placeholder emails
        if (str_ends_with(strtolower($email), '@wpr.com')) {
            return false;
        }

        try {
            if (self::shouldSkipRemoteVerification()) {
                return true;
            }

            $token = self::getSiteToken();
            if ($token === '') {
                return true;
            }

            $response = wp_remote_post(self::API_ENDPOINT, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                    'X-PloverCRM-Token' => $token,
                    'X-PloverCRM-Service' => 'email_verification',
                ],
                'body' => wp_json_encode(['email' => $email]),
                'timeout' => self::TIMEOUT,
                'sslverify' => true,
            ]);

            // If API call failed, allow the email (fail open)
            if (is_wp_error($response)) {
                return true;
            }

            $statusCode = wp_remote_retrieve_response_code($response);

            if (in_array($statusCode, [401, 403], true)) {
                return false;
            }

            if ($statusCode !== 200) {
                return true;
            }

            $result = json_decode(wp_remote_retrieve_body($response), true);

            if (!is_array($result)) {
                return true;
            }

            return (bool) ($result['safe_to_send'] ?? true);
        } catch (\Throwable $e) {
            return true; // Fail open - don't block on exceptions
        }
    }

    /**
     * Local and test installs should not depend on the remote verification service.
     */
    private static function shouldSkipRemoteVerification(): bool
    {
        $host = wp_parse_url(home_url('/'), PHP_URL_HOST);

        if (!is_string($host) || $host === '') {
            return false;
        }

        return str_ends_with($host, '.local')
            || str_ends_with($host, '.test')
            || str_contains($host, 'localhost');
    }

    /**
     * Read the activation token already stored by the licensing system.
     */
    private static function getSiteToken(): string
    {
        $license = LicenseChecker::getLicense();
        return isset($license['token']) ? (string) $license['token'] : '';
    }
}
