<?php

namespace App\Http\Controllers;

use App\Models\Assessment;
use App\Models\Subject;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AssessmentController extends Controller
{
    // --- 1. HALAMAN UTAMA (READ) ---
    public function index()
    {
        $user = Auth::user();

        // Ambil Data dengan Filter Hak Akses
        $query = Assessment::with('subject')->latest();

        if ($user->role == 'super_admin') {
            // Super Admin: Semua data
        } 
        elseif ($user->role == 'admin_mapel') {
            // Admin Mapel: Hanya mapel yang diampu (Logic Many-to-Many)
            // Ambil array ID mapel dari tabel pivot
            $subjectIds = $user->subjects->pluck('id'); 
            $query->whereIn('subject_id', $subjectIds);
        } 
        else {
            // Guru Mapel: Hanya data milik sendiri
            $query->where('user_id', $user->id);
        }

        $assessments = $query->get();

        // --- LOGIKA DROPDOWN PILIHAN MAPEL ---
        // Agar form tambah/edit hanya memunculkan mapel yang diampu
        if ($user->role == 'super_admin') {
            $subjects = Subject::all();
        } else {
            // Guru & Admin Mapel ambil dari relasi subjects
            $subjects = $user->subjects;
        }

        return view('pages.perangkat.asesmen.index', compact('assessments', 'subjects'));
    }

    // --- 2. SIMPAN DATA (CREATE) ---
    public function store(Request $request)
    {
        // [PENTING] BLOKIR AKSES TAMBAH UNTUK ADMIN MAPEL
        if (Auth::user()->role == 'admin_mapel') {
            return back()->with('error', 'Maaf, Admin Mapel tidak memiliki akses untuk menambah data baru.');
        }

        $request->validate([
            'subject_id' => 'required',
            'title' => 'required',
            'type' => 'required',
            'technique' => 'required',
            'questions' => 'required',
            'total_score' => 'required|numeric'
        ]);

        Assessment::create([
            'user_id' => Auth::id(),
            'subject_id' => $request->subject_id,
            'title' => $request->title,
            'type' => $request->type,
            'technique' => $request->technique,
            'total_score' => $request->total_score, // Simpan Skor
            'questions' => $request->questions,
            'rubric' => $request->rubric,
            'remedial_plan' => $request->remedial_plan,
            'enrichment' => $request->enrichment, // Simpan Pengayaan
        ]);

        return redirect()->back()->with('success', 'Asesmen berhasil disimpan.');
    }

    // --- 3. UPDATE DATA (EDIT) ---
    public function update(Request $request, $id)
    {
        $assessment = Assessment::findOrFail($id);

        // Cek otorisasi edit: Guru hanya boleh edit punya sendiri
        if(Auth::user()->role == 'guru_mapel' && $assessment->user_id != Auth::id()) {
             return back()->with('error', 'Anda tidak berhak mengedit data ini.');
        }

        $request->validate([
            'subject_id' => 'required',
            'title' => 'required',
            'type' => 'required',
            'technique' => 'required',
            'questions' => 'required',
        ]);

        $assessment->update([
            'subject_id' => $request->subject_id,
            'title' => $request->title,
            'type' => $request->type,
            'technique' => $request->technique,
            'total_score' => $request->total_score, // Update Skor
            'questions' => $request->questions,
            'rubric' => $request->rubric,
            'remedial_plan' => $request->remedial_plan,
            'enrichment' => $request->enrichment, // Update Pengayaan
        ]);

        return redirect()->back()->with('success', 'Asesmen berhasil diperbarui!');
    }

    // --- 4. HAPUS DATA (DELETE) ---
    public function destroy($id)
    {
        $assessment = Assessment::findOrFail($id);
        
        // Cek otorisasi hapus
        if(Auth::user()->role == 'guru_mapel' && $assessment->user_id != Auth::id()) {
             return back()->with('error', 'Anda tidak berhak menghapus data ini.');
        }

        $assessment->delete();
        return redirect()->back()->with('success', 'Asesmen dihapus.');
    }

    // --- 5. CETAK MASSAL ---
    public function printBulk(Request $request)
    {
        $request->validate([
            'assessment_ids' => 'required|array|min:1',
        ]);

        $user = Auth::user();
        
        // Query data yang mau dicetak
        $query = Assessment::with('subject')->whereIn('id', $request->assessment_ids);

        // Keamanan: Pastikan hanya mencetak data yang boleh dilihat
        if ($user->role == 'guru_mapel') {
            $query->where('user_id', $user->id);
        } 
        elseif ($user->role == 'admin_mapel') {
            // Perbaikan Logic: Admin Mapel boleh cetak semua asesmen dalam lingkup mapelnya
            $subjectIds = $user->subjects->pluck('id');
            $query->whereIn('subject_id', $subjectIds);
        }

        $data = $query->latest()->get();

        if($data->isEmpty()) {
            return back()->with('error', 'Tidak ada data asesmen yang dapat dicetak.');
        }

        return view('pages.perangkat.asesmen.print', compact('data'));
    }
}