<?php

namespace App\Http\Controllers;

use App\Models\PenilaianPesertaTakwim;
use App\Models\PesertaTakwim;
use App\Models\Takwim;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PenilaianPesertaController extends Controller
{
    public function index(Request $request)
    {
        $query = PesertaTakwim::with(['anggota', 'takwim', 'penilaianTerbaru']);

        // Filter berdasarkan takwim
        if ($request->filled('takwim_id')) {
            $query->where('takwim_id', $request->takwim_id);
        }

        // Filter berdasarkan status penilaian
        if ($request->filled('status_penilaian')) {
            if ($request->status_penilaian == 'sudah_dinilai') {
                $query->whereHas('penilaian');
            } elseif ($request->status_penilaian == 'belum_dinilai') {
                $query->whereDoesntHave('penilaian');
            }
        }

        // Filter berdasarkan status kelulusan
        if ($request->filled('status_kelulusan')) {
            $query->whereHas('penilaianTerbaru', function($q) use ($request) {
                $q->where('status_kelulusan', $request->status_kelulusan);
            });
        }

        $peserta = $query->paginate(10);
        $takwimList = Takwim::orderBy('nama_takwim')->get();

        return view('penilaian-peserta.index', compact('peserta', 'takwimList'));
    }

    public function create(Request $request)
    {
        $pesertaId = $request->get('peserta_id');
        
        if (!$pesertaId) {
            return redirect()->route('penilaian-peserta.index')
                ->with('error', 'Pilih peserta terlebih dahulu untuk melakukan penilaian.');
        }

        $peserta = PesertaTakwim::with(['anggota', 'takwim'])->findOrFail($pesertaId);
        
        // Cek apakah sudah dinilai oleh penilai yang sama
        $existingPenilaian = PenilaianPesertaTakwim::where('peserta_takwim_id', $peserta->id)
            ->where('penilai_id', Auth::id())
            ->first();

        if ($existingPenilaian) {
            return redirect()->route('penilaian-peserta.edit', $existingPenilaian)
                ->with('info', 'Anda sudah melakukan penilaian untuk peserta ini. Silakan edit penilaian yang sudah ada.');
        }

        $indikators = \App\Models\IndikatorTakwim::where('is_active', true)->orderBy('nomor')->get();
        return view('penilaian-peserta.create', compact('peserta', 'indikators'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'peserta_takwim_id' => 'required|exists:tbl_peserta_takwim,id',
            'tanggal_penilaian' => 'required|date',
            'indikator_1' => 'boolean',
            'indikator_2' => 'boolean',
            'indikator_3' => 'boolean',
            'indikator_4' => 'boolean',
            'indikator_5' => 'boolean',
            'indikator_6' => 'boolean',
            'indikator_7' => 'boolean',
            'catatan_penilaian' => 'nullable|string|max:1000',
            'rekomendasi' => 'nullable|string|max:1000'
        ]);

        $validated['penilai_id'] = Auth::id();

        // Convert radio button values to boolean
        for ($i = 1; $i <= 7; $i++) {
            $validated["indikator_$i"] = $request->input("indikator_$i") == '1';
        }

        PenilaianPesertaTakwim::create($validated);

        return redirect()->route('penilaian-peserta.index')
            ->with('success', 'Penilaian peserta berhasil disimpan.');
    }

    public function show(PenilaianPesertaTakwim $penilaian)
    {
        // Debug: log informasi penilaian
        \Log::info('Penilaian ID: ' . $penilaian->id);
        \Log::info('Peserta Takwim ID: ' . $penilaian->peserta_takwim_id);
        
        $penilaian->load(['pesertaTakwim.anggota', 'pesertaTakwim.takwim', 'penilai']);
        
        // Debug: cek apakah relasi ter-load
        if (!$penilaian->pesertaTakwim) {
            \Log::error('Peserta takwim tidak ditemukan untuk penilaian ID: ' . $penilaian->id);
            return redirect()->route('penilaian-peserta.index')
                ->with('error', 'Data peserta takwim tidak ditemukan.');
        }
        
        if (!$penilaian->pesertaTakwim->anggota) {
            \Log::error('Anggota tidak ditemukan untuk peserta takwim ID: ' . $penilaian->peserta_takwim_id);
            return redirect()->route('penilaian-peserta.index')
                ->with('error', 'Data anggota tidak ditemukan.');
        }
        
        return view('penilaian-peserta.show', compact('penilaian'));
    }

    public function edit(PenilaianPesertaTakwim $penilaian)
    {
        // Cek apakah penilai yang sama
        if ($penilaian->penilai_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'Anda tidak memiliki akses untuk mengedit penilaian ini.');
        }

        $peserta = $penilaian->pesertaTakwim;
        
        $indikators = \App\Models\IndikatorTakwim::where('is_active', true)->orderBy('nomor')->get();
        return view('penilaian-peserta.edit', compact('penilaian', 'peserta', 'indikators'));
    }

    public function update(Request $request, PenilaianPesertaTakwim $penilaian)
    {
        // Cek apakah penilai yang sama
        if ($penilaian->penilai_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'Anda tidak memiliki akses untuk mengedit penilaian ini.');
        }

        $validated = $request->validate([
            'tanggal_penilaian' => 'required|date',
            'indikator_1' => 'boolean',
            'indikator_2' => 'boolean',
            'indikator_3' => 'boolean',
            'indikator_4' => 'boolean',
            'indikator_5' => 'boolean',
            'indikator_6' => 'boolean',
            'indikator_7' => 'boolean',
            'catatan_penilaian' => 'nullable|string|max:1000',
            'rekomendasi' => 'nullable|string|max:1000'
        ]);

        // Convert radio button values to boolean
        for ($i = 1; $i <= 7; $i++) {
            $validated["indikator_$i"] = $request->input("indikator_$i") == '1';
        }

        $penilaian->update($validated);

        return redirect()->route('penilaian-peserta.show', $penilaian)
            ->with('success', 'Penilaian peserta berhasil diperbarui.');
    }

    public function destroy(PenilaianPesertaTakwim $penilaian)
    {
        // Cek apakah penilai yang sama
        if ($penilaian->penilai_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'Anda tidak memiliki akses untuk menghapus penilaian ini.');
        }

        $penilaian->delete();

        return redirect()->route('penilaian-peserta.index')
            ->with('success', 'Penilaian peserta berhasil dihapus.');
    }

    public function laporan(Request $request)
    {
        $query = PenilaianPesertaTakwim::with(['pesertaTakwim.anggota', 'pesertaTakwim.takwim', 'penilai']);

        // Filter berdasarkan takwim
        if ($request->filled('takwim_id')) {
            $query->whereHas('pesertaTakwim', function($q) use ($request) {
                $q->where('takwim_id', $request->takwim_id);
            });
        }

        // Filter berdasarkan status kelulusan
        if ($request->filled('status_kelulusan')) {
            $query->where('status_kelulusan', $request->status_kelulusan);
        }

        // Filter berdasarkan penilai
        if ($request->filled('penilai_id')) {
            $query->where('penilai_id', $request->penilai_id);
        }

        $penilaian = $query->orderBy('created_at', 'desc')->paginate(20);
        $takwimList = Takwim::orderBy('nama_takwim')->get();
        $penilaiList = \App\Models\User::whereIn('role', ['superadmin', 'admin'])->get();

        // Statistik
        $statistik = [
            'total_penilaian' => $query->count(),
            'lulus' => $query->where('status_kelulusan', 'Lulus')->count(),
            'tidak_lulus' => $query->where('status_kelulusan', 'Tidak Lulus')->count(),
            'rata_rata_skor' => $query->avg('total_skor') ?? 0
        ];

        return view('penilaian-peserta.laporan', compact('penilaian', 'takwimList', 'penilaiList', 'statistik'));
    }
}