<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

// Set JSON response headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

$activities = [];

try {
    // Recent user registrations
    $stmt = $pdo->query("
        SELECT 'user_registration' as type, CONCAT(first_name, ' ', last_name) as title,
               CONCAT('Nuevo usuario registrado: ', username) as description,
               created_at as timestamp
        FROM users
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        ORDER BY created_at DESC
        LIMIT 5
    ");
    $user_activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Recent job postings
    $stmt = $pdo->query("
        SELECT 'job_posting' as type, j.title,
               CONCAT('Nueva oferta publicada por ', c.company_name) as description,
               j.posted_date as timestamp
        FROM jobs j
        JOIN companies c ON j.company_id = c.id
        WHERE j.posted_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        ORDER BY j.posted_date DESC
        LIMIT 5
    ");
    $job_activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Recent applications
    $stmt = $pdo->query("
        SELECT 'application' as type, j.title as title,
               CONCAT('Nueva postulación para: ', j.title) as description,
               a.applied_date as timestamp
        FROM applications a
        JOIN jobs j ON a.job_id = j.id
        WHERE a.applied_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        ORDER BY a.applied_date DESC
        LIMIT 5
    ");
    $application_activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Combine and sort all activities
    $all_activities = array_merge($user_activities, $job_activities, $application_activities);

    // Sort by timestamp descending
    usort($all_activities, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']);
    });

    // Take top 10 most recent
    $all_activities = array_slice($all_activities, 0, 10);

    // Format activities for display
    foreach ($all_activities as $activity) {
        $type_labels = [
            'user_registration' => 'success',
            'job_posting' => 'info',
            'application' => 'warning'
        ];

        $type_text = [
            'user_registration' => 'Usuario',
            'job_posting' => 'Empleo',
            'application' => 'Postulación'
        ];

        $activities[] = [
            'type' => $type_labels[$activity['type']] ?? 'secondary',
            'type_label' => $type_text[$activity['type']] ?? 'Sistema',
            'title' => $activity['title'],
            'description' => $activity['description'],
            'time' => self::time_elapsed_string($activity['timestamp'])
        ];
    }

} catch (Exception $e) {
    $activities = [
        [
            'type' => 'danger',
            'type_label' => 'Error',
            'title' => 'Error al cargar actividades',
            'description' => 'No se pudieron cargar las actividades recientes.',
            'time' => 'ahora'
        ]
    ];
}

function time_elapsed_string($datetime) {
    $now = new DateTime();
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    if ($diff->d > 0) {
        return "hace {$diff->d} día" . ($diff->d > 1 ? 's' : '');
    } elseif ($diff->h > 0) {
        return "hace {$diff->h} hora" . ($diff->h > 1 ? 's' : '');
    } elseif ($diff->i > 0) {
        return "hace {$diff->i} minuto" . ($diff->i > 1 ? 's' : '');
    } else {
        return "hace unos segundos";
    }
}

echo json_encode([
    'success' => true,
    'activities' => $activities,
    'timestamp' => time()
]);
?>