<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;

class WorldTargetsController extends Controller
{
    /**
     * Get all world targets from world_targets.txt
     */
    public function index(): JsonResponse
    {
        try {
            $worldTargets = $this->getWorldTargets();
            
            return response()->json([
                'success' => true,
                'data' => $worldTargets,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to load world targets: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Parse world_targets.txt file and return array of targets
     * 
     * @return array
     */
    private function getWorldTargets(): array
    {
        // Cache for 1 hour
        return Cache::remember('world_targets', 3600, function () {
            $filePath = public_path('img/world_targets.txt');
            
            if (!file_exists($filePath)) {
                throw new \Exception('world_targets.txt file not found');
            }

            // Read file content with UTF-16LE encoding
            $content = file_get_contents($filePath);
            
            // Convert from UTF-16LE to UTF-8
            $content = mb_convert_encoding($content, 'UTF-8', 'UTF-16LE');
            
            // Remove BOM if present
            $content = str_replace("\xEF\xBB\xBF", '', $content);
            
            // Split into lines
            $lines = explode("\n", $content);
            
            $targets = [];
            
            foreach ($lines as $line) {
                $line = trim($line);
                
                // Skip empty lines
                if (empty($line)) {
                    continue;
                }
                
                // Split by tab character
                $parts = preg_split('/\t+/', $line);
                
                // Expected format: ID \t Name \t WorldTag \t "x,y,z"
                if (count($parts) >= 4) {
                    $id = (int) trim($parts[0]);
                    $name = trim($parts[1], " \t\n\r\0\x0B\""); // Remove quotes
                    $worldtag = (int) trim($parts[2]);
                    $coordinates = trim($parts[3], " \t\n\r\0\x0B\""); // Remove quotes
                    
                    // Parse coordinates "x,y,z"
                    $coords = explode(',', $coordinates);
                    
                    if (count($coords) === 3) {
                        $targets[] = [
                            'id' => $id,
                            'name' => $name,
                            'worldtag' => $worldtag,
                            'posx' => (float) trim($coords[0]),
                            'posy' => (float) trim($coords[1]),
                            'posz' => (float) trim($coords[2]),
                        ];
                    }
                }
            }
            
            return $targets;
        });
    }
}
