<?php
// Savit API: Fetch research prompts for a project
// Ported from api-fetch-prompts.php

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

use CAE\Lib\Database;

$project_id = $_GET['brand_id'] ?? null;
$search = $_GET['search'] ?? '';
$page = (int)($_GET['page'] ?? 1);
$limit = (int)($_GET['limit'] ?? 10);
$offset = ($page - 1) * $limit;

if (!$project_id) {
    echo json_encode(['success' => false, 'error' => 'Project ID is required']);
    exit();
}

try {
    $db = Database::getInstance();
    
    $where = "brand_id = :project_id";
    $params = ['project_id' => (int)$project_id];

    if (!empty($search)) {
        $where .= " AND prompt_text LIKE :search";
        $params['search'] = '%' . $search . '%';
    }

    $total = $db->count('brand_prompts', $where, $params);
    
    $sql = "SELECT * FROM brand_prompts WHERE {$where} ORDER BY created_at DESC LIMIT {$limit} OFFSET {$offset}";
    $data = $db->fetchAll($sql, $params);

    // For each prompt, calculate competitor mentions (from structured competitors table)
    foreach ($data as &$prompt) {
        $run = $db->fetch("SELECT ai_response FROM prompt_runs WHERE prompt_id = ? ORDER BY created_at DESC LIMIT 1", [$prompt['id']]);
        $comp_mentions = 0;
        if ($run && !empty($run['ai_response'])) {
            $resp = strtolower($run['ai_response']);
            $competitors = $db->fetchAll("SELECT competitor_name FROM competitors WHERE brand_id = ?", [(int)$project_id]);
            foreach ($competitors as $c) {
                if (!empty($c['competitor_name'])) {
                    $comp_mentions += substr_count($resp, strtolower($c['competitor_name']));
                }
            }
        }
        $prompt['competitors_mentions'] = $comp_mentions;
    }

    echo json_encode([
        'success' => true,
        'data' => $data,
        'total' => $total,
        'total_pages' => ceil($total / $limit)
    ]);

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