<?php

namespace App\Http\Controllers\Admin\Fitur;

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

class FiturController extends Controller
{
    /**
     * Load rare_item.conf file content
     */
    public function loadRareItemFile(Request $request)
    {
        $path = $request->input('path', '/home/gamed/config/rare_item.conf');

        // Validate path to prevent directory traversal
        $realPath = realpath($path);

        if (! $realPath || ! File::exists($realPath)) {
            return response()->json([
                'success' => false,
                'message' => 'File not found: '.$path,
            ], 404);
        }

        try {
            $content = File::get($realPath);

            return response()->json([
                'success' => true,
                'content' => $content,
                'path' => $realPath,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error reading file: '.$e->getMessage(),
            ], 500);
        }
    }

    /**
     * Save rare_item.conf file content
     */
    public function saveRareItemFile(Request $request)
    {
        $request->validate([
            'path' => 'required|string',
            'content' => 'required|string',
        ]);

        $path = $request->input('path');
        $content = $request->input('content');

        // Validate path
        $realPath = realpath(dirname($path)).'/'.basename($path);

        if (! File::exists(dirname($realPath))) {
            return response()->json([
                'success' => false,
                'message' => 'Directory not found',
            ], 404);
        }

        try {
            File::put($realPath, $content);

            return response()->json([
                'success' => true,
                'message' => 'File saved successfully',
                'path' => $realPath,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error saving file: '.$e->getMessage(),
            ], 500);
        }
    }
}
