<?php
// ============================================================
//  ajax/create_keyword.php
//  Creates a new keyword in master table (or returns existing)
// ============================================================
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');
startSession();
getCurrentUser(); // auth check

$keyword = trim($_POST['keyword'] ?? '');
if (!$keyword) jsonResponse(false, 'Keyword text required');
if (mb_strlen($keyword) > 200) jsonResponse(false, 'Keyword too long (max 200 chars)');

$db = db();
try {
    // Check if already exists (case-insensitive)
    $stmt = $db->prepare("SELECT keyword_id FROM keywords WHERE LOWER(keyword) = LOWER(?)");
    $stmt->execute([$keyword]);
    $existing = $stmt->fetch();

    if ($existing) {
        jsonResponse(true, 'Keyword already exists', ['keyword_id' => (int)$existing['keyword_id']]);
    }

    // Insert new
    $stmt = $db->prepare("INSERT INTO keywords (keyword) VALUES (?)");
    $stmt->execute([$keyword]);
    $kwId = (int)$db->lastInsertId();

    jsonResponse(true, 'Keyword created', ['keyword_id' => $kwId]);

} catch (PDOException $e) {
    // Handle duplicate key race condition
    if ($e->getCode() == 23000) {
        $stmt = $db->prepare("SELECT keyword_id FROM keywords WHERE LOWER(keyword) = LOWER(?)");
        $stmt->execute([$keyword]);
        $row = $stmt->fetch();
        jsonResponse(true, 'Keyword exists', ['keyword_id' => (int)$row['keyword_id']]);
    }
    jsonResponse(false, 'DB error: ' . $e->getMessage());
}