<?php

namespace App\Http\Controllers\Petani;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\Produk;
use App\Models\Transaksi; 

class DashboardController extends Controller
{
    public function index()
    {
        $petaniId = Auth::guard('petani')->id();
        $totalProduk = Produk::where('petani_id', $petaniId)->count();
        $pesananBaru = Transaksi::where('petani_id', $petaniId)
            ->where('status', 'dibayar') 
            ->count();

        $totalPemesanan = Transaksi::where('petani_id', $petaniId)
            ->where('status', '!=', 'batal')
            ->count();

        $totalPendapatan = Transaksi::where('petani_id', $petaniId)
            ->where('status', 'selesai')
            ->sum('total_harga');

        $pendapatanPerBulan = Transaksi::where('petani_id', $petaniId)
            ->where('status', 'selesai')
            ->whereYear('tanggal_transaksi', date('Y')) 
            ->selectRaw('MONTH(tanggal_transaksi) as bulan, SUM(total_harga) as total')
            ->groupBy('bulan')
            ->pluck('total', 'bulan')
            ->toArray();

        $labels = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agt', 'Sep', 'Okt', 'Nov', 'Des'];
        $dataGrafik = [];

        for ($i = 1; $i <= 12; $i++) {
            $dataGrafik[] = $pendapatanPerBulan[$i] ?? 0;
        }

        return view('petani.dashboard', compact(
            'totalProduk', 'pesananBaru', 'totalPemesanan', 'totalPendapatan', 'labels', 'dataGrafik'
        ));
    }
}