<?php
// Analytics API - Get user's search statistics
header('Content-Type: application/json');
require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';

$db = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit();
}

$userId = $auth->getCurrentUser()['id'];

// Total searches
$totalResult = $db->fetch(
    "SELECT COUNT(*) as count FROM search_logs WHERE user_id = ?",
    [$userId]
);
$totalSearches = $totalResult['count'] ?? 0;

// Mobile searches
$mobileResult = $db->fetch(
    "SELECT COUNT(*) as count FROM search_logs WHERE user_id = ? AND type = 'mobile'",
    [$userId]
);
$mobileSearches = $mobileResult['count'] ?? 0;

// Aadhaar searches
$aadhaarResult = $db->fetch(
    "SELECT COUNT(*) as count FROM search_logs WHERE user_id = ? AND type = 'aadhaar'",
    [$userId]
);
$aadhaarSearches = $aadhaarResult['count'] ?? 0;

// Credits spent
$creditsResult = $db->fetch(
    "SELECT SUM(cost) as total FROM search_logs WHERE user_id = ? AND status = 'success'",
    [$userId]
);
$creditsSpent = $creditsResult['total'] ?? 0;

// Current balance
$balanceResult = $db->fetch(
    "SELECT balance FROM wallets WHERE user_id = ?",
    [$userId]
);
$currentBalance = $balanceResult['balance'] ?? 0;

// Success rate
$successResult = $db->fetch(
    "SELECT COUNT(*) as count FROM search_logs WHERE user_id = ? AND status = 'success'",
    [$userId]
);
$successCount = $successResult['count'] ?? 0;
$successRate = $totalSearches > 0 ? round(($successCount / $totalSearches) * 100) : 0;

// Recent searches (last 5)
$recentSearches = $db->fetchAll(
    "SELECT type, query, created_at FROM search_logs WHERE user_id = ? ORDER BY created_at DESC LIMIT 5",
    [$userId]
);

// Format recent searches with time ago
$formattedRecent = [];
foreach ($recentSearches as $search) {
    $time = strtotime($search['created_at']);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        $timeAgo = 'just now';
    } elseif ($diff < 3600) {
        $timeAgo = floor($diff / 60) . ' min ago';
    } elseif ($diff < 86400) {
        $timeAgo = floor($diff / 3600) . ' h ago';
    } else {
        $timeAgo = floor($diff / 86400) . ' d ago';
    }
    
    $formattedRecent[] = [
        'type' => $search['type'],
        'query' => htmlspecialchars($search['query']),
        'time_ago' => $timeAgo
    ];
}

echo json_encode([
    'success' => true,
    'total_searches' => $totalSearches,
    'mobile_searches' => $mobileSearches,
    'aadhaar_searches' => $aadhaarSearches,
    'credits_spent' => $creditsSpent,
    'current_balance' => $currentBalance,
    'success_rate' => $successRate,
    'recent_searches' => $formattedRecent
]);
?>
