<?php
declare(strict_types=1);

const VERIPHONE_API_KEY = '2FA92AFB47FC4F4E94588F15DD462BBE';
const DRCASH_API_KEY = 'M2U0NJGZNDKTNDBJYY00YTBHLTHJMTKTMGEYODGZYZE3MTEZ';
const DRCASH_STREAM_CODE = 'pay4e';
const DRCASH_ORDER_URL = 'https://order.drcash.sh/v1/order';
const SHEET_WEBHOOK_URL = 'https://script.google.com/macros/s/AKfycbzbyVqdnfok_FoAC7tLqR5n0ZARiCeBUgJ3JIyg-QyVaZxmjZxFL0AuD87XqzP_Apg/exec';

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_spanish_mobile($input['phone'] ?? '');
$source = clean_text($input['source'] ?? '', 500);
$subid = clean_text($input['subid'] ?? '', 120);
$timestamp = clean_text($input['timestamp'] ?? '', 60) ?: gmdate('c');
$orderReference = 'GZ-' . gmdate('ymd') . '-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));

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

$verification = verify_spanish_mobile($phone);
if (!$verification['valid']) {
    log_to_sheet($timestamp, $name, $phone, $source, $subid, 'invalid_phone', (string) $verification['http'], $verification['body']);
    respond(422, ['status' => 'error', 'message' => 'Phone verification failed']);
}

$drcash = send_to_drcash($name, $phone, $subid);
log_to_sheet(
    $timestamp,
    $name,
    $phone,
    $source,
    $subid,
    $drcash['ok'] ? 'drcash_sent' : 'drcash_error',
    (string) $drcash['http'],
    $drcash['body']
);

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_spanish_mobile(string $phone): array
{
    $url = 'https://api.veriphone.io/v2/verify?phone=' . rawurlencode($phone) . '&default_country=ES';
    $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'] ?? '') === 'ES'
        && ($body['phone_type'] ?? '') === 'mobile';
    return ['valid' => $valid, 'http' => $response['http'], 'body' => $response['body']];
}

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, '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 log_to_sheet(
    string $timestamp,
    string $name,
    string $phone,
    string $source,
    string $subid,
    string $status,
    string $drcashHttp,
    string $drcashResponse
): void {
    $payload = [
        'timestamp' => $timestamp,
        'name' => $name,
        'phone' => $phone,
        'country' => 'ES',
        'offer' => 'GlucoZen',
        'source' => $source,
        'subid' => $subid,
        'status' => $status,
        'drcash_http' => $drcashHttp,
        'drcash_response' => clean_text($drcashResponse, 1000),
    ];
    http_request(SHEET_WEBHOOK_URL, 'POST', json_encode($payload, JSON_UNESCAPED_UNICODE), [
        'Content-Type: text/plain; charset=utf-8',
    ]);
}

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_spanish_mobile($value): string
{
    $digits = preg_replace('/\D+/', '', (string) $value) ?? '';
    if (strpos($digits, '0034') === 0) {
        $digits = substr($digits, 4);
    } elseif (strpos($digits, '34') === 0) {
        $digits = substr($digits, 2);
    }
    return preg_match('/^[67]\d{8}$/', $digits) === 1 ? '+34' . $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;
}
