<?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 la base de datos']); exit;
}
mysqli_set_charset($conn, 'utf8mb4');

$ruc          = trim((string)($_POST['ruc'] ?? ''));
$razon_social = trim((string)($_POST['razon_social'] ?? ''));
$alias        = trim((string)($_POST['alias'] ?? ''));
$servicios    = isset($_POST['servicios']) ? (int)$_POST['servicios'] : 0; // 0/1
$estado       = isset($_POST['estado']) ? (int)$_POST['estado'] : 1;       // 0/1

if (!preg_match('/^\d{13}$/', $ruc)) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'RUC inválido']); exit; }
if ($razon_social === '' || $alias === '') { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Razón social y Alias son obligatorios']); exit; }

try {
  if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); }

  $stmt = $conn->prepare("SELECT idempresa FROM tb_empresa WHERE ruc=? LIMIT 1");
  $stmt->bind_param('s',$ruc);
  $stmt->execute(); $stmt->store_result();
  if ($stmt->num_rows > 0) { http_response_code(409); echo json_encode(['success'=>false,'message'=>'El RUC ya existe']); exit; }
  $stmt->close();

  $stmt = $conn->prepare("INSERT INTO tb_empresa (ruc, razon_social, alias, servicios, estado, condicion) VALUES (?, ?, ?, ?, ?, 1)");
  $stmt->bind_param('sssii', $ruc, $razon_social, $alias, $servicios, $estado);
  $stmt->execute();
  $id = $stmt->insert_id; $stmt->close();

  echo json_encode(['success'=>true,'message'=>'Empresa registrada correctamente','data'=>[
    'idempresa'=>$id,'ruc'=>$ruc,'razon_social'=>$razon_social,'alias'=>$alias,'servicios'=>$servicios,'estado'=>$estado
  ]], JSON_UNESCAPED_UNICODE);

} catch(Throwable $e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error al guardar','error'=>$e->getMessage()]);
}
