<?php
// 1. PembimbingMagangDashboardController - Fixed
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{Jurnal, SiswaMagang, User};

class PembimbingMagangDashboardController extends Controller
{
    public function dashboard()
    {
        $pembimbing = auth()->user()->pembimbingMagang;
        
        // Check if pembimbing exists
        if (!$pembimbing) {
            return redirect()->back()->with('error', 'Data pembimbing tidak ditemukan');
        }
        
        // Statistik siswa bimbingan
        $totalSiswa = $pembimbing->siswaList->count();
        $siswaAktif = $pembimbing->siswaList->where('selesai_magang', '>=', now())->count();
        
        // Statistik jurnal
        $siswaIds = $pembimbing->siswaList->pluck('id')->toArray();
        $userIds = User::whereIn('id_siswa', $siswaIds)->pluck('id')->toArray();
        
        $jurnalStats = [
            'pending' => Jurnal::whereIn('user_id', $userIds)->where('status_verifikasi', 'pending')->count(),
            'diterima' => Jurnal::whereIn('user_id', $userIds)->where('status_verifikasi', 'diterima')->count(),
            'ditolak' => Jurnal::whereIn('user_id', $userIds)->where('status_verifikasi', 'ditolak')->count()
        ];
        
        // Jurnal terbaru yang perlu verifikasi
        $jurnalPending = Jurnal::with('user.siswa')->whereIn('user_id', $userIds)
                              ->where('status_verifikasi', 'pending')
                              ->orderBy('tanggal', 'desc')
                              ->limit(5)->get();
        
        return view('pembimbing-magang.dashboard', compact('totalSiswa', 'siswaAktif', 'jurnalStats', 'jurnalPending'));
    }
    
    public function siswaList(Request $request)
    {
        $pembimbing = auth()->user()->pembimbingMagang;
        
        // Check if pembimbing exists
        if (!$pembimbing) {
            return redirect()->back()->with('error', 'Data pembimbing tidak ditemukan');
        }
        
        $query = $pembimbing->siswaList()->with(['sekolah', 'user.jurnal']);
        
        // Filter pencarian berdasarkan nama siswa
        if ($request->search) {
            $query->where('nama_siswa', 'like', '%' . $request->search . '%');
        }
        
        // Pagination dengan 5 data per halaman
        $siswa = $query->paginate(5);
        
        return view('pembimbing-magang.siswa.index', compact('siswa'));
    }
}