<?php
// api/buscar_empresa.php
declare(strict_types=1);
session_start();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

// ⬇️ Ajusta la ruta a tu archivo de conexión
require_once __DIR__ . '/../conex.php';

// Soporta $conn o $conex
$db = $conn ?? ($conex ?? null);
if (!$db) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => 'Sin conexión a la base de datos']);
  exit;
}

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

// Recibir parámetro
$chasis = trim($_GET['chasis'] ?? $_POST['chasis'] ?? '');

if ($chasis === '') {
  http_response_code(400);
  echo json_encode(['success' => false, 'message' => 'Debe enviar el chasis']);
  exit;
}

// Consulta
$sql = "SELECT sp.id_empresa 
        FROM tb_datadai AS d
        INNER JOIN tb_solicitudprevia AS sp ON sp.idsolicitudprevia = d.id_solicitudprevia
        WHERE d.condicion = 1 AND d.chasis = ? 
        LIMIT 1";

$stmt = $db->prepare($sql);
if (!$stmt) {
  echo json_encode(['success' => false, 'message' => 'Error en prepare: ' . $db->error]);
  exit;
}

$stmt->bind_param('s', $chasis);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
  echo json_encode(['success' => true, 'id_empresa' => (int)$row['id_empresa']]);
} else {
  echo json_encode(['success' => false, 'message' => 'No se encontró empresa para este chasis']);
}

$stmt->close();
$db->close();
