<?php
declare(strict_types=1);

const DRCASH_API_KEY = 'M2U0NJGZNDKTNDBJYY00YTBHLTHJMTKTMGEYODGZYZE3MTEZ';
const DRCASH_STREAM_CODE = 'ihm3v';
const DRCASH_ORDER_URL = 'https://order.drcash.sh/v1/order';

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']);
}

$drcash = send_to_drcash($name, $phone, $subid);
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 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 respond(int $httpStatus, array $payload): void
{
    http_response_code($httpStatus);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}
