<?php

namespace App\Http\Controllers\Admin; 

use App\Http\Controllers\Controller; 
use Illuminate\Http\Request;
use App\Models\Petani;
use App\Models\Produk;
use App\Models\Transaksi;

class AdminController extends Controller
{
    public function dashboard()
    {
        $totalPetani = Petani::where('status_akun', 'aktif')->count();
        $petaniPending = Petani::where('status_akun', 'menunggu')->count();
        $totalProduk = Produk::count();
        $totalTransaksi = Transaksi::count();

        $transaksiTerbaru = Transaksi::with(['pembeli', 'petani'])
            ->latest()
            ->take(5)
            ->get();

        return view('admin.dashboard', compact(
            'totalPetani', 
            'petaniPending', 
            'totalProduk', 
            'totalTransaksi',
            'transaksiTerbaru'
        ));
    }

    public function monitoring()
    {
        $produks = Produk::with('petani')->latest()->paginate(10);
        $transaksis = Transaksi::with(['pembeli', 'petani'])
            ->latest()
            ->paginate(10);

        return view('admin.monitoring', compact('produks', 'transaksis'));
    }

    public function transaksiDetail($id)
    {
        $transaksi = Transaksi::with(['pembeli', 'petani', 'detailTransaksis.produk'])
            ->findOrFail($id);

        return view('admin.transaksi_detail', compact('transaksi'));
    }

    public function verifikasiIndex()
    {
        $petanis = Petani::orderBy('created_at', 'desc')->get(); 
        return view('admin.verifikasi.index', compact('petanis'));
    }

    public function verifikasiShow($id)
    {
        $petani = Petani::findOrFail($id);
        return view('admin.verifikasi.show', compact('petani'));
    }

    public function verifikasiApprove($id)
    {
        $petani = Petani::findOrFail($id);
        $petani->status_akun = 'aktif';
        $petani->save();

        return redirect('admin/verifikasi')->with('success', 'Pendaftaran Petani BERHASIL diterima.');
    }

    public function verifikasiReject($id)
    {
        $petani = Petani::findOrFail($id);
        $petani->status_akun = 'ditolak';
        $petani->save();

        return redirect('admin/verifikasi')->with('success', 'Pendaftaran Petani DITOLAK.');
    }
}