<?php
require_once dirname(__DIR__) . '/auth.php';
require_once dirname(__DIR__) . '/includes/config.php';
$pdo = pdo();
$pageTitle = 'Categorías';

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['add_category']) && !empty($_POST['new_category'])) {
            $stmt = $pdo->prepare("INSERT IGNORE INTO categories (name) VALUES (?)");
            $stmt->execute([trim($_POST['new_category'])]);
            $success_message = 'Category added';
        }
        if (isset($_POST['edit_category'], $_POST['category_id'], $_POST['edit_category_name'])) {
            $stmt = $pdo->prepare("UPDATE categories SET name=? WHERE id=?");
            $stmt->execute([trim($_POST['edit_category_name']), (int)$_POST['category_id']]);
            $success_message = 'Category updated';
        }
        if (isset($_POST['delete_category'], $_POST['category_id'])) {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("DELETE FROM channels WHERE category_id=?");
            $stmt->execute([(int)$_POST['category_id']]);
            $stmt = $pdo->prepare("DELETE FROM categories WHERE id=?");
            $stmt->execute([(int)$_POST['category_id']]);
            $pdo->commit();
            $success_message = 'Category deleted';
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $error_message = $e->getMessage();
    }
}

$categories = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll();

include dirname(__DIR__) . '/includes/header.php';
?>

<div class="card">
  <h2 style="margin-bottom:.75rem;">Administrar Categorías</h2>
  <?php if ($success_message): ?><div class="flash success"><?= h($success_message) ?></div><?php endif; ?>
  <?php if ($error_message): ?><div class="flash error"><?= h($error_message) ?></div><?php endif; ?>

  <form method="POST" style="margin:.5rem 0 1rem; display:flex; gap:.5rem; align-items:center;">
    <input type="text" name="new_category" placeholder="Nombre de categoría" required>
    <button type="submit" name="add_category" class="btn btn-primary">Agregar</button>
  </form>

  <table>
    <thead><tr><th>Nombre</th><th style="width:220px">Acciones</th></tr></thead>
    <tbody>
      <?php foreach ($categories as $cat): ?>
        <tr>
          <td>
            <form method="POST" class="actions" style="gap:.5rem;">
              <input type="hidden" name="category_id" value="<?= h($cat['id']) ?>">
              <input type="text" name="edit_category_name" value="<?= h($cat['name']) ?>" style="max-width:300px;">
              <button type="submit" name="edit_category" class="btn btn-primary">Guardar</button>
              <button type="submit" name="delete_category" class="btn btn-danger" onclick="return confirm('Eliminar categoría y sus canales?')">Eliminar</button>
            </form>
          </td>
          <td></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<?php include dirname(__DIR__) . '/includes/footer.php';
