<?php
declare(strict_types=1);

const VERIPHONE_API_KEY = '2FA92AFB47FC4F4E94588F15DD462BBE';
const DRCASH_API_KEY = 'M2U0NJGZNDKTNDBJYY00YTBHLTHJMTKTMGEYODGZYZE3MTEZ';
const DRCASH_STREAM_CODE = 'yntad';
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)) {
    $input = $_POST;
}

$name = clean_text($input['name'] ?? '', 120);
$phone = normalize_greek_mobile($input['phone'] ?? '');
$sub1 = clean_text($input['sub1'] ?? $input['subid'] ?? $input['esub'] ?? '', 120);
$sub2 = clean_text($input['sub2'] ?? '', 120);
$sub3 = clean_text($input['sub3'] ?? '', 120);
$sub4 = clean_text($input['sub4'] ?? '', 120);
$sub5 = clean_text($input['sub5'] ?? '', 120);
$sourceUrl = clean_text($input['source_url'] ?? ($_SERVER['HTTP_REFERER'] ?? ''), 500);
$orderReference = 'UF-' . gmdate('ymd') . '-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));

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

$verification = verify_greek_mobile($phone);
if (!$verification['valid']) {
    respond(422, ['status' => 'error', 'message' => 'Phone verification failed']);
}

$drcash = send_to_drcash($name, $phone, $sub1, $sub2, $sub3, $sub4, $sub5);
send_to_telegram($name, $phone, $sourceUrl, $sub1, $sub2, $sub3, $sub4, $sub5, $orderReference, $verification, $drcash);

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

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

function verify_greek_mobile(string $phone): array
{
    $url = 'https://api.veriphone.io/v2/verify?phone=' . rawurlencode($phone) . '&default_country=GR';
    $response = http_request($url, 'GET', null, [
        'Authorization: Bearer ' . VERIPHONE_API_KEY,
    ]);
    $body = json_decode($response['body'], true);
    $valid = $response['http'] === 200
        && is_array($body)
        && ($body['phone_valid'] ?? false) === true
        && ($body['country_code'] ?? '') === 'GR'
        && ($body['phone_type'] ?? '') === 'mobile';
    return ['valid' => $valid, 'http' => $response['http'], 'body' => $response['body']];
}

function send_to_drcash(
    string $name,
    string $phone,
    string $sub1,
    string $sub2,
    string $sub3,
    string $sub4,
    string $sub5
): array {
    $payload = [
        'stream_code' => DRCASH_STREAM_CODE,
        'client' => [
            'name' => $name,
            'phone' => $phone,
            'country' => 'GR',
        ],
        'sub1' => $sub1,
        'sub2' => $sub2,
        'sub3' => $sub3,
        'sub4' => $sub4,
        'sub5' => $sub5,
    ];
    $response = http_request(DRCASH_ORDER_URL, 'POST', json_encode($payload, JSON_UNESCAPED_UNICODE), [
        'Content-Type: application/json',
        'Authorization: Bearer ' . DRCASH_API_KEY,
    ]);
    return [
        'ok' => $response['http'] === 200,
        'http' => $response['http'],
        'body' => $response['body'],
    ];
}

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

    $message = "<b>New Uro UP Forte 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> Greece\n"
        . "<b>Lead URL:</b> " . escape_html($sourceUrl) . "\n"
        . "<b>Stream:</b> " . escape_html(DRCASH_STREAM_CODE) . "\n"
        . "<b>Veriphone Status:</b> " . escape_html((string) $verification['http']) . "\n"
        . "<b>Dr.Cash Status:</b> " . escape_html((string) $drcash['http']) . "\n"
        . "<b>Sub1:</b> " . escape_html($sub1) . "\n"
        . "<b>Sub2:</b> " . escape_html($sub2) . "\n"
        . "<b>Sub3:</b> " . escape_html($sub3) . "\n"
        . "<b>Sub4:</b> " . escape_html($sub4) . "\n"
        . "<b>Sub5:</b> " . escape_html($sub5) . "\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 => 10,
        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 $method, ?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_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_HTTPHEADER => $headers,
    ]);
    if ($payload !== null) {
        curl_setopt($curl, 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_greek_mobile($value): string
{
    $digits = preg_replace('/\D+/', '', (string) $value) ?? '';
    if (strpos($digits, '0030') === 0) {
        $digits = substr($digits, 4);
    } elseif (strpos($digits, '30') === 0) {
        $digits = substr($digits, 2);
    }
    return preg_match('/^69\d{8}$/', $digits) === 1 ? '+30' . $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;
}
