<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;


class UsersListController extends Controller{

    public function listUsersAction(){
        $data = shell_exec("python3 list_users_raspberrypi.py | grep Users: | grep -o '\[.*\]'");
	$data = json_decode(str_replace("'", '"', $data));
        return view('users-list')->with('data', $data);
	

    }


public function listFacesAction()
{
    // Get the path to the pictures directory
    $picturesPath = public_path('storage/pictures');

    // Check if the images are already cached
    $imageData = Cache::get('image_data');

    // If the images are not cached, read them from the directory and cache them
    if (!$imageData) {
        // Get all files in the pictures directory
        $files = scandir($picturesPath);

        // Filter out any non-image files
        $imageFiles = array_filter($files, function($file) {
            return in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif']);
        });

        // Sort the image files by their modification time (i.e. the time they were taken)
        usort($imageFiles, function($a, $b) use ($picturesPath) {
            return filemtime($picturesPath . '/' . $a) < filemtime($picturesPath . '/' . $b);
        });

        // Map the image files to an array of data for the Blade template
        $imageData = array_map(function($file) use ($picturesPath) {
            return [
                'filename' => $file,
                'datetime' => date('Y-m-d H:i:s', filemtime($picturesPath . '/' . $file)),
                'status' => strpos($file, 'success') !== false ? 'success' : 'failure',
            ];
        }, $imageFiles);

        // Cache the image data for 5 minutes
        Cache::put('image_data', $imageData, 5);
    }

    // Render the Blade template with the image data
    return view('facesList', ['images' => $imageData]);
}



public function deletePictures()
{
    $picturesPath = public_path('storage/pictures');
    $files = File::glob($picturesPath . '/*');
    foreach ($files as $file) {
        if (is_file($file)) {
            File::delete($file);
        }
    }
    return 'All pictures deleted.';
}

}
