<?php
// ../../Controlador/Ctrl_Administrador/MySQL_Borrar_Galonera.php
session_start();

require_once "../Utilidades/Conexion_BD.php";
require_once "../Utilidades/Auditoria.php";

if (!isset($_SESSION['usuario'])) {
  header("Location: ../../Controlador/Utilidades/Sesion_Destroy.php");
  exit();
}

if (empty($_GET['IDG'])) {
  header("Location: ../../Vista/Administrador/Adm_Gestion_Galoneras.php");
  exit();
}

$id_galonera = (int) $_GET['IDG'];

$conn = new Conexion_BD();
$db   = $conn->getConnection();

/* 1) Verificar existencia */
$sqlExiste = "SELECT id FROM galoneras WHERE id = ?";
$stmt = $conn->prepare($sqlExiste);
$stmt->bind_param("i", $id_galonera);
$stmt->execute();
$res = $stmt->get_result();
if (!$res || $res->num_rows === 0) {
  $stmt->close();
  $conn->closeConnection();
  $_SESSION['error_eliminar_galonera'] = "No se encontró la galonera con ID: $id_galonera.";
  header("Location: ../../Vista/Administrador/Adm_Gestion_Galoneras.php");
  exit();
}
$stmt->close();

/* 2) Verificar dependencias directas en control_abastecimiento_galonera */
$totalDep = 0;
$sqlDep = "SELECT COUNT(*) AS total FROM control_abastecimiento_galonera WHERE galonera_id = ?";
$stmt = $conn->prepare($sqlDep);
$stmt->bind_param("i", $id_galonera);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$totalDep += (int)($row['total'] ?? 0);
$stmt->close();

if ($totalDep > 0) {
  $conn->closeConnection();
  $_SESSION['error_eliminar_galonera'] =
    "No se puede eliminar: la galonera tiene $totalDep abastecimiento(s) registrado(s).";
  header("Location: ../../Vista/Administrador/Adm_Gestion_Galoneras.php");
  exit();
}

/* 2b) (Opcional/defensivo) Verificar si control_combustible tiene columna relacionada */
$columnaGalonera = null;
$sqlCol = "
  SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME   = 'control_combustible'
    AND COLUMN_NAME IN ('galonera_id','id_galonera','galonera','galoneraId')
  LIMIT 1";
if ($rs = $db->query($sqlCol)) {
  if ($r = $rs->fetch_assoc()) {
    $columnaGalonera = $r['COLUMN_NAME'] ?? null;
  }
  $rs->free();
}
if ($columnaGalonera) {
  $sqlCheck = "SELECT COUNT(*) AS total FROM control_combustible WHERE `$columnaGalonera` = ?";
  $stmt = $conn->prepare($sqlCheck);
  $stmt->bind_param("i", $id_galonera);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $depCC = (int)($row['total'] ?? 0);
  $stmt->close();

  if ($depCC > 0) {
    $conn->closeConnection();
    $_SESSION['error_eliminar_galonera'] =
      "No se puede eliminar: hay $depCC registro(s) en control_combustible vinculados a la galonera.";
    header("Location: ../../Vista/Administrador/Adm_Gestion_Galoneras.php");
    exit();
  }
}

/* 3) Borrado con transacción */
$db->begin_transaction();
try {
  // 3.1 Eliminar historial (si existe la tabla)
  $tieneHist = 0;
  $sqlExisteTablaHist = "
    SELECT COUNT(*) AS n
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'galonera_estado_historial'";
  if ($rs = $db->query($sqlExisteTablaHist)) {
    $tieneHist = (int)($rs->fetch_assoc()['n'] ?? 0);
    $rs->free();
  }
  if ($tieneHist > 0) {
    $sqlDelHist = "DELETE FROM galonera_estado_historial WHERE galonera_id = ?";
    $stmt = $conn->prepare($sqlDelHist);
    $stmt->bind_param("i", $id_galonera);
    $stmt->execute();
    $stmt->close();
  }

  // 3.2 Eliminar galonera
  $sqlDel = "DELETE FROM galoneras WHERE id = ?";
  $stmt = $conn->prepare($sqlDel);
  $stmt->bind_param("i", $id_galonera);
  $stmt->execute();
  $af = $stmt->affected_rows;
  $stmt->close();

  if ($af <= 0) {
    throw new Exception("La eliminación no afectó ninguna fila.");
  }

  // 3.3 Auditoría
  $id_usuario     = $_SESSION['id_usuario'] ?? 0;
  $nombre_usuario = $_SESSION['nombre'] ?? ($_SESSION['usuario'] ?? 'sistema');
  $tipo_usuario   = $_SESSION['rol'] ?? '';
  $descripcion    = "Se eliminó la galonera con ID: $id_galonera";

  registrarAuditoria(
    'galoneras',
    'eliminar',
    $descripcion,
    $id_usuario,
    $nombre_usuario,
    'galoneras',
    $id_galonera,
    $tipo_usuario
  );

  $db->commit();

  $_SESSION['id_galonera_eliminada'] = $id_galonera;
  $conn->closeConnection();
  header("Location: ../../Vista/Administrador/Adm_Gestion_Galoneras.php");
  exit();

} catch (Throwable $e) {
  $db->rollback();
  $conn->closeConnection();
  $_SESSION['error_eliminar_galonera'] = "Error al eliminar: " . $e->getMessage();
  header("Location: ../../Vista/Administrador/Adm_Gestion_Galoneras.php");
  exit();
}
