<?php

namespace App\Http\Middleware;

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

class ClearCacheMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            // cleare cache (2 day)
            $filePath = storage_path('app/cache_clear_time.txt');

            if (!File::exists($filePath)) {
                File::put($filePath, now()->subDays(3)->toDateTimeString());
            }

            $lastCleared = Carbon::parse(File::get($filePath));

            if ($lastCleared->diffInHours(now()) >= 48) {

                File::deleteDirectory(storage_path('framework/cache/data'));
                Cache::flush();
                foreach (File::files(storage_path('framework/views')) as $view) {
                    File::delete($view);
                }

                File::put($filePath, now()->toDateTimeString());
            }

            // clear laravel.log (30 day)
            $logTimeFile = storage_path('app/log_clear_time.txt');
            $logFilePath = storage_path('logs/laravel.log');

            if (!File::exists($logTimeFile)) {
                File::put($logTimeFile, now()->toDateTimeString());
            }

            $lastLogClear = Carbon::parse(File::get($logTimeFile));

            if ($lastLogClear->diffInDays(now()) >= 30) {
                if (File::exists($logFilePath)) {
                    File::delete($logFilePath);
                }
                File::put($logTimeFile, now()->toDateTimeString());
            }
        } catch (\Exception $e) {
        }

        return $next($request);
    }
}
