<?php

namespace App;

use App\Models\Project;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;

class ProjectLogger
{
    public static function log(Project $project, $message)
    {
        $filePath = $project->download_path . '/logs/' . now()->format('Ymd') . '.log';
        Storage::makeDirectory(dirname($filePath));
        file_put_contents(Storage::path($filePath), now()->format('Y-m-d H:i:s') . ': ' . $message . PHP_EOL, FILE_APPEND);
    }

    public static function getAsList(Project $project)
    {
        $logs = [];
        $logPath = $project->download_path . '/logs';
        if(Storage::exists($logPath)) {
            $files = Storage::files($logPath);
            foreach ($files as $file) {
                $logs[] = (object) [
                    'name' => basename($file),
                    'path' => Storage::path( $project->download_path . '/logs/'. basename($file)),
                ];
            }
        }
        return collect($logs)->sortByDesc('name');
    }

    public static function getLogFileForToday(Project $project)
    {
        $logPath = $project->download_path . '/logs/' . now()->format('Ymd') . '.log';
        if(Storage::exists($logPath)) {
            return Storage::path($logPath);
        }
        return null;
    }
}
