<?php
// Include your database connection file
include 'includes/session.php'; 
$dbh = new PDO("mysql:host=localhost;dbname=xpydayib_tracking", "xpydayib_xpyder", "{k5Gn}]aWl81");

// Fetch data for all active users
$sql_users = "SELECT id, name FROM users where status='Running'";  // Adjust based on the users table
$query_users = $dbh->prepare($sql_users);
$query_users->execute();
$users = $query_users->fetchAll(PDO::FETCH_ASSOC);

$all_data = [];

foreach ($users as $user) {
    $user_id = $user['id'];
    
    // Fetch the latest 4 photos from the `user_photos` table for the user
    $sql_photos = "SELECT photo_path FROM user_photos WHERE user_id = :u_id ORDER BY created_at DESC LIMIT 4";
    $query_photos = $dbh->prepare($sql_photos);
    $query_photos->bindParam(':u_id', $user_id, PDO::PARAM_STR);
    $query_photos->execute();
    $photos = $query_photos->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch the latest 4 screenshots from the `user_screenshots` table for the user
    $sql_screenshots = "SELECT file_path FROM screenshots WHERE user_id = :u_id ORDER BY id DESC LIMIT 4"; // Adjust based on the screenshots table
    $query_screenshots = $dbh->prepare($sql_screenshots);
    $query_screenshots->bindParam(':u_id', $user_id, PDO::PARAM_STR);
    $query_screenshots->execute();
    $screenshots = $query_screenshots->fetchAll(PDO::FETCH_ASSOC);

    // Fetch distinct running apps from the `running_apps` table for the user
    $sql_apps = "SELECT DISTINCT name FROM running_apps WHERE user_id = :u_id";
    $query_apps = $dbh->prepare($sql_apps);
    $query_apps->bindParam(':u_id', $user_id, PDO::PARAM_STR);
    $query_apps->execute();
    $apps = $query_apps->fetchAll(PDO::FETCH_ASSOC);

    // Collect all the data in a single array for each user
    $all_data[] = [
        'user' => $user['name'],
        'id' => $user_id, // Add user ID here
        'photos' => $photos,
        'screenshots' => $screenshots, // Add screenshots here
        'apps' => $apps
    ];
}

// Return JSON for AJAX requests
echo json_encode($all_data);
?>
