<?php
// api/buscar_ruc.php
declare(strict_types=1);
session_start();
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../conex.php';
$db = $conn ?? ($conex ?? null);
if (!$db) {
  echo json_encode(['success'=>false,'message'=>'Sin conexión']); exit;
}

mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone='-05:00'");

// Acepta POST o GET
$ruc = trim((string)($_POST['ruc'] ?? $_GET['ruc'] ?? ''));

// Normaliza: solo dígitos (útil para RUC/RUC+DV)
$ruc = preg_replace('/\D+/', '', $ruc);

if ($ruc === '') {
  echo json_encode(['success'=>false,'message'=>'RUC vacío']); exit;
}

$stmt = mysqli_prepare($db, "SELECT idempresa, razon_social FROM tb_empresa WHERE ruc = ? LIMIT 1");
if (!$stmt) {
  echo json_encode(['success'=>false,'message'=>'Error prepare: '.mysqli_error($db)]); exit;
}
mysqli_stmt_bind_param($stmt, 's', $ruc);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $idempresa, $razon);
$found = mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);

if ($found) {
  echo json_encode([
    'success'      => true,
    'idempresa'    => (int)$idempresa,
    'razon_social' => (string)$razon,
    'ruc'          => $ruc
  ]);
} else {
  echo json_encode([
    'success' => false,
    'message' => 'Empresa no encontrada',
    'ruc'     => $ruc
  ]);
}
