<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\GuruMengajar;
use Illuminate\Http\Request;

class GuruMengajarController extends Controller
{
    public function index(Request $request)
    {
        $query = GuruMengajar::with(['guru', 'mataPelajaran', 'kelas', 'tahunAjaran'])
            ->when($request->guru_id, fn($q) => $q->where('guru_id', $request->guru_id))
            ->when($request->kelas_id, fn($q) => $q->where('kelas_id', $request->kelas_id))
            ->when($request->tahun_ajaran_id, fn($q) => $q->where('tahun_ajaran_id', $request->tahun_ajaran_id))
            ->orderBy('guru_id');

        $data = $request->boolean('all') ? $query->get() : $query->paginate(20);

        return response()->json(['success' => true, 'data' => $data]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'guru_id'          => 'required|exists:guru,id',
            'mata_pelajaran_id'=> 'required|exists:mata_pelajaran,id',
            'kelas_id'         => 'required|exists:kelas,id',
            'tahun_ajaran_id'  => 'required|exists:tahun_ajaran,id',
        ]);

        // Cek duplikat
        $exists = GuruMengajar::where([
            'guru_id'          => $request->guru_id,
            'mata_pelajaran_id'=> $request->mata_pelajaran_id,
            'kelas_id'         => $request->kelas_id,
            'tahun_ajaran_id'  => $request->tahun_ajaran_id,
        ])->exists();

        if ($exists) {
            return response()->json(['success' => false, 'message' => 'Assignment mengajar ini sudah ada.'], 422);
        }

        $data = GuruMengajar::create($request->only(['guru_id', 'mata_pelajaran_id', 'kelas_id', 'tahun_ajaran_id']));
        $data->load(['guru', 'mataPelajaran', 'kelas', 'tahunAjaran']);

        return response()->json(['success' => true, 'message' => 'Assignment mengajar berhasil ditambahkan.', 'data' => $data], 201);
    }

    public function destroy(GuruMengajar $guruMengajar)
    {
        if ($guruMengajar->ujian()->count() > 0) {
            return response()->json(['success' => false, 'message' => 'Guru mengajar ini sudah memiliki ujian, tidak dapat dihapus.'], 422);
        }

        $guruMengajar->delete();
        return response()->json(['success' => true, 'message' => 'Assignment mengajar berhasil dihapus.']);
    }

    public function myMengajar(Request $request)
    {
        $guru = $request->user()->guru;

        if (!$guru) {
            return response()->json(['success' => false, 'message' => 'Profil guru tidak ditemukan.'], 404);
        }

        $data = GuruMengajar::with(['mataPelajaran', 'kelas.tingkatSekolah', 'tahunAjaran'])
            ->where('guru_id', $guru->id)
            ->when($request->tahun_ajaran_id, fn($q) => $q->where('tahun_ajaran_id', $request->tahun_ajaran_id))
            ->get();

        return response()->json(['success' => true, 'data' => $data]);
    }
}
