<?php
// Savit API: Add research prompts to selected projects
// Ported from api-add-prompts-to-projects.php

header('Content-Type: application/json');

use CAE\Lib\Database;

$prompts_json = $_POST['prompts'] ?? '[]';
$project_ids_json = $_POST['project_ids'] ?? '[]';

$prompts_data = json_decode((string)$prompts_json, true);
$project_ids = json_decode((string)$project_ids_json, true);

if (empty($prompts_data) || empty($project_ids)) {
    echo json_encode(['success' => false, 'error' => 'No prompts or projects selected']);
    exit();
}

try {
    $db = Database::getInstance();
    $db->beginTransaction();

    foreach ($project_ids as $project_id) {
        foreach ($prompts_data as $p) {
            $text = trim((string)$p['text']);
            if (empty($text)) continue;

            // Check for duplicates
            $dup = $db->fetch("SELECT id FROM brand_prompts WHERE brand_id = ? AND prompt_text = ?", [(int)$project_id, $text]);
            if ($dup) continue;

            $vol = $p['volume'] ?? 0;
            $db->insert('brand_prompts', [
                'brand_id'    => (int)$project_id,
                'prompt_text' => $text,
                'ai_volume'   => (int)$vol
            ]);
        }
    }

    $db->commit();
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    $db->rollback();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
