<?php
declare(strict_types=1);

const DRCASH_API_KEY = 'M2U0NJGZNDKTNDBJYY00YTBHLTHJMTKTMGEYODGZYZE3MTEZ';
const DRCASH_STREAM_CODE = '4ur54';
const DRCASH_ORDER_URL = 'https://order.drcash.sh/v1/order';
const TELEGRAM_BOT_TOKEN = '8777663907:AAE2Bb5MxCHZgEbPuBFevPs6ymUH2NUQSUY';
const TELEGRAM_CHAT_ID = '1007780956';

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(405, ['status' => 'error', 'message' => 'Method not allowed']);
}

$input = json_decode((string) file_get_contents('php://input'), true);
if (!is_array($input)) {
    respond(400, ['status' => 'error', 'message' => 'Invalid request']);
}

$name = clean_text($input['name'] ?? '', 120);
$phone = normalize_phone($input['phone'] ?? '');
$subid = clean_text($input['subid'] ?? ($input['clickid'] ?? ''), 120);
$orderReference = 'GZ-' . gmdate('ymd') . '-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));

if ($name === '' || $phone === '') {
    respond(422, ['status' => 'error', 'message' => 'Invalid name or phone']);
}

$sourceUrl = clean_text($input['source_url'] ?? ($input['source'] ?? ($_SERVER['HTTP_REFERER'] ?? '')), 500);
$drcash = send_to_drcash($name, $phone, $subid);
send_to_telegram($name, $phone, $subid, $sourceUrl, $orderReference, $drcash);

if (!$drcash['ok']) {
    respond(502, [
        'status' => 'error',
        'message' => 'Order service rejected the lead',
        'http' => $drcash['http'],
        'response' => $drcash['body'],
    ]);
}

respond(200, ['status' => 'ok', 'message' => 'Order sent', 'order_reference' => $orderReference]);

function send_to_drcash(string $name, string $phone, string $subid): array
{
    $payload = [
        'stream_code' => DRCASH_STREAM_CODE,
        'client' => [
            'name' => $name,
            'phone' => $phone,
        ],
        'sub1' => $subid,
    ];

    $response = http_request(DRCASH_ORDER_URL, json_encode($payload, JSON_UNESCAPED_UNICODE), [
        'Content-Type: application/json',
        'Authorization: Bearer ' . DRCASH_API_KEY,
    ]);

    return [
        'ok' => $response['http'] >= 200 && $response['http'] < 300,
        'http' => $response['http'],
        'body' => $response['body'],
    ];
}

function send_to_telegram(string $name, string $phone, string $subid, string $sourceUrl, string $orderReference, array $drcash): void
{
    if (TELEGRAM_BOT_TOKEN === '' || TELEGRAM_CHAT_ID === '' || !function_exists('curl_init')) {
        return;
    }

    $message = "<b>New GlucoZen Lead</b>\n"
        . "<b>Order:</b> " . escape_html($orderReference) . "\n"
        . "<b>Name:</b> " . escape_html($name) . "\n"
        . "<b>Phone:</b> " . escape_html($phone) . "\n"
        . "<b>Country:</b> Spain\n"
        . "<b>Lead URL:</b> " . escape_html($sourceUrl) . "\n"
        . "<b>Offer:</b> GlucoZen\n"
        . "<b>Stream:</b> " . escape_html(DRCASH_STREAM_CODE) . "\n"
        . "<b>Dr.Cash Status:</b> " . escape_html((string) $drcash['http']) . "\n"
        . "<b>Subid:</b> " . escape_html($subid) . "\n"
        . "<b>IP:</b> " . escape_html($_SERVER['REMOTE_ADDR'] ?? '') . "\n"
        . "<b>Time:</b> " . gmdate('Y-m-d H:i:s') . " UTC";

    $curl = curl_init('https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/sendMessage');
    curl_setopt_array($curl, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT_MS => 10000,
        CURLOPT_POSTFIELDS => [
            'chat_id' => TELEGRAM_CHAT_ID,
            'text' => $message,
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => '1',
        ],
    ]);
    curl_exec($curl);
    curl_close($curl);
}

function http_request(string $url, string $payload, array $headers): array
{
    if (!function_exists('curl_init')) {
        respond(500, ['status' => 'error', 'message' => 'PHP cURL extension is required']);
    }

    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CONNECTTIMEOUT_MS => 10000,
        CURLOPT_TIMEOUT_MS => 20000,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $payload,
    ]);

    $body = curl_exec($curl);
    $http = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($body === false) {
        $body = 'cURL error: ' . curl_error($curl);
    }
    curl_close($curl);

    return ['http' => $http, 'body' => clean_text((string) $body, 2000)];
}

function normalize_phone($value): string
{
    $raw = trim((string) $value);
    $digits = preg_replace('/\D+/', '', $raw) ?? '';

    if ($digits === '') {
        return '';
    }

    if (strpos($digits, '0034') === 0) {
        $digits = substr($digits, 4);
    }

    if (strpos($digits, '34') !== 0 && preg_match('/^[67]\d{8}$/', $digits) === 1) {
        return '+34' . $digits;
    }

    return '+' . ltrim($digits, '+');
}

function clean_text($value, int $maxLength): string
{
    $text = trim((string) $value);
    return function_exists('mb_substr') ? mb_substr($text, 0, $maxLength) : substr($text, 0, $maxLength);
}

function escape_html($value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function respond(int $httpStatus, array $payload): void
{
    http_response_code($httpStatus);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}
