<?php
// Savit API: Delete research prompts
// Ported from api-delete-prompt.php

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

use CAE\Lib\Database;

$prompt_ids = $_POST['prompt_ids'] ?? [];

if (empty($prompt_ids)) {
    echo json_encode(['success' => false, 'error' => 'No prompts selected']);
    exit();
}

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

    foreach ($prompt_ids as $id) {
        $id = (int)$id;
        // Delete runs and links first
        $runs = $db->fetchAll("SELECT id FROM prompt_runs WHERE prompt_id = ?", [$id]);
        foreach ($runs as $run) {
            $db->delete('prompt_run_links', 'run_id = ?', [(int)$run['id']]);
        }
        $db->delete('prompt_runs', 'prompt_id = ?', [$id]);
        $db->delete('brand_prompts', 'id = ?', [$id]);
    }

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

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