<?php
// api/empresa_buscar.php — Busca empresa por RUC/Cédula en tb_empresa
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');

$ruc = trim((string)($_GET['ruc'] ?? ''));
if ($ruc === '') { echo json_encode(['success'=>false,'message'=>'RUC/Cédula vacío']); exit; }

$sql = "SELECT idempresa, ruc, razon_social
        FROM tb_empresa
        WHERE condicion = 1 AND ruc = ?
        LIMIT 1";
$stmt = mysqli_prepare($db, $sql);
if (!$stmt) { echo json_encode(['success'=>false,'message'=>'Error al preparar: '.mysqli_error($db)]); exit; }
mysqli_stmt_bind_param($stmt, 's', $ruc);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($res)){
  echo json_encode([
    'success' => true,
    'idempresa' => (int)$row['idempresa'],
    'ruc' => (string)$row['ruc'],
    'razon_social' => (string)$row['razon_social']
  ], JSON_UNESCAPED_UNICODE);
} else {
  echo json_encode(['success'=>false, 'message'=>'No encontrada']);
}
