<?php
require_once __DIR__ . '/../lib.php';

hw_require_auth(['client']);

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    hw_json(['success' => false, 'error' => 'Method not allowed'], 405);
}

$authUser = hw_get_auth_user();

try {
    $db = hw_db();
    
    // Parse pagination parameters
    $limit = min((int)($_GET['limit'] ?? 20), 100);
    $offset = (int)($_GET['offset'] ?? 0);
    $type = $_GET['type'] ?? 'all'; // 'all', 'appointment', 'order', 'health', 'recommendation'
    
    // Build activity feed from multiple sources
    $activities = [];
    
    // 1. Completed Appointments
    $apptStmt = $db->prepare("
        SELECT 
            a.id,
            'appointment' as type,
            'Completed session' as action,
            'completed' as status,
            CONCAT('Session with ', IFNULL(c.display_name, CONCAT(u.first_name, ' ', u.last_name))) as description,
            a.starts_at as created_at,
            a.duration_minutes,
            c.display_name as coach_name
        FROM appointments a
        LEFT JOIN coaches c ON a.coach_id = c.id
        LEFT JOIN users u ON c.user_id = u.id
        WHERE a.user_id = ? AND a.status = 'completed'
        ORDER BY a.starts_at DESC
    ");
    $apptStmt->execute([$authUser['id']]);
    $appointments = $apptStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 2. Purchases/Orders
    $orderStmt = $db->prepare("
        SELECT 
            o.id,
            'order' as type,
            'Made purchase' as action,
            o.status,
            CONCAT('Order #', o.id, ' - ', COUNT(oi.id), ' item(s)') as description,
            o.created_at,
            o.total_amount
        FROM orders o
        LEFT JOIN order_items oi ON o.id = oi.order_id
        WHERE o.user_id = ?
        GROUP BY o.id
        ORDER BY o.created_at DESC
    ");
    $orderStmt->execute([$authUser['id']]);
    $orders = $orderStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 3. Health Data Entries
    $healthStmt = $db->prepare("
        SELECT 
            id,
            'health' as type,
            CASE 
                WHEN blood_pressure IS NOT NULL THEN 'Logged blood pressure'
                WHEN heart_rate IS NOT NULL THEN 'Logged heart rate'
                WHEN sleep_hours IS NOT NULL THEN 'Logged sleep hours'
                WHEN weight IS NOT NULL THEN 'Logged weight'
                WHEN session_notes IS NOT NULL THEN 'Added session notes'
                ELSE 'Updated health data'
            END as action,
            'logged' as status,
            CASE 
                WHEN blood_pressure IS NOT NULL THEN CONCAT('BP: ', blood_pressure)
                WHEN heart_rate IS NOT NULL THEN CONCAT('Heart Rate: ', heart_rate, ' bpm')
                WHEN sleep_hours IS NOT NULL THEN CONCAT('Sleep: ', sleep_hours, ' hours')
                WHEN weight IS NOT NULL THEN CONCAT('Weight: ', weight, ' kg')
                ELSE 'Health metrics updated'
            END as description,
            created_at
        FROM health_metrics
        WHERE user_id = ?
        ORDER BY created_at DESC
    ");
    $healthStmt->execute([$authUser['id']]);
    $healthData = $healthStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 4. Medical Report Uploads
    $reportStmt = $db->prepare("
        SELECT 
            id,
            'document' as type,
            'Uploaded medical report' as action,
            'uploaded' as status,
            original_filename as description,
            uploaded_at as created_at,
            file_size
        FROM medical_reports
        WHERE user_id = ?
        ORDER BY uploaded_at DESC
    ");
    $reportStmt->execute([$authUser['id']]);
    $reports = $reportStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 5. Intake Form Submissions
    $intakeStmt = $db->prepare("
        SELECT 
            id,
            'intake' as type,
            'Completed intake assessment' as action,
            'submitted' as status,
            'Health and wellness intake form' as description,
            created_at
        FROM intake_forms
        WHERE user_id = ?
        ORDER BY created_at DESC
    ");
    $intakeStmt->execute([$authUser['id']]);
    $intakes = $intakeStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Merge all activities
    $activities = array_merge($appointments, $orders, $healthData, $reports, $intakes);
    
    // Filter by type if specified
    if ($type !== 'all') {
        $activities = array_filter($activities, function($a) use ($type) {
            return $a['type'] === $type;
        });
    }
    
    // Sort by created_at descending
    usort($activities, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    // Get total count before pagination
    $totalCount = count($activities);
    
    // Apply pagination
    $activities = array_slice($activities, $offset, $limit);
    
    // Format dates for display
    $activities = array_map(function($activity) {
        $createdDate = new DateTime($activity['created_at']);
        $now = new DateTime();
        $diff = $now->diff($createdDate);
        
        if ($diff->days == 0 && $diff->h == 0) {
            $timeAgo = $diff->i . ' min ago';
        } elseif ($diff->days == 0) {
            $timeAgo = $diff->h . 'h ago';
        } elseif ($diff->days == 1) {
            $timeAgo = 'Yesterday';
        } elseif ($diff->days < 7) {
            $timeAgo = $diff->days . ' days ago';
        } else {
            $timeAgo = $createdDate->format('M j, Y');
        }
        
        $activity['time_ago'] = $timeAgo;
        $activity['formatted_date'] = $createdDate->format('l, F j, Y g:i A');
        
        return $activity;
    }, $activities);
    
    // Get activity type counts
    $typeCountsStmt = $db->prepare("
        SELECT 
            SUM(CASE WHEN type = 'appointment' THEN 1 ELSE 0 END) as appointments,
            SUM(CASE WHEN type = 'order' THEN 1 ELSE 0 END) as orders,
            SUM(CASE WHEN type = 'health' THEN 1 ELSE 0 END) as health,
            SUM(CASE WHEN type = 'document' THEN 1 ELSE 0 END) as documents,
            SUM(CASE WHEN type = 'intake' THEN 1 ELSE 0 END) as intakes
        FROM (
            SELECT 'appointment' as type FROM appointments WHERE user_id = ? AND status = 'completed'
            UNION ALL
            SELECT 'order' as type FROM orders WHERE user_id = ?
            UNION ALL
            SELECT 'health' as type FROM health_metrics WHERE user_id = ?
            UNION ALL
            SELECT 'document' as type FROM medical_reports WHERE user_id = ?
            UNION ALL
            SELECT 'intake' as type FROM intake_forms WHERE user_id = ?
        ) as all_activities
    ");
    $typeCountsStmt->execute([
        $authUser['id'],
        $authUser['id'],
        $authUser['id'],
        $authUser['id'],
        $authUser['id']
    ]);
    $typeCounts = $typeCountsStmt->fetch(PDO::FETCH_ASSOC);
    
    hw_json([
        'success' => true,
        'activities' => $activities,
        'pagination' => [
            'offset' => $offset,
            'limit' => $limit,
            'total' => $totalCount,
            'has_more' => ($offset + $limit) < $totalCount
        ],
        'type_counts' => $typeCounts
    ]);
    
} catch (PDOException $e) {
    error_log('Activity feed fetch error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Database error'], 500);
} catch (Exception $e) {
    error_log('Activity feed error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
}
