<?php

namespace App\Controllers;

use App\Models\PetaniModel;
use App\Models\PupukModel;
use App\Models\KeuanganModel;

class Home extends BaseController
{
    public function index()
    {
        // Pastikan Model di-load. Jika database belum siap, 
        // kita bisa beri nilai 0 dulu agar tidak error.
        try {
            $petaniM = new PetaniModel();
            $pupukM  = new PupukModel();
            $kasM    = new KeuanganModel();

            $total_petani = $petaniM->countAll();
            $total_stok   = $pupukM->selectSum('stok_global')->get()->getRow()->stok_global ?? 0;
            $saldo_kas    = $kasM->orderBy('id_kas', 'DESC')->first()['saldo_akhir'] ?? 0;
        } catch (\Exception $e) {
            // Jika database belum terkoneksi, nilai default 0
            $total_petani = 0;
            $total_stok = 0;
            $saldo_kas = 0;
        }

        $data = [
            'title'        => 'Dashboard Utama Sari Rasa',
            'total_petani' => $total_petani,
            'total_stok'   => $total_stok,
            'saldo_kas'    => $saldo_kas,
        ];

        // INI KUNCINYA: Kita ubah dari 'welcome_message' menjadi 'dashboard'
        return view('dashboard', $data);
    }
}
