<?php

namespace App\Http\Controllers;

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

class CacheController extends Controller
{
    /**
     * Get the current cache version.
     * This is used by the datepicker to invalidate local storage caches.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCacheVersion()
    {
        // Use a cache versioning approach to allow frontend cache invalidation
        // If the version key doesn't exist, create it with the current timestamp
        $version = Cache::remember('app_cache_version', 60 * 24 * 30, function () {
            return time();
        });

        return response()->json(['version' => $version]);
    }

    /**
     * Increment the cache version (for admin use).
     * This forces all clients to invalidate their local caches.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function incrementCacheVersion()
    {
        // Increment version to invalidate all client-side caches
        $version = time();
        Cache::put('app_cache_version', $version, 60 * 24 * 30);

        return response()->json([
            'success' => true,
            'message' => 'Cache version updated. All client-side caches will be invalidated.',
            'version' => $version
        ]);
    }
}
