<?php
require_once 'config.php';
require_once 'middleware.php';

header('Content-Type: application/json; charset=utf-8');

$negocio_id = validarToken();
$method     = $_SERVER['REQUEST_METHOD'];
$db         = getDB();
$MAX        = 50;

// GET — listar keywords del negocio
if ($method === 'GET') {
    $stmt = $db->prepare('SELECT id, keyword FROM keywords WHERE negocio_id = ? ORDER BY id ASC');
    $stmt->execute([$negocio_id]);
    jsonResponse($stmt->fetchAll());
}

// POST — agregar keyword
if ($method === 'POST') {
    $data    = getJsonInput();
    $keyword = trim(strtolower($data['keyword'] ?? ''));

    if (!$keyword) jsonResponse(['error' => 'Keyword vacía'], 400);
    if (strlen($keyword) > 60) jsonResponse(['error' => 'Máximo 60 caracteres por keyword'], 400);

    $stmt = $db->prepare('SELECT COUNT(*) FROM keywords WHERE negocio_id = ?');
    $stmt->execute([$negocio_id]);
    if ((int)$stmt->fetchColumn() >= $MAX) {
        jsonResponse(['error' => "Límite de $MAX keywords alcanzado"], 400);
    }

    try {
        $db->prepare('INSERT INTO keywords (negocio_id, keyword) VALUES (?, ?)')
           ->execute([$negocio_id, $keyword]);
        jsonResponse(['id' => (int)$db->lastInsertId(), 'keyword' => $keyword], 201);
    } catch (\Exception $e) {
        jsonResponse(['error' => 'Esa keyword ya existe'], 409);
    }
}

// DELETE ?id=X — eliminar keyword
if ($method === 'DELETE') {
    $id = (int)($_GET['id'] ?? 0);
    if (!$id) jsonResponse(['error' => 'ID requerido'], 400);

    $db->prepare('DELETE FROM keywords WHERE id = ? AND negocio_id = ?')
       ->execute([$id, $negocio_id]);
    jsonResponse(['ok' => true]);
}

jsonResponse(['error' => 'Método no permitido'], 405);
