<?php
declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['success'=>false,'message'=>'No autorizado']); exit;
}
require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !$conn instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Sin conexión a BD']); exit;
}
mysqli_set_charset($conn, 'utf8mb4');

$id = isset($_GET['idempresa']) ? (int)$_GET['idempresa'] : 0;
if ($id <= 0) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'ID inválido']); exit; }

$stmt = $conn->prepare("SELECT idempresa, ruc, razon_social, alias, servicios, estado FROM tb_empresa WHERE idempresa=? LIMIT 1");
$stmt->bind_param('i',$id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();

if(!$row){ http_response_code(404); echo json_encode(['success'=>false,'message'=>'No encontrado']); exit; }

echo json_encode(['success'=>true,'data'=>[
  'idempresa'=>(int)$row['idempresa'],
  'ruc'=>$row['ruc'],
  'razon_social'=>$row['razon_social'],
  'alias'=>$row['alias'],
  'servicios'=>(int)$row['servicios'],
  'estado'=>(int)$row['estado'],
]], JSON_UNESCAPED_UNICODE);
