<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Sampah;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class SampahController extends Controller
{
    public function index(Request $request)
    {
        Carbon::setLocale('id');

        $title = 'Data Sampah';

        $tahun = $request->tahun;

        $query = Sampah::with('user');

        // Filter tahun jika dipilih
        if ($tahun) {
            $query->where('tahun', $tahun);
        }

        $sampah = $query->orderBy('tahun', 'desc')
            ->orderBy('bulan', 'desc')
            ->get();

        // ambil daftar tahun untuk dropdown filter
        $listTahun = Sampah::select('tahun')
            ->distinct()
            ->orderBy('tahun', 'desc')
            ->pluck('tahun');

        return view('admin.sampah.index', compact('title', 'sampah', 'listTahun'));
    }

    public function create()
    {
        $title = 'Tambah Data Sampah';
        $users = User::all();

        return view('admin.sampah.create', compact('title', 'users'));
    }

    public function store(Request $request)
    {
        $request->merge([
            'total_sampah' => $this->convertToDecimal($request->total_sampah),
            'total_kelola' => $this->convertToDecimal($request->total_kelola),
            'total_daur_ulang' => $this->convertToDecimal($request->total_daur_ulang),
        ]);

        $validator = Validator::make($request->all(), [
            'tahun' => 'required|digits:4',
            'bulan' => 'required|integer|min:1|max:12',
            'total_sampah' => 'required|numeric|min:0',
            'total_kelola' => 'required|numeric|min:0',
            'total_daur_ulang' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        if (($request->total_kelola + $request->total_daur_ulang) > $request->total_sampah) {
            return back()->withErrors([
                'total_kelola' => 'Jumlah kelola + daur ulang tidak boleh melebihi total sampah.'
            ])->withInput();
        }

        $sisa_sampah = $request->total_sampah - ($request->total_kelola + $request->total_daur_ulang);

        Sampah::create([
            'user_id' => Auth::id(),
            'tahun' => $request->tahun,
            'bulan' => $request->bulan,
            'total_sampah' => $request->total_sampah,
            'total_kelola' => $request->total_kelola,
            'total_daur_ulang' => $request->total_daur_ulang,
            'sisa_sampah' => $sisa_sampah,
        ]);

        return redirect()->route('admin.sampah.index')
            ->with('success', 'Data sampah berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $title = 'Edit Data Sampah';
        $sampah = Sampah::findOrFail($id);

        return view('admin.sampah.edit', compact('title', 'sampah'));
    }

    public function update(Request $request, $id)
    {
        $sampah = Sampah::findOrFail($id);

        $request->merge([
            'total_sampah' => $this->convertToDecimal($request->total_sampah),
            'total_kelola' => $this->convertToDecimal($request->total_kelola),
            'total_daur_ulang' => $this->convertToDecimal($request->total_daur_ulang),
        ]);

        $validator = Validator::make($request->all(), [
            'tahun' => 'required|digits:4',
            'bulan' => 'required|integer|min:1|max:12',
            'total_sampah' => 'required|numeric|min:0',
            'total_kelola' => 'required|numeric|min:0',
            'total_daur_ulang' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        if (($request->total_kelola + $request->total_daur_ulang) > $request->total_sampah) {
            return back()->withErrors([
                'total_kelola' => 'Jumlah kelola + daur ulang tidak boleh melebihi total sampah.'
            ])->withInput();
        }

        $sisa_sampah = $request->total_sampah - ($request->total_kelola + $request->total_daur_ulang);

        $sampah->update([
            'user_id' => Auth::id(),
            'tahun' => $request->tahun,
            'bulan' => $request->bulan,
            'total_sampah' => $request->total_sampah,
            'total_kelola' => $request->total_kelola,
            'total_daur_ulang' => $request->total_daur_ulang,
            'sisa_sampah' => $sisa_sampah,
        ]);

        return redirect()->route('admin.sampah.index')
            ->with('success', 'Data sampah berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $sampah = Sampah::findOrFail($id);
        $sampah->delete();

        return redirect()->route('admin.sampah.index')
            ->with('success', 'Data sampah berhasil dihapus.');
    }

    private function convertToDecimal($value)
    {
        if (!$value) {
            return 0;
        }

        return str_replace(',', '.', str_replace('.', '', $value));
    }
}
