<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Lapor;
use App\Services\DecisionService;

class LaporController extends Controller
{
    public function index()
    {
        $laporan = Lapor::orderBy('ranking')->get();
        return view('lapor.index', compact('laporan'));
    }

    public function dashboard()
    {
        $laporan = Lapor::orderBy('ranking')->get();

        $statistik = Lapor::selectRaw('tingkat_serangan, COUNT(*) as total')
            ->groupBy('tingkat_serangan')
            ->pluck('total','tingkat_serangan');

        return view('lapor.dashboard', compact('laporan','statistik'));
    }

    public function create()
    {
        return view('lapor.create');
    }

    public function show($id)
    {
        $lapor = Lapor::findOrFail($id);
        return view('lapor.show', compact('lapor'));
    }

    public function store(Request $request, DecisionService $decision)
    {
        $request->validate([
            'nama_petani' => 'required',
            'lokasi' => 'required',
            'koordinat' => 'required',
            'kecamatan' => 'required',
            'jenis_hama' => 'required',
            'tingkat_serangan' => 'required',
            'luas_lahan' => 'required',
            'lama_kejadian' => 'required',
            'foto_base64' => 'required',
        ]);

        $parts = explode(',', $request->koordinat);
        if(count($parts) !== 2){
            return back()->withErrors(['koordinat'=>'Format harus lat,lng']);
        }

        $lat = trim($parts[0]);
        $lng = trim($parts[1]);

        // SIMPAN FOTO
        $image = preg_replace('/^data:image\/\w+;base64,/', '', $request->foto_base64);
        $imageData = base64_decode($image);

        $fotoName = time().'.jpg';

        if (!file_exists(public_path('foto'))) {
            mkdir(public_path('foto'), 0755, true);
        }

        file_put_contents(public_path('foto/'.$fotoName), $imageData);

        // HITUNG AHP
        $ahp = $decision->hitungAHP();

        if($ahp['CR'] > 0.1){
            return back()->with('error','CR tidak konsisten');
        }

        $bobot = $ahp['bobot'];

        $r = [
            $request->tingkat_serangan,
            $request->luas_lahan,
            $request->lama_kejadian,
            $request->jenis_hama
        ];

        $mapping = [
            ['Ringan'=>1,'Sedang'=>3,'Berat'=>5],
            ['luas_kecil'=>1,'luas_sedang'=>3,'luas_besar'=>5],
            ['cepat'=>1,'menengah'=>3,'lama'=>5],
            ['Wereng'=>5,'Penggerek Batang'=>4,'Tikus'=>3,'Walang Sangit'=>2],
        ];

        $skor = 0;
        foreach($mapping as $i=>$map){
            $skor += ($map[$r[$i]]/5) * $bobot[$i];
        }

        Lapor::create([
            'user_id' => auth()->id(),
            'nama_petani'=>$request->nama_petani,
            'lokasi'=>$request->lokasi,
            'koordinat'=>$request->koordinat,
            'lat'=>$lat,
            'lng'=>$lng,
            'kecamatan' => $request->kecamatan,
            'jenis_hama'=>$request->jenis_hama,
            'tingkat_serangan'=>$request->tingkat_serangan,
            'luas_lahan'=>$request->luas_lahan,
            'lama_kejadian'=>$request->lama_kejadian,
            'deskripsi'=>$request->deskripsi,
            'skor_ahp'=>$skor,
            'status'=>'menunggu_validasi',
            'foto'=>$fotoName,
        ]);

        return redirect('/petani/dashboard')->with('success','Laporan berhasil disimpan');
    }

    public function edit($id)
    {
        $lapor = Lapor::findOrFail($id);

        return view('lapor.edit', compact('lapor'));
    }

    public function update(Request $request, $id)
{
    $lapor = Lapor::findOrFail($id);

    $lapor->update([
        'nama_petani' => $request->nama_petani,
        'jenis_hama' => $request->jenis_hama,
        'tingkat_serangan' => $request->tingkat_serangan,
        'luas_lahan' => $request->luas_lahan,
        'lama_kejadian' => $request->lama_kejadian,
        'koordinat' => $request->koordinat,
        'kecamatan' => $request->kecamatan,
        'lokasi' => $request->lokasi,
        'deskripsi' => $request->deskripsi,
    ]);

    // UPDATE FOTO JIKA ADA
    if($request->foto_base64){

        $image = preg_replace('/^data:image\/\w+;base64,/', '', $request->foto_base64);
        $imageData = base64_decode($image);

        $fotoName = time().'.jpg';

        file_put_contents(public_path('foto/'.$fotoName), $imageData);

        // hapus foto lama
        if($lapor->foto && file_exists(public_path('foto/'.$lapor->foto))){
            unlink(public_path('foto/'.$lapor->foto));
        }

        $lapor->update([
            'foto' => $fotoName
        ]);
    }

    return redirect('/petani/dashboard')
        ->with('success','Laporan berhasil diupdate');
}

    public function validasi($id, DecisionService $decision)
    {
        $lapor = Lapor::findOrFail($id);

        // Ubah status jadi valid
        $lapor->update(['status'=>'menunggu']);
 
        $decision->hitungTOPSIS();

        return redirect('/penyuluh/dashboard')
        ->with('success','Laporan berhasil divalidasi');
}

    public function tolak($id)
    {
        $lapor = Lapor::findOrFail($id);

        $lapor->update([
            'status' => 'ditolak'
        ]);

        return back()->with('success','Laporan berhasil ditolak');
    }
    
    public function proses($id)
    {
        Lapor::findOrFail($id)->update(['status'=>'diproses']);
        return back();
    }

    public function selesai($id)
    {
        Lapor::findOrFail($id)->update(['status'=>'selesai']);
        return back();
    }

    public function destroy($id)
    {
        $lapor = Lapor::findOrFail($id);

        if ($lapor->foto && file_exists(public_path('foto/'.$lapor->foto))) {
            unlink(public_path('foto/'.$lapor->foto));
        }

        $lapor->delete();

        return back();
    }
}