<?php
require_auth();
require_permission('ai.view');
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    csrf_check();
    if (!function_exists('hv4_generate_insights')) json_error('V4 not loaded', 503);
    $insights = hv4_generate_insights();
    json_ok(['insights' => $insights, 'generated' => true]);
}

$rows = [];
if (hv4_table_exists('ai_insights')) {
    $rows = db()->query('SELECT * FROM ai_insights ORDER BY created_at DESC LIMIT 20')->fetchAll();
}
if (!$rows && function_exists('hv4_generate_insights')) {
    $generated = hv4_generate_insights();
    json_ok(['insights' => $generated, 'live' => true]);
}
json_ok(['insights' => $rows, 'live' => true]);
