<?php

namespace Blazemedia\Affiliation\Rendering\Trait;
use Blazemedia\Affiliation\Support\Environment;
use Blazemedia\Affiliation\Rendering\Parameters;

trait DebugPrint {

    public function getApiCallForDebug(\WP_Post $post): void {

        // Always expose DebugPrint UI for allowed users, even when meta is used
        $parameters = new Parameters($post);
        $baseUrl = Environment::get('BLZ_API_RENDERING_MANAGER', 'https://rendering-manager.blazemedia.it/api/') . 'v2/';
        $apiSecret = Environment::get('BLZ_AFF_API_SECRET', '');
        $apiCall = $baseUrl . 'render/content/' . $parameters->getSignature($apiSecret);
        $options = [
            'headers'   => [
                'Content-Type' => 'application/json',
                'X-API-Key'    => $parameters->getSignature($apiSecret),
                'Source'       => get_permalink($post->ID),
            ],
            'body'      => json_encode($parameters->toArray()),
            'sslverify' => false,
            'Accept'    => 'application/json',
        ];

        $currentSignature = $parameters->getSignature($apiSecret);
        $this->printApiCallForDebug($currentSignature, $apiCall, $options);
    }

    public function printApiCallForDebug(string $signature, string $apiCall, $options): void {
        if (!$this->shouldShowDebug()) {
            return;
        }

        $curlCommand = $this->generateCurlCommand($apiCall, $options);
        $apiResponse = $this->executeApiCall($apiCall, $options);

        $this->renderDebugInterface($curlCommand, $apiResponse, $apiCall, $options);
        die();
    }

    private function shouldShowDebug(): bool {
        $user = wp_get_current_user();

        return isset($_GET['debug-aff']) &&
            $_GET['debug-aff'] === 'trello' &&
            is_user_logged_in() &&
            (str_contains($user->user_email, 'blazemedia.it') ||
                str_contains($user->user_email, 'f2innovation.com') ||
                $user->user_login == 'techteam'
            );
    }

    private function generateCurlCommand(string $apiCall, array $options): string {
        $curlCommand = "curl -X POST '" . $apiCall . "'";

        // Aggiungi headers
        if (isset($options['headers'])) {
            foreach ($options['headers'] as $key => $value) {
                $curlCommand .= " \\\n  -H '" . $key . ": " . addslashes($value) . "'";
            }
        }

        // Aggiungi body
        if (isset($options['body'])) {
            $curlCommand .= " \\\n  -d " . json_encode($options['body']);
        }

        // Aggiungi opzioni SSL
        if (isset($options['sslverify']) && $options['sslverify'] === false) {
            $curlCommand .= " \\\n  --insecure";
        }

        return $curlCommand;
    }

    private function executeApiCall(string $apiCall, array $options): string {
        if (!isset($_GET['execute-call']) || $_GET['execute-call'] !== 'true') {
            return '';
        }

        $response = wp_remote_post($apiCall, $options);

        if (is_wp_error($response)) {
            return "❌ Errore: " . $response->get_error_message();
        }

        return $this->formatApiResponse($response);
    }

    private function formatApiResponse($response): string {
        $responseCode = wp_remote_retrieve_response_code($response);
        $responseBody = wp_remote_retrieve_body($response);
        $responseHeaders = wp_remote_retrieve_headers($response);

        $formatted = "✅ Status Code: " . $responseCode . "\n\n";
        $formatted .= $this->formatHeaders($responseHeaders);
        $formatted .= $this->formatResponseBody($responseBody);

        return $formatted;
    }

    private function formatHeaders($headers): string {
        return "📋 Headers:\n" . print_r($headers, true) . "\n";
    }

    private function formatResponseBody(string $body): string {
        $decodedBody = json_decode($body);

        if (json_last_error() === JSON_ERROR_NONE) {
            return "📄 Body (JSON formatted):\n" .
                json_encode($decodedBody, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }

        return "📄 Body (raw):\n" . $body;
    }

    private function renderDebugInterface(string $curlCommand, string $apiResponse, string $apiCall, array $options): void {
        $apiSecret = (string) Environment::get('BLZ_AFF_API_SECRET', '');
        echo $this->getMainContainer([
            $this->getApiSecretSection($apiSecret),
            $this->getCurlSection($curlCommand),
            $this->getButtonSection(),
            $this->getApiResponseSection($apiResponse),
            $this->getRequestDetailsSection($apiCall, $options),
            $this->getToastNotification(),
            $this->getCopyToClipboardScript()
        ]);
    }

    private function getApiSecretSection(string $apiSecret): string {
        return sprintf(
            "<div style='%s'>
                <h3 style='%s'>🔑 Chiave impostata nei Settings (in chiaro)</h3>
                <pre style='%s'>%s</pre>
            </div>",
            'margin: 25px 0;',
            $this->getHeadingStyles(),
            $this->getPreStyles('details'),
            htmlspecialchars($apiSecret)
        );
    }

    private function getMainContainer(array $sections): string {
        return sprintf(
            "<div style='%s'>%s</div>",
            $this->getMainContainerStyles(),
            implode('', $sections)
        );
    }

    private function getMainContainerStyles(): string {
        return 'background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); 
                padding: 30px; 
                margin: 20px; 
                border-radius: 15px; 
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
                border: 1px solid #dee2e6;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;';
    }

    private function getCurlSection(string $curlCommand): string {
        return sprintf(
            "<div style='%s'>
                <h3 style='%s'>🔧 cURL Command per Postman</h3>
                <textarea id='curl-command' style='%s' onclick='copyToClipboard()' readonly>%s</textarea>
            </div>",
            'margin-bottom: 25px;',
            $this->getHeadingStyles(),
            $this->getTextareaStyles(),
            htmlspecialchars($curlCommand)
        );
    }

    private function getButtonSection(): string {
        $executeButton = $this->getExecuteButton();
        $resetButton = isset($_GET['execute-call']) ? $this->getResetButton() : '';

        return sprintf(
            "<div style='%s'>%s%s</div>",
            'margin: 25px 0; text-align: center;',
            $executeButton,
            $resetButton
        );
    }

    private function getExecuteButton(): string {
        $currentUrl = add_query_arg(['execute-call' => 'true'], $_SERVER['REQUEST_URI']);

        return sprintf(
            "<a href='%s' style='%s' %s>🚀 Esegui Chiamata API</a>",
            esc_url($currentUrl),
            $this->getButtonStyles('primary'),
            $this->getButtonEvents('primary')
        );
    }

    private function getResetButton(): string {
        $refreshUrl = remove_query_arg('execute-call', $_SERVER['REQUEST_URI']);

        return sprintf(
            "<a href='%s' style='%s' %s>🔄 Reset</a>",
            esc_url($refreshUrl),
            $this->getButtonStyles('secondary'),
            $this->getButtonEvents('secondary')
        );
    }

    private function getButtonStyles(string $type): string {
        $baseStyles = 'border: none;
                      color: white;
                      padding: 15px 30px;
                      border-radius: 10px;
                      text-decoration: none;
                      font-weight: 600;
                      font-size: 14px;
                      display: inline-flex;
                      align-items: center;
                      gap: 10px;
                      transition: all 0.3s ease;
                      margin: 0 10px;
                      cursor: pointer;
                      box-shadow: 0 5px 15px rgba(0,0,0,0.15);';

        $gradients = [
            'primary' => 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);',
            'secondary' => 'background: linear-gradient(135deg, #6c757d 0%, #495057 100%);'
        ];

        return $baseStyles . $gradients[$type];
    }

    private function getButtonEvents(string $type): string {
        $colors = [
            'primary' => ['normal' => 'rgba(102, 126, 234, 0.3)', 'hover' => 'rgba(102, 126, 234, 0.5)'],
            'secondary' => ['normal' => 'rgba(108, 117, 125, 0.3)', 'hover' => 'rgba(108, 117, 125, 0.5)']
        ];

        return sprintf(
            'onmouseover="this.style.transform=\'translateY(-3px)\'; this.style.boxShadow=\'0 8px 25px %s\';"
             onmouseout="this.style.transform=\'translateY(0px)\'; this.style.boxShadow=\'0 5px 15px %s\';"',
            $colors[$type]['hover'],
            $colors[$type]['normal']
        );
    }

    private function getApiResponseSection(string $apiResponse): string {
        if (empty($apiResponse)) {
            return '';
        }

        return sprintf(
            "<div style='%s'>
                <h3 style='%s'>📡 Risultato della chiamata API</h3>
                <pre style='%s'>%s</pre>
            </div>",
            'margin: 25px 0;',
            $this->getHeadingStyles(),
            $this->getPreStyles('response'),
            htmlspecialchars($apiResponse)
        );
    }

    private function getRequestDetailsSection(string $apiCall, array $options): string {
        return sprintf(
            "<div style='%s'>
                <h3 style='%s'>📋 Dettagli della richiesta</h3>
                <pre style='%s'>%s</pre>
            </div>",
            'margin: 25px 0;',
            $this->getHeadingStyles(),
            $this->getPreStyles('details'),
            $this->formatRequestDetails($apiCall, $options)
        );
    }

    private function formatRequestDetails(string $apiCall, array $options): string {
        $details = "🌐 URL: " . htmlspecialchars($apiCall) . "\n";
        $details .= "📤 Method: POST\n\n";

        if (isset($options['headers'])) {
            $details .= "📋 Headers:\n";
            foreach ($options['headers'] as $key => $value) {
                $details .= "  • " . $key . ": " . htmlspecialchars($value) . "\n";
            }
            $details .= "\n";
        }

        if (isset($options['body'])) {
            $details .= "📄 Body (JSON):\n";
            $details .= htmlspecialchars(
                json_encode(json_decode($options['body']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
            );
        }

        return $details;
    }

    private function getHeadingStyles(): string {
        return 'color: #495057;
                font-size: 18px;
                margin-bottom: 15px;
                font-weight: 700;
                text-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                border-bottom: 2px solid #dee2e6;
                padding-bottom: 8px;';
    }

    private function getTextareaStyles(): string {
        return 'width: 100%;
                height: 200px;
                font-family: "Fira Code", "Monaco", monospace;
                font-size: 12px;
                padding: 15px;
                border: 2px solid #ced4da;
                border-radius: 8px;
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                resize: vertical;
                line-height: 1.5;
                box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
                cursor: pointer;
                transition: all 0.2s ease;';
    }

    private function getPreStyles(string $type): string {
        $baseStyles = 'padding: 20px;
                      border: 2px solid #ced4da;
                      border-radius: 8px;
                      overflow: auto;
                      font-family: "Fira Code", "Monaco", monospace;
                      font-size: 12px;
                      line-height: 1.6;
                      box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.03);';

        $typeStyles = [
            'response' => 'max-height: 500px; 
                          background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%); 
                          border-color: #ced4da;',
            'details' => 'background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); 
                         border-color: #ced4da;'
        ];

        return $baseStyles . $typeStyles[$type];
    }

    private function getToastNotification(): string {
        return "
    <div id='toast-notification' style='{$this->getToastStyles()}'>
        <span style='margin-right: 10px;'>✅</span>
        <span>Comando cURL copiato con successo!</span>
    </div>";
    }

    private function getToastStyles(): string {
        return 'position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 15px 25px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            font-weight: 600;
            font-size: 14px;
            z-index: 10000;
            transform: translateX(400px);
            opacity: 0;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            min-width: 280px;';
    }

    private function getCopyToClipboardScript(): string {
        return "
    <script>
    function copyToClipboard() {
        const textarea = document.getElementById('curl-command');
        const toast = document.getElementById('toast-notification');
        
        try {
            // Seleziona il testo
            textarea.select();
            textarea.setSelectionRange(0, 99999); // Per dispositivi mobili
            
            // Copia usando l'API moderna se disponibile
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(textarea.value).then(function() {
                    showToast(toast);
                }).catch(function(err) {
                    // Fallback al metodo classico
                    fallbackCopy(textarea, toast);
                });
            } else {
                // Fallback al metodo classico
                fallbackCopy(textarea, toast);
            }
        } catch (err) {
            console.error('Errore durante la copia:', err);
            showErrorToast(toast);
        }
    }
    
    function fallbackCopy(textarea, toast) {
        try {
            const successful = document.execCommand('copy');
            if (successful) {
                showToast(toast);
            } else {
                showErrorToast(toast);
            }
        } catch (err) {
            console.error('Fallback copy failed:', err);
            showErrorToast(toast);
        }
    }
    
    function showToast(toast) {
        // Toast di successo con verde
        toast.style.background = 'linear-gradient(135deg, #28a745 0%, #20c997 100%)';
        toast.innerHTML = '<span style=\"margin-right: 10px;\">✅</span><span>Comando cURL copiato con successo!</span>';
        
        // Mostra il toast
        toast.style.transform = 'translateX(0)';
        toast.style.opacity = '1';
        
        // Nascondi dopo 3 secondi
        setTimeout(function() {
            hideToast(toast);
        }, 3000);
    }
    
    function showErrorToast(toast) {
        // Toast di errore con rosso
        toast.style.background = 'linear-gradient(135deg, #dc3545 0%, #c82333 100%)';
        toast.innerHTML = '<span style=\"margin-right: 10px;\">❌</span><span>Errore durante la copia</span>';
        
        // Mostra il toast
        toast.style.transform = 'translateX(0)';
        toast.style.opacity = '1';
        
        // Nascondi dopo 3 secondi
        setTimeout(function() {
            hideToast(toast);
        }, 3000);
    }
    
    function hideToast(toast) {
        toast.style.transform = 'translateX(400px)';
        toast.style.opacity = '0';
    }
    
    // Permetti di chiudere il toast cliccandoci sopra
    document.getElementById('toast-notification').addEventListener('click', function() {
        hideToast(this);
    });
    </script>";
    }
}
