<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MapFileController extends Controller
{
    private $storageFolder = 'upload';

    public function index()
    {
        $path = public_path($this->storageFolder);
        if (!File::exists($path)) {
            File::makeDirectory($path, 0755, true);
        }

        $files = [];
        $allFiles = File::files($path);
        
        foreach ($allFiles as $file) {
            if ($file->getExtension() === 'json') {
                $files[] = [
                    'name' => $file->getFilename(),
                    'size' => number_format($file->getSize() / 1048576, 2) . ' MB', // Convert Bytes to MB
                    'modified' => date('d M Y H:i', $file->getMTime()),
                ];
            }
        }

        return view('admin.maps.index', compact('files'));
    }

    public function store(Request $request)
    {
        // --- TURBO MODE: NAIKKAN BATAS MEMORI & WAKTU ---
        // Ini solusi untuk "tidak semua file bisa". Kita set RAM jadi 512MB atau Unlimited (-1)
        // dan waktu tunggu (timeout) jadi 5 menit biar file besar sempat terproses.
        ini_set('memory_limit', '512M'); 
        ini_set('max_execution_time', 300); 

        // Cek Error Server (Post Max Size)
        $contentLength = (int) ($request->server('CONTENT_LENGTH') ?: 0);
        $postMaxSize = ini_get('post_max_size'); 
        $unit = strtoupper(substr($postMaxSize, -1));
        $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
        $maxBytes = (int)$postMaxSize * $multiplier;

        if ($contentLength > $maxBytes && count($request->all()) == 0) {
            $currentPort = $request->server('SERVER_PORT');
            return back()->with('error', "Gagal Upload (Port: $currentPort): Server menolak file besar. Batas saat ini cuma $postMaxSize. Pastikan Anda akses lewat Port 8082 yang sudah saya buka!");
        }

        if (!$request->hasFile('json_file')) {
            $currentPort = $request->server('SERVER_PORT');
            return back()->with('error', "File hilang/kosong (Port: $currentPort). Kemungkinan besar karena limit server ($postMaxSize) terlampaui. Pindah ke Port 8082!");
        }

        $file = $request->file('json_file');

        if (!$file->isValid()) {
            return back()->with('error', "Upload Gagal (Kode: " . $file->getError() . "): " . $file->getErrorMessage());
        }

        // Validasi format (json/geojson/txt)
        $request->validate([
            'json_file' => 'required|file|mimes:json,geojson,txt|max:102400',
        ]);

        $filename = $file->getClientOriginalName();
        $file->move(public_path($this->storageFolder), $filename);

        try {
            // Proses Database
            $this->processJsonToDb($filename);
            return back()->with('success', "SUKSES! File $filename (Besar) berhasil diproses.");
        } catch (\Exception $e) {
            Log::error("Map Error ($filename): " . $e->getMessage());
            // Hapus file jika gagal biar tidak numpuk sampah
            @unlink(public_path($this->storageFolder . '/' . $filename));
            
            // Pesan error lebih ramah
            if (strpos($e->getMessage(), 'Allowed memory size') !== false) {
                return back()->with('error', "Gagal: File terlalu berat untuk server (Out of Memory).");
            }
            return back()->with('error', "Gagal memproses data: " . $e->getMessage());
        }
    }

    public function destroy(Request $request)
    {
        $filename = $request->input('filename');
        if (!$filename) {
            return back()->with('error', "Nama file tidak valid.");
        }

        $path = public_path($this->storageFolder . '/' . $filename);
        if (File::exists($path)) File::delete($path);
        
        DB::table('region_stats')->where('file_source', $filename)->delete();
        return back()->with('success', "File $filename berhasil dihapus.");
    }

    public function syncDatabase()
    {
        // --- TURBO MODE UNTUK SYNC ---
        ini_set('memory_limit', '1024M'); // Butuh lebih besar karena proses banyak file
        ini_set('max_execution_time', 600); 

        try {
            DB::beginTransaction();
            DB::table('region_stats')->truncate();

            $path = public_path($this->storageFolder);
            if (!File::exists($path)) File::makeDirectory($path, 0755, true);

            $files = File::files($path);
            $count = 0;

            foreach ($files as $file) {
                if ($file->getExtension() !== 'json') continue;
                try {
                    $this->processJsonToDb($file->getFilename());
                    $count++;
                } catch (\Exception $e) {
                    Log::warning("Gagal sync file: " . $file->getFilename());
                }
            }

            DB::commit();
            return back()->with('success', "Sync Selesai! $count file berhasil diproses.");

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', "Sync Gagal: " . $e->getMessage());
        }
    }

    private function processJsonToDb($filename)
    {
        $path = public_path($this->storageFolder . '/' . $filename);
        if (!File::exists($path)) return;

        // Gunakan file_get_contents biasa agar hemat resource dibanding File Facade
        $jsonContent = file_get_contents($path);
        
        // Bersihkan BOM (Byte Order Mark) jika ada
        $bom = pack('H*','EFBBBF');
        if (substr($jsonContent, 0, 3) === $bom) {
            $jsonContent = substr($jsonContent, 3);
        }
        
        // Decode dengan opsi depth 512 (standar)
        $data = json_decode($jsonContent, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception("JSON Rusak/Invalid: " . json_last_error_msg());
        }

        if (!isset($data['features'])) {
            throw new \Exception("Format salah: Tidak ada 'features'.");
        }

        // Hapus data lama untuk file source ini
        DB::table('region_stats')->where('file_source', $filename)->delete();

        // Coba tebak Nama Kabupaten dari nama file jika di properti tidak ada
        // Contoh: Kab_Kudus.json -> Kudus
        $inferredKabupaten = 'Unknown';
        $parts = explode('_', pathinfo($filename, PATHINFO_FILENAME));
        if (count($parts) >= 2 && (strtolower($parts[0]) == 'kab' || strtolower($parts[0]) == 'kec' || strtolower($parts[0]) == 'kal' || strtolower($parts[0]) == 'kel')) {
            $inferredKabupaten = $parts[1]; // Ambil kata kedua sebagai Kabupaten
        }

        $insertData = [];
        $timestamp = now();

        foreach ($data['features'] as $feature) {
            $props = $feature['attributes'] ?? $feature['properties'] ?? [];
            
            // Cari key RTLH yang cocok
            $rtlhVal = 0;
            $rtlhKeys = ['RTLH_KD', 'RTLH_KK', 'RTLH_KC', 'TOTAL_RTLH', 'JUMLAH_RTLH', 'RTLH'];
            foreach ($rtlhKeys as $key) {
                if (isset($props[$key])) {
                    $rtlhVal = (int)$props[$key];
                    break;
                }
            }

            // Logika Penentuan Wilayah
            $kab = $props['WADMKK'] ?? $props['KABUPATEN'] ?? $inferredKabupaten;
            $kec = $props['WADMKC'] ?? $props['KECAMATAN'] ?? 'Unknown';
            $kel = $props['WADMKD'] ?? $props['WADMKD_1'] ?? $props['KELURAHAN'] ?? $props['DESA'] ?? 'Unknown';

            $insertData[] = [
                'kabupaten' => $kab,
                'kecamatan' => $kec,
                'kelurahan' => $kel,
                'jumlah_rtlh' => $rtlhVal,
                'file_source' => $filename,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ];

            // Batch insert per 1000 baris
            if (count($insertData) >= 1000) {
                DB::table('region_stats')->insert($insertData);
                $insertData = [];
            }
        }

        if (!empty($insertData)) {
            DB::table('region_stats')->insert($insertData);
        }
        
        Log::info("Sukses memproses $filename. Total fitur: " . count($data['features']));
        
        // Bersihkan variabel berat dari memori manual (Garbage Collection)
        unset($jsonContent);
        unset($data);
    }
}