<?php
// admin/pumps.php - Gestión de bombas con edición y reemplazo de imagen sin borrar la bomba
require __DIR__ . '/../init.php';
require_login();
$pdo = pdo();
$config = require __DIR__ . '/../config.php';

// Asegurar carpeta uploads/pumps existe
$uploadPumpsDir = rtrim($config->upload_dir, '/\\') . '/pumps';
if (!is_dir($uploadPumpsDir)) {
    @mkdir($uploadPumpsDir, 0777, true);
}

$msg = '';

// Helper: eliminar fichero de imagen si existe (tanto image_filename como {id}.png/.jpg)
function removePumpImageFiles($uploadDir, $filenameCandidate, $pumpId) {
    // eliminar nombre explícito
    if ($filenameCandidate) {
        $f = $uploadDir . '/' . $filenameCandidate;
        if (file_exists($f)) @unlink($f);
    }
    // eliminar por id con extensiones comunes
    foreach (['png','jpg','jpeg','webp'] as $ext) {
        $f2 = $uploadDir . '/' . $pumpId . '.' . $ext;
        if (file_exists($f2)) @unlink($f2);
    }
}

// Procesar formularios
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Agregar bomba (crear)
    if (isset($_POST['add_pump'])) {
        $name = trim($_POST['name'] ?? '');
        $location = trim($_POST['location'] ?? '');

        if ($name === '') {
            $msg = "Nombre de bomba requerido.";
        } else {
            $stmt = $pdo->prepare("INSERT INTO pumps (name, location, created_at) VALUES (?, ?, NOW())");
            $stmt->execute([$name, $location]);
            $pumpId = $pdo->lastInsertId();

            // manejar imagen subida (opcional)
            if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $tmp = $_FILES['image']['tmp_name'];
                $origName = basename($_FILES['image']['name']);
                $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
                $allowed = ['png','jpg','jpeg','webp'];
                if (in_array($ext, $allowed, true)) {
                    $newName = $pumpId . '.' . $ext;
                    $dest = $uploadPumpsDir . '/' . $newName;
                    if (move_uploaded_file($tmp, $dest)) {
                        $pdo->prepare("UPDATE pumps SET image_filename = ? WHERE id = ?")->execute([$newName, $pumpId]);
                    } else {
                        $msg = "No se pudo mover la imagen subida.";
                    }
                } else {
                    $msg = "Formato de imagen no permitido. Use png/jpg/jpeg/webp.";
                }
            }

            if ($msg === '') {
                header('Location: ' . site('admin/pumps.php'));
                exit;
            }
        }
    }

    // Actualizar bomba (editar nombre/ubicación y opcional reemplazar imagen)
    if (isset($_POST['update_pump'])) {
        $pumpId = (int)($_POST['pump_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $location = trim($_POST['location'] ?? '');

        if ($pumpId <= 0 || $name === '') {
            $msg = "Datos inválidos para actualizar.";
        } else {
            // Actualizar nombre/ubicación
            $pdo->prepare("UPDATE pumps SET name = ?, location = ? WHERE id = ?")->execute([$name, $location, $pumpId]);

            // Procesar posible imagen nueva
            if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                // eliminar imagen previa (si existe)
                $stmt = $pdo->prepare("SELECT image_filename FROM pumps WHERE id = ?");
                $stmt->execute([$pumpId]);
                $row = $stmt->fetch();
                $prev = $row['image_filename'] ?? null;
                removePumpImageFiles($uploadPumpsDir, $prev, $pumpId);

                $tmp = $_FILES['image']['tmp_name'];
                $origName = basename($_FILES['image']['name']);
                $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
                $allowed = ['png','jpg','jpeg','webp'];
                if (in_array($ext, $allowed, true)) {
                    $newName = $pumpId . '.' . $ext;
                    $dest = $uploadPumpsDir . '/' . $newName;
                    if (move_uploaded_file($tmp, $dest)) {
                        $pdo->prepare("UPDATE pumps SET image_filename = ? WHERE id = ?")->execute([$newName, $pumpId]);
                    } else {
                        $msg = "No se pudo mover la imagen subida.";
                    }
                } else {
                    $msg = "Formato de imagen no permitido. Use png/jpg/jpeg/webp.";
                }
            }

            if ($msg === '') {
                header('Location: ' . site('admin/pumps.php'));
                exit;
            }
        }
    }

    // Eliminar imagen de bomba (sin borrar registro)
    if (isset($_POST['remove_image'])) {
        $pumpId = (int)($_POST['pump_id'] ?? 0);
        if ($pumpId > 0) {
            // obtener nombre y eliminar ficheros
            $stmt = $pdo->prepare("SELECT image_filename FROM pumps WHERE id = ?");
            $stmt->execute([$pumpId]);
            $row = $stmt->fetch();
            $prev = $row['image_filename'] ?? null;
            removePumpImageFiles($uploadPumpsDir, $prev, $pumpId);
            // actualizar DB a NULL
            $pdo->prepare("UPDATE pumps SET image_filename = NULL WHERE id = ?")->execute([$pumpId]);
        }
        header('Location: ' . site('admin/pumps.php'));
        exit;
    }

    // Agregar manguera
    if (isset($_POST['add_hose'])) {
        $pump_id = (int)($_POST['pump_id'] ?? 0);
        $hname = trim($_POST['name'] ?? '');
        $product_id = (int)($_POST['product_id'] ?? 0);
        if ($pump_id && $hname && $product_id) {
            $pdo->prepare("INSERT INTO hoses (pump_id,name,product_id) VALUES (?,?,?)")->execute([$pump_id,$hname,$product_id]);
        }
        header('Location: ' . site('admin/pumps.php'));
        exit;
    }

    // Borrar manguera
    if (isset($_POST['delete_hose'])) {
        $hid = (int)($_POST['id'] ?? 0);
        if ($hid) {
            $pdo->prepare("DELETE FROM hoses WHERE id = ?")->execute([$hid]);
        }
        header('Location: ' . site('admin/pumps.php'));
        exit;
    }

    // Borrar bomba (completo) - elimina imagenes asociadas
    if (isset($_POST['delete_pump'])) {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
            // eliminar imagen si existe
            $stmt = $pdo->prepare("SELECT image_filename FROM pumps WHERE id = ?");
            $stmt->execute([$id]);
            $row = $stmt->fetch();
            if ($row && !empty($row['image_filename'])) {
                $fpath = $uploadPumpsDir . '/' . $row['image_filename'];
                if (file_exists($fpath)) @unlink($fpath);
            } else {
                // comprobar archivos por id.* también
                foreach (['png','jpg','jpeg','webp'] as $ext) {
                    $f2 = $uploadPumpsDir . '/' . $id . '.' . $ext;
                    if (file_exists($f2)) @unlink($f2);
                }
            }
            $pdo->prepare("DELETE FROM pumps WHERE id = ?")->execute([$id]);
        }
        header('Location: ' . site('admin/pumps.php'));
        exit;
    }
}

// obtener datos para mostrar
$pumps = $pdo->query("SELECT * FROM pumps ORDER BY id")->fetchAll();
$products = $pdo->query("SELECT id,name FROM products WHERE active=1")->fetchAll();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bombas - Backoffice</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.pump-thumb { width:72px; height:72px; object-fit:contain; border-radius:8px; background:#fff; border:1px solid #eef2f6; padding:6px; }
.card-thumb { display:flex; gap:12px; align-items:center; }
.form-inline-sm .form-control { height: calc(1.5em + .5rem + 2px); padding:.25rem .5rem; }
</style>
</head>
<body class="p-3">
<a href="<?= site('admin/index.php') ?>">&laquo; Volver</a>
<h3>Bombas y Mangueras</h3>

<?php if ($msg): ?><div class="alert alert-warning"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

<!-- Form: Añadir bomba (con imagen opcional) -->
<form method="post" enctype="multipart/form-data" class="row g-2 mb-3">
  <div class="col-md-4"><input name="name" class="form-control" placeholder="Nombre bomba" required></div>
  <div class="col-md-4"><input name="location" class="form-control" placeholder="Ubicación"></div>
  <div class="col-md-2"><input type="file" name="image" accept="image/*" class="form-control"></div>
  <div class="col-md-2"><button name="add_pump" class="btn btn-success">Agregar bomba</button></div>
</form>

<?php foreach($pumps as $pump): ?>
  <div class="card mb-3">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-start">
        <div class="card-thumb">
          <?php
            // determinar URL de thumbnail (priorizar image_filename, luego id.* por compatibilidad, sino fallback SVG)
            $thumbUrl = site('assets/pump.svg');
            if (!empty($pump['image_filename'])) {
                $thumbUrl = rtrim($config->upload_url,'/') . '/pumps/' . $pump['image_filename'];
            } else {
                // comprobar archivos por id
                foreach (['png','jpg','jpeg','webp'] as $ext) {
                    $cand = $uploadPumpsDir . '/' . $pump['id'] . '.' . $ext;
                    if (file_exists($cand)) {
                        $thumbUrl = rtrim($config->upload_url,'/') . '/pumps/' . $pump['id'] . '.' . $ext;
                        break;
                    }
                }
            }
          ?>
          <img src="<?= htmlspecialchars($thumbUrl) ?>" alt="<?= htmlspecialchars($pump['name']) ?>" class="pump-thumb">
          <div>
            <h5 class="mb-0"><?= htmlspecialchars($pump['name']) ?></h5>
            <small class="text-muted"><?= htmlspecialchars($pump['location']) ?></small>
          </div>
        </div>

        <div style="min-width:280px;">
          <!-- Form editar bomba + cambiar imagen -->
          <form method="post" enctype="multipart/form-data" class="row g-2 form-inline-sm">
            <input type="hidden" name="pump_id" value="<?= $pump['id'] ?>">
            <div class="col-12 col-md-5">
              <label class="form-label small mb-1">Nombre</label>
              <input name="name" class="form-control form-control-sm" value="<?= htmlspecialchars($pump['name']) ?>" required>
            </div>
            <div class="col-12 col-md-5">
              <label class="form-label small mb-1">Ubicación</label>
              <input name="location" class="form-control form-control-sm" value="<?= htmlspecialchars($pump['location']) ?>">
            </div>
            <div class="col-12 col-md-12 d-flex gap-2 mt-1 align-items-center">
              <input type="file" name="image" accept="image/*" class="form-control form-control-sm" style="max-width:200px;">
              <button name="update_pump" class="btn btn-primary btn-sm">Guardar cambios</button>

              <!-- eliminar imagen si existe -->
              <?php if (!empty($pump['image_filename']) || file_exists($uploadPumpsDir . '/' . $pump['id'] . '.png') || file_exists($uploadPumpsDir . '/' . $pump['id'] . '.jpg')): ?>
                <form method="post" style="display:inline">
                  <input type="hidden" name="pump_id" value="<?= $pump['id'] ?>">
                  <button name="remove_image" class="btn btn-outline-danger btn-sm" onclick="return confirm('Eliminar imagen de esta bomba?')">Eliminar imagen</button>
                </form>
              <?php endif; ?>
            </div>
          </form>
        </div>

        <div class="text-end">
          <form method="post" onsubmit="return confirm('Borrar bomba y sus mangueras?')">
            <input type="hidden" name="id" value="<?= $pump['id'] ?>">
            <button name="delete_pump" class="btn btn-danger btn-sm">Borrar bomba</button>
          </form>
        </div>
      </div>

      <hr>
      <div>
        <strong>Mangueras</strong>
        <ul class="mb-1">
        <?php
          $hoses = $pdo->prepare("SELECT h.*, p.name as prod FROM hoses h JOIN products p ON p.id=h.product_id WHERE h.pump_id=?");
          $hoses->execute([$pump['id']]);
          foreach($hoses->fetchAll() as $h):
        ?>
          <li><?= htmlspecialchars($h['name']) ?> - <?= htmlspecialchars($h['prod']) ?>
            <form method="post" style="display:inline"><input type="hidden" name="id" value="<?= $h['id'] ?>"><button name="delete_hose" class="btn btn-sm btn-link text-danger">Borrar</button></form>
          </li>
        <?php endforeach; ?>
        </ul>

        <!-- Form añadir manguera -->
        <form method="post" class="row g-2">
          <input type="hidden" name="pump_id" value="<?= $pump['id'] ?>">
          <div class="col-md-4"><input name="name" class="form-control form-control-sm" placeholder="Nombre manguera" required></div>
          <div class="col-md-4">
            <select name="product_id" class="form-select form-select-sm">
              <?php foreach($products as $pr): ?>
                <option value="<?= $pr['id'] ?>"><?= htmlspecialchars($pr['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4"><button name="add_hose" class="btn btn-primary btn-sm">Agregar manguera</button></div>
        </form>
      </div>

    </div>
  </div>
<?php endforeach; ?>

</body>
</html>