<?php
$title = 'Plataformas';
require_once __DIR__ . '/../templates/header.php';
require_role(['superadmin', 'admin']);
csrf_check();

$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  $name = trim($_POST['name'] ?? '');
  $desc = trim($_POST['description'] ?? '');

  if ($action === 'create') {
    $existing = pdo()->prepare('SELECT COUNT(*) FROM platforms WHERE name = ?');
    $existing->execute([$name]);
    if ($existing->fetchColumn() > 0) {
      $error = "El nombre de plataforma '$name' ya existe. Por favor, elige otro.";
    } else {
      $st = pdo()->prepare('INSERT INTO platforms (name, description) VALUES (?, ?)');
      $st->execute([$name, $desc]);
      header('Location: platforms.php');
      exit;
    }
  } elseif ($action === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      $existing = pdo()->prepare('SELECT COUNT(*) FROM platforms WHERE name = ? AND id <> ?');
      $existing->execute([$name, $id]);
      if ($existing->fetchColumn() > 0) {
        $error = "El nombre de plataforma '$name' ya existe en otro registro. Por favor, elige otro.";
      } else {
        $st = pdo()->prepare('UPDATE platforms SET name = ?, description = ? WHERE id = ?');
        $st->execute([$name, $desc, $id]);
        header('Location: platforms.php');
        exit;
      }
    }
  } elseif ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      $st = pdo()->prepare('DELETE FROM platforms WHERE id = ?');
      $st->execute([$id]);
      header('Location: platforms.php');
      exit;
    }
  }
}

// Búsqueda y paginación
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 4; // Cambia a 5 si quieres mostrar 5 registros por página
$offset = ($page - 1) * $perPage;

// Contar totales
$countSt = pdo()->prepare('SELECT COUNT(*) FROM platforms WHERE name LIKE :search OR description LIKE :search');
$countSt->execute(['search' => "%$search%"]);
$totalPlatforms = $countSt->fetchColumn();
$totalPages = ceil($totalPlatforms / $perPage);

// Obtener registros paginados
$st = pdo()->prepare('SELECT * FROM platforms WHERE name LIKE :search OR description LIKE :search ORDER BY id DESC LIMIT :limit OFFSET :offset');
$st->bindValue(':search', "%$search%", PDO::PARAM_STR);
$st->bindValue(':limit', $perPage, PDO::PARAM_INT);
$st->bindValue(':offset', $offset, PDO::PARAM_INT);
$st->execute();
$platforms = $st->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h3>Plataformas</h3>
  <button class="btn btn-success" data-bs-toggle="collapse" data-bs-target="#frmNew">+ Agregar plataforma</button>
</div>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<!-- Formulario búsqueda -->
<form method="get" class="mb-3" style="max-width:400px;">
  <div class="input-group">
    <input type="text" name="search" class="form-control" placeholder="Buscar por nombre o descripción" value="<?= e($search) ?>">
    <button class="btn btn-outline-primary" type="submit">Buscar</button>
  </div>
</form>

<div id="frmNew" class="collapse mb-3">
  <div class="card card-body">
    <form method="post" class="row g-2">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">
      <div class="col-md-4">
        <label class="form-label">Nombre</label>
        <input class="form-control" name="name" required placeholder="Disney+" value="<?= e($_POST['name'] ?? '') ?>">
      </div>
      <div class="col-md-8">
        <label class="form-label">Descripción</label>
        <input class="form-control" name="description" value="<?= e($_POST['description'] ?? '') ?>">
      </div>
      <div class="col-12">
        <button class="btn btn-primary">Guardar</button>
      </div>
    </form>
  </div>
</div>

<div class="table-responsive">
  <table class="table table-striped align-middle">
    <thead>
      <tr>
        <th>ID</th>
        <th>Nombre</th>
        <th>Descripción</th>
        <th>Acciones</th>
      </tr>
    </thead>
    <tbody>
      <?php if (count($platforms) === 0): ?>
        <tr><td colspan="4" class="text-center">No se encontraron plataformas.</td></tr>
      <?php endif; ?>
      <?php foreach ($platforms as $p): ?>
      <tr>
        <td><?= e($p['id']) ?></td>
        <td><?= e($p['name']) ?></td>
        <td><?= e($p['description'] ?? '') ?></td>
        <td>
          <button class="btn btn-sm btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#edit<?= e($p['id']) ?>">Editar</button>
          <form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar plataforma?');">
            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?= e($p['id']) ?>">
            <button class="btn btn-sm btn-outline-danger">Eliminar</button>
          </form>
        </td>
      </tr>
      <tr class="collapse" id="edit<?= e($p['id']) ?>">
        <td colspan="4">
          <div class="card card-body">
            <form method="post" class="row g-2">
              <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="id" value="<?= e($p['id']) ?>">
              <div class="col-md-4">
                <label class="form-label">Nombre</label>
                <input class="form-control" name="name" value="<?= e($p['name']) ?>">
              </div>
              <div class="col-md-8">
                <label class="form-label">Descripción</label>
                <input class="form-control" name="description" value="<?= e($p['description'] ?? '') ?>">
              </div>
              <div class="col-12">
                <button class="btn btn-primary">Actualizar</button>
              </div>
            </form>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<!-- Paginación -->
<nav aria-label="Paginación plataformas">
  <ul class="pagination justify-content-center">
    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
      <a class="page-link" href="?search=<?= urlencode($search) ?>&page=<?= $page - 1 ?>" tabindex="-1">Anterior</a>
    </li>
    <?php for ($i=1; $i <= $totalPages; $i++): ?>
    <li class="page-item <?= $page === $i ? 'active' : '' ?>">
      <a class="page-link" href="?search=<?= urlencode($search) ?>&page=<?= $i ?>"><?= $i ?></a>
    </li>
    <?php endfor; ?>
    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
      <a class="page-link" href="?search=<?= urlencode($search) ?>&page=<?= $page + 1 ?>">Siguiente</a>
    </li>
  </ul>
</nav>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php require_once __DIR__ . '/../templates/footer.php'; ?>
