<?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');

$idempresa = isset($_POST['idempresa']) ? (int)$_POST['idempresa'] : 0;
$hard      = isset($_POST['hard']) ? (int)$_POST['hard'] : 0;

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

try{
  if ($hard === 1) {
    $stmt = $conn->prepare("DELETE FROM tb_empresa WHERE idempresa=?");
    $stmt->bind_param('i',$idempresa);
    $stmt->execute(); $af = $stmt->affected_rows; $stmt->close();
    echo json_encode(['success'=>true,'message'=> $af>0 ? 'Empresa eliminada definitivamente' : 'Nada para eliminar']);
  } else {
    $stmt = $conn->prepare("UPDATE tb_empresa SET condicion=0 WHERE idempresa=?");
    $stmt->bind_param('i',$idempresa);
    $stmt->execute(); $af = $stmt->affected_rows; $stmt->close();
    echo json_encode(['success'=>true,'message'=> $af>0 ? 'Empresa desactivada' : 'Nada para desactivar']);
  }
}catch(Throwable $e){
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Error al eliminar','error'=>$e->getMessage()]);
}
