<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;

class CacheController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:settings', ['only' => ['index', 'clearCache', 'clearView', 'clearConfig', 'clearRoute', 'clearAll']]);
    }

    /**
     * Display the cache settings page
     */
    public function index()
    {
        // Get cache storage path size
        $cachePath = storage_path('framework/cache');
        $cacheSize = $this->calculateDirectorySize($cachePath);

        // Get view cache size
        $viewPath = storage_path('framework/views');
        $viewSize = $this->calculateDirectorySize($viewPath);

        // Get log files size
        $logsPath = storage_path('logs');
        $logsSize = $this->calculateDirectorySize($logsPath);

        return view('admin.settings.cache', compact('cacheSize', 'viewSize', 'logsSize'));
    }

    /**
     * Clear application cache
     */
    public function clearCache()
    {
        try {
            Artisan::call('cache:clear');
            session()->flash('success', __('translations.cache_cleared_successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('translations.cache_clear_failed') . ' - ' . $e->getMessage());
        }
        return redirect()->route('admin.settings.cache');
    }

    /**
     * Clear view cache
     */
    public function clearView()
    {
        try {
            Artisan::call('view:clear');
            session()->flash('success', __('translations.view_cache_cleared_successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('translations.view_cache_clear_failed') . ' - ' . $e->getMessage());
        }
        return redirect()->route('admin.settings.cache');
    }

    /**
     * Clear config cache
     */
    public function clearConfig()
    {
        try {
            Artisan::call('config:clear');
            session()->flash('success', __('translations.config_cache_cleared_successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('translations.config_cache_clear_failed') . ' - ' . $e->getMessage());
        }
        return redirect()->route('admin.settings.cache');
    }

    /**
     * Clear route cache
     */
    public function clearRoute()
    {
        try {
            Artisan::call('route:clear');
            session()->flash('success', __('translations.route_cache_cleared_successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('translations.route_cache_clear_failed') . ' - ' . $e->getMessage());
        }
        return redirect()->route('admin.settings.cache');
    }

    /**
     * Clear logs
     */
    public function clearLogs()
    {
        try {
            $logPath = storage_path('logs');
            $logFiles = File::glob($logPath . '/*.log');

            foreach ($logFiles as $file) {
                if (File::exists($file)) {
                    File::put($file, '');
                }
            }

            session()->flash('success', __('translations.logs_cleared_successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('translations.logs_clear_failed') . ' - ' . $e->getMessage());
        }
        return redirect()->route('admin.settings.cache');
    }

    /**
     * Clear all caches
     */
    public function clearAll()
    {
        try {
            Artisan::call('cache:clear');
            Artisan::call('view:clear');
            Artisan::call('config:clear');
            Artisan::call('route:clear');
            Artisan::call('optimize:clear');

            session()->flash('success', __('translations.all_caches_cleared_successfully'));
        } catch (\Exception $e) {
            session()->flash('error', __('translations.all_caches_clear_failed') . ' - ' . $e->getMessage());
        }
        return redirect()->route('admin.settings.cache');
    }

    /**
     * Calculate directory size
     *
     * @param string $path Directory path
     * @return string Formatted size
     */
    private function calculateDirectorySize($path)
    {
        $size = 0;

        if (!File::exists($path)) {
            return $this->formatSize(0);
        }

        foreach (File::allFiles($path) as $file) {
            $size += $file->getSize();
        }

        return $this->formatSize($size);
    }

    /**
     * Format size to human readable format
     *
     * @param int $bytes Size in bytes
     * @return string Formatted size
     */
    private function formatSize($bytes)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);

        $bytes /= pow(1024, $pow);

        return round($bytes, 2) . ' ' . $units[$pow];
    }
}
