<?php
/**
 * API: Buscar NIT/CUI en Digifact (SufarmaERP)
 */

header('Content-Type: application/json');
require_once '../config/fel_config.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $identifier = $input['identifier'] ?? '';
    $type = $input['type'] ?? 'NIT';

    if (empty($identifier)) throw new Exception('Identificador requerido');

    $token = getFELToken();
    if (!$token) throw new Exception('Error de autenticación FEL');

    $nit_padd = str_pad(FEL_NIT_EMISOR, 12, "0", STR_PAD_LEFT);
    $url = FEL_API_URL . "/shared/get_name?" . http_build_query([
        "NIT" => $nit_padd,
        "IDENTIFIER" => $identifier,
        "USERNAME" => FEL_USUARIO
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: " . $token]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) throw new Exception('Error conectando con SAT');

    $data = json_decode($res, true);

    if (isset($data['NOMBRE'])) {
        echo json_encode([
            'success' => true,
            'data' => [
                'name' => $data['NOMBRE'],
                'address' => 'CIUDAD'
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'No encontrado']);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
