<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HostingCacheController extends Controller
{
    private string $token = 'ganti-token-rahasia-123';

    public function clear(Request $request): JsonResponse
    {
        if ($request->query('token') !== $this->token) {
            abort(403);
        }

        try {
            $this->clearArtisanCache();
            $this->deleteBootstrapCacheFiles();
            $this->deleteCompiledViews();

            return response()->json([
                'status' => 'success',
                'message' => 'Cache Laravel berhasil dibersihkan.',
                'current_config' => $this->databaseInfo(),
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ], 500);
        }
    }

    private function clearArtisanCache(): void
    {
        $commands = [
            'config:clear',
            'cache:clear',
            'route:clear',
            'view:clear',
            'event:clear',
            'optimize:clear',
        ];

        foreach ($commands as $command) {
            Artisan::call($command);
        }
    }

    private function deleteBootstrapCacheFiles(): void
    {
        $files = [
            base_path('bootstrap/cache/config.php'),
            base_path('bootstrap/cache/routes.php'),
            base_path('bootstrap/cache/routes-v7.php'),
            base_path('bootstrap/cache/events.php'),
            base_path('bootstrap/cache/packages.php'),
            base_path('bootstrap/cache/services.php'),
        ];

        foreach ($files as $file) {
            $this->deleteFileIfExists($file);
        }
    }

    private function deleteCompiledViews(): void
    {
        $views = File::glob(storage_path('framework/views/*'));

        foreach ($views as $view) {
            if (File::isFile($view) && basename($view) !== '.gitignore') {
                File::delete($view);
            }
        }
    }

    private function deleteFileIfExists(string $path): void
    {
        if (File::exists($path)) {
            File::delete($path);
        }
    }

    private function databaseInfo(): array
    {
        return [
            'database_default' => config('database.default'),
            'mysql_host' => config('database.connections.mysql.host'),
            'mysql_database' => config('database.connections.mysql.database'),
            'mysql_username' => config('database.connections.mysql.username'),
            'pgsql_host' => config('database.connections.pgsql.host'),
        ];
    }
}
