<?php
require __DIR__ . '/../init.php';
require_login();
$pdo = pdo();

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Agregar producto
    if (isset($_POST['add_product'])) {
        $name = trim($_POST['name'] ?? '');
        $sku = trim($_POST['sku'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $unit = trim($_POST['unit'] ?? '');
        $bg_color = trim($_POST['bg_color'] ?? '');

        if ($name === '') {
            $msg = 'Nombre requerido';
        } else {
            $stmt = $pdo->prepare("INSERT INTO products (name, sku, price, unit, bg_color, active) VALUES (?,?,?,?,?,1)");
            $stmt->execute([$name, $sku, $price, $unit, $bg_color ?: '#0d6efd']);
            header('Location: ' . site('admin/products.php'));
            exit;
        }
    }

    // Actualizar producto
    if (isset($_POST['update_product'])) {
        $id = (int)($_POST['product_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $sku = trim($_POST['sku'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $unit = trim($_POST['unit'] ?? '');
        $bg_color = trim($_POST['bg_color'] ?? '');

        if ($id <= 0 || $name === '') {
            $msg = 'Datos inválidos';
        } else {
            $stmt = $pdo->prepare("UPDATE products SET name=?, sku=?, price=?, unit=?, bg_color=? WHERE id=?");
            $stmt->execute([$name, $sku, $price, $unit, $bg_color ?: '#0d6efd', $id]);
            header('Location: ' . site('admin/products.php'));
            exit;
        }
    }

    // Eliminar producto
    if (isset($_POST['delete_product'])) {
        $id = (int)($_POST['product_id'] ?? 0);
        if ($id > 0) {
            $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$id]);
        }
        header('Location: ' . site('admin/products.php'));
        exit;
    }
}

// obtener productos
$products = $pdo->query("SELECT id,name,sku,price,unit,bg_color,active FROM products ORDER BY id")->fetchAll();
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Productos - Backoffice</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.color-input { width:46px; height:36px; padding:0; border:none; }
.table td { vertical-align:middle; }
.price-amount { font-weight:700; }
.tile-preview { width:140px; height:56px; border-radius:10px; display:flex; align-items:center; justify-content:center; color:#fff; font-weight:700; box-shadow:0 6px 18px rgba(2,6,23,0.06); }
</style>
</head>
<body class="p-3">
<a href="<?= site('admin/index.php') ?>">&laquo; Volver</a>
<h3>Productos</h3>

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

<!-- Form alta -->
<form method="post" class="row g-2 mb-3 align-items-center">
  <div class="col-md-3"><input name="name" class="form-control" placeholder="Nombre" required></div>
  <div class="col-md-2"><input name="sku" class="form-control" placeholder="SKU"></div>
  <div class="col-md-2"><input name="price" type="number" step="0.001" class="form-control" placeholder="Precio" required></div>
  <div class="col-md-2"><input name="unit" class="form-control" placeholder="Unidad (L/UN)"></div>
  <div class="col-md-1">
    <input type="color" name="bg_color" value="#0d6efd" class="form-control form-control-color" title="Color fondo">
  </div>
  <div class="col-md-2"><button name="add_product" class="btn btn-success">Agregar producto</button></div>
</form>

<table class="table table-sm table-striped">
<thead><tr><th>ID</th><th>Preview</th><th>Nombre</th><th>SKU</th><th>Precio</th><th>Unidad</th><th>Color</th><th></th></tr></thead>
<tbody>
<?php foreach($products as $p): ?>
  <tr>
    <td><?= $p['id'] ?></td>
    <td><div class="tile-preview" style="background:<?= htmlspecialchars($p['bg_color'] ?: '#0d6efd') ?>;">$<?= number_format($p['price'],3,'.','') ?></div></td>
    <td><?= htmlspecialchars($p['name']) ?></td>
    <td><?= htmlspecialchars($p['sku']) ?></td>
    <td>$<?= number_format($p['price'],3,'.','') ?></td>
    <td><?= htmlspecialchars($p['unit']) ?></td>
    <td><div style="width:28px;height:20px;background:<?= htmlspecialchars($p['bg_color'] ?: '#0d6efd') ?>;border-radius:4px;border:1px solid #e9eef6"></div></td>
    <td style="white-space:nowrap;">
      <!-- editar inline -->
      <form method="post" class="d-inline-block me-1">
        <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal<?= $p['id'] ?>">Editar</button>
      </form>

      <form method="post" class="d-inline-block" onsubmit="return confirm('Borrar producto?')">
        <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
        <button name="delete_product" class="btn btn-sm btn-danger">Borrar</button>
      </form>
    </td>
  </tr>

  <!-- Modal editar -->
  <div class="modal fade" id="editModal<?= $p['id'] ?>" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <form method="post" class="modal-body">
          <div class="modal-header">
            <h5 class="modal-title">Editar producto #<?= $p['id'] ?></h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
            <div class="mb-2"><label class="form-label small">Nombre</label><input name="name" class="form-control" value="<?= htmlspecialchars($p['name']) ?>" required></div>
            <div class="mb-2"><label class="form-label small">SKU</label><input name="sku" class="form-control" value="<?= htmlspecialchars($p['sku']) ?>"></div>
            <div class="mb-2"><label class="form-label small">Precio</label><input name="price" type="number" step="0.001" class="form-control" value="<?= htmlspecialchars($p['price']) ?>" required></div>
            <div class="mb-2"><label class="form-label small">Unidad</label><input name="unit" class="form-control" value="<?= htmlspecialchars($p['unit']) ?>"></div>
            <div class="mb-2"><label class="form-label small">Color fondo</label><input type="color" name="bg_color" value="<?= htmlspecialchars($p['bg_color'] ?: '#0d6efd') ?>" class="form-control form-control-color"></div>
          </div>
          <div class="modal-footer">
            <button type="submit" name="update_product" class="btn btn-primary">Guardar</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
          </div>
        </form>
      </div>
    </div>
  </div>

<?php endforeach; ?>
</tbody>
</table>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>