<?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';

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

