<?php
/**
 * API endpoint to get recent assignment activity
 */

// Include dependencies
require_once '../../config/database.php';
require_once '../../config/auth_enhanced.php';

// Require admin access
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'message' => 'Error retrieving assignment activity',
    'data' => []
];

// Handle request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $db = new \Services\Core\Database();
        $conn = $db->getConnection();
        
        // Limit parameter (optional)
        $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
        if ($limit <= 0 || $limit > 50) {
            $limit = 10; // Default or corrected value
        }
        
        // Get recent activity
        $query = "SELECT 
                    l.id,
                    l.assignment_id,
                    l.action_type,
                    l.details,
                    l.created_at,
                    a.member_id,
                    CONCAT(m.first_name, ' ', m.last_name) as member_name,
                    a.assigned_to,
                    admin.username as admin_name
                FROM 
                    assignment_activity_log l
                LEFT JOIN 
                    admin_assignments a ON l.assignment_id = a.id
                LEFT JOIN 
                    members m ON a.member_id = m.id
                LEFT JOIN 
                    admin_users admin ON a.assigned_to = admin.id
                ORDER BY 
                    l.created_at DESC
                LIMIT :limit";
        
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':limit', $limit, \PDO::PARAM_INT);
        $stmt->execute();
        
        $activities = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        // Calculate time ago for each activity
        foreach ($activities as &$activity) {
            $activity['time_ago'] = getTimeAgo($activity['created_at']);
            
            // Format description based on action type
            switch ($activity['action_type']) {
                case 'create':
                    $activity['description'] = "New assignment created for {$activity['member_name']} assigned to {$activity['admin_name']}.";
                    break;
                case 'update':
                    $activity['description'] = "Assignment for {$activity['member_name']} was updated: {$activity['details']}.";
                    break;
                case 'complete':
                    $activity['description'] = "Assignment for {$activity['member_name']} was marked as completed.";
                    break;
                case 'cancel':
                    $activity['description'] = "Assignment for {$activity['member_name']} was cancelled.";
                    break;
                default:
                    $activity['description'] = $activity['details'];
            }
        }
        
        $response = [
            'success' => true,
            'message' => 'Activity retrieved successfully',
            'data' => $activities
        ];
        
    } catch (\Exception $e) {
        $response = [
            'success' => false,
            'message' => 'Error: ' . $e->getMessage(),
            'data' => []
        ];
    }
}

// Helper function to calculate time ago
function getTimeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return "Just now";
    } elseif ($diff < 3600) {
        $mins = floor($diff / 60);
        return $mins . " minute" . ($mins > 1 ? "s" : "") . " ago";
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . " hour" . ($hours > 1 ? "s" : "") . " ago";
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        return $days . " day" . ($days > 1 ? "s" : "") . " ago";
    } elseif ($diff < 2592000) {
        $weeks = floor($diff / 604800);
        return $weeks . " week" . ($weeks > 1 ? "s" : "") . " ago";
    } elseif ($diff < 31536000) {
        $months = floor($diff / 2592000);
        return $months . " month" . ($months > 1 ? "s" : "") . " ago";
    } else {
        $years = floor($diff / 31536000);
        return $years . " year" . ($years > 1 ? "s" : "") . " ago";
    }
}

// Send response
header('Content-Type: application/json');
echo json_encode($response);
