<?php
// TEST RUC API - Standalone test file
// Upload this to backend/public/test_ruc.php and access via browser
// https://back.italvettools.com/test_ruc.php?ruc=20601214831

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

$ruc = $_GET['ruc'] ?? '20601214831';
$ruc = preg_replace('/[^0-9]/', '', $ruc);

if (strlen($ruc) !== 11) {
    echo json_encode(['success' => false, 'message' => 'RUC inválido: ' . $ruc]);
    exit;
}

// Try all possible ways to get the token
$token = $_ENV['TOKEN_APIPERUDEV'] ?? getenv('TOKEN_APIPERUDEV') ?: '';

// If token is empty, try reading .env directly
if (empty($token)) {
    $envFile = __DIR__ . '/../.env';
    if (file_exists($envFile)) {
        $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            if (str_starts_with(trim($line), 'TOKEN_APIPERUDEV=')) {
                $token = trim(substr($line, strlen('TOKEN_APIPERUDEV=')));
                break;
            }
        }
    }
}

$diagnostics = [
    'ruc' => $ruc,
    'token_found' => !empty($token),
    'token_prefix' => $token ? substr($token, 0, 10) . '...' : 'NONE',
    'curl_available' => function_exists('curl_init'),
    'php_version' => PHP_VERSION,
    'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'unknown',
];

// Make the API call
$ch = curl_init('https://apiperu.dev/api/ruc');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode(['ruc' => $ruc]),
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Content-Type: application/json',
        'Authorization: Bearer ' . $token,
    ],
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 0,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$diagnostics['api_http_code'] = $httpCode;
$diagnostics['curl_error'] = $err ?: null;
$diagnostics['api_response'] = $response ? json_decode($response, true) : null;
$diagnostics['curl_info'] = [
    'total_time' => $info['total_time'],
    'namelookup_time' => $info['namelookup_time'],
    'connect_time' => $info['connect_time'],
    'pretransfer_time' => $info['pretransfer_time'],
    'starttransfer_time' => $info['starttransfer_time'],
    'primary_ip' => $info['primary_ip'],
    'primary_port' => $info['primary_port'],
];

if (!$err && $httpCode === 200 && $response) {
    $data = json_decode($response, true);
    if ($data['success'] ?? false) {
        $d = $data['data'] ?? [];
        echo json_encode([
            'success' => true,
            'diagnostics' => $diagnostics,
            'data' => [
                'ruc' => $d['ruc'] ?? $ruc,
                'business_name' => $d['nombre_o_razon_social'] ?? '',
                'address' => $d['direccion'] ?? $d['direccion_completa'] ?? '',
            ],
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

echo json_encode([
    'success' => false,
    'diagnostics' => $diagnostics,
    'message' => $err ? "cURL Error: $err" : 'API returned HTTP ' . $httpCode,
], JSON_UNESCAPED_UNICODE);
