<?php
/**
 * GET /api/user/history.php
 * آخر محادثات المستخدم لإرشاد المساعد الشخصي
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/Logger.php';

$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];
if (!$u) { http_response_code(401); die(json_encode(['error'=>'unauthorized'])); }

$uid   = (int)$u['id'];
$limit = min(20, max(1, (int)($_GET['limit'] ?? 10)));

try {
    $history = db()->prepare(
        "SELECT sector, LEFT(question,100) as question,
                LEFT(answer,200) as answer_preview, created_at
         FROM execution_log WHERE user_id=?
         ORDER BY created_at DESC LIMIT ?"
    );
    $history->execute([$uid, $limit]);
    $rows = $history->fetchAll();

    // أكثر القطاعات استخداماً
    $sectors = array_count_values(array_column($rows, 'sector'));
    arsort($sectors);

    echo json_encode([
        'history'        => $rows,
        'top_sector'     => array_key_first($sectors) ?? 'general',
        'sector_counts'  => $sectors,
        'total'          => count($rows),
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode(['history' => [], 'top_sector' => 'general', 'total' => 0]);
}
