<?php
/**
 * Colex AI - Period Stats Endpoint
 *
 * GET /api/colex/stats?period=current_week
 * GET /api/colex/stats?period=custom&date_from=YYYY-MM-DD&date_to=YYYY-MM-DD
 *
 * Returns the same greeting / context-card / suggested-prompt data that
 * public/colex.php renders on first load, so the frontend can refresh
 * it live without a full page reload whenever the period selector changes.
 */

// Ensure this file is accessed through the router
if (!isset($auth) || !isset($db)) {
    http_response_code(500);
    die(json_encode(['error' => 'Direct access not permitted.']));
}

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

// Ensure user is authenticated
if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Authentication required']);
    exit;
}

require_once __DIR__ . '/../../src/ColexHelpers.php';

$userId = $auth->getUserId();

$period = isset($_GET['period']) ? $_GET['period'] : 'current_week';
$customDateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : null;
$customDateTo = isset($_GET['date_to']) ? $_GET['date_to'] : null;

// Same authoritative user_profiles row public/colex.php reads on initial
// load — the AJAX refresh must never disagree with the page's own greeting.
// Name resolution goes through the one shared resolveDisplayName() (see
// RenderHelpers.php), not a second copy of the same fallback check.
$colexDisplayName = 'Trader';
$colexTimezone = null;
try {
    $colexProfileRow = $db->selectById('user_profiles', $userId, 'user_id');
    $colexDisplayName = resolveDisplayName($colexProfileRow);
    if ($colexProfileRow && !empty($colexProfileRow['timezone'])) {
        $colexTimezone = $colexProfileRow['timezone'];
    }
} catch (\Throwable $e) {
    error_log("colex/stats: failed to read display_name/timezone: " . $e->getMessage());
}

try {
    $dateRange = calculateDateRange($period, $customDateFrom, $customDateTo);
    $periodStats = getPeriodStats($db, $userId, $dateRange['from'], $dateRange['to']);
    $greeting = generateGreeting($periodStats, $period, $dateRange, $colexDisplayName, $colexTimezone);
    $contextCards = generateContextCards($periodStats);
    $suggestedPrompts = generateSuggestedPrompts($periodStats, $period, $dateRange);

    echo json_encode([
        'success' => true,
        'date_range' => $dateRange,
        'greeting' => $greeting,
        'cards' => $contextCards,
        'suggested_prompts' => $suggestedPrompts,
        'stats' => $periodStats
    ]);

} catch (Exception $e) {
    error_log("Error building Colex stats: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to load stats']);
}
