<?php

namespace App\Http\Controllers;

use App\Models\Sampah;
use App\Models\KategoriTps;
use App\Models\LokasiTps;
use Illuminate\Http\Request;

class IndexController extends Controller
{
    public function index()
{
    $tahun = date('Y');

    // Ambil data sampah per bulan
    $dataSampah = Sampah::where('tahun', $tahun)
        ->orderBy('bulan')
        ->get();

    $bulan = [];
    $timbulan = [];
    $kelola = [];
    $daur = [];
    $sisa = [];

    foreach ($dataSampah as $d) {
        $bulan[] = \Carbon\Carbon::create()->month($d->bulan)->translatedFormat('M');
        $timbulan[] = $d->total_sampah;
        $kelola[] = $d->total_kelola;
        $daur[] = $d->total_daur_ulang;
        $sisa[] = $d->sisa_sampah;
    }

    // Rekap total satu tahun
    $rekap = [
        'timbulan' => array_sum($timbulan),
        'kelola' => array_sum($kelola),
        'daur' => array_sum($daur),
        'sisa' => array_sum($sisa),
    ];

    // Data sampah terbaru untuk card
    $sampah = Sampah::orderBy('tahun', 'desc')->first();

    // Data TPS
    $kategoriTps = KategoriTps::orderBy('id_kategori_tps')->get();
    $tps = LokasiTps::all();

    $jumlahTps = LokasiTps::where('kategori_tps_id', 1)->count();
    $jumlahTps3r = LokasiTps::where('kategori_tps_id', 2)->count();
    $jumlahTpa = LokasiTps::where('kategori_tps_id', 3)->count();

    return view('user.index', compact(
        'sampah',
        'kategoriTps',
        'tps',
        'jumlahTps',
        'jumlahTps3r',
        'jumlahTpa',
        'bulan',
        'timbulan',
        'kelola',
        'daur',
        'sisa',
        'rekap',
        'tahun'
    ));
}
}
