<?php

namespace App\Http\Controllers\Admin; 

use App\Http\Controllers\Controller;  
use App\Models\Guru;
use App\Models\Mapel;
use App\Models\Kelas;
use App\Models\Mengajar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class GuruController extends Controller
{
    public function index(Request $request)
    {
        $query = Guru::with('mengajars.mapel', 'mengajars.kelas');
        
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('nama', 'like', "%$search%")
                  ->orWhere('nip', 'like', "%$search%");
            });
        }

        $perPage = $request->get('perPage', 10);
        $gurus   = $query->paginate($perPage)->appends($request->all());
        $mapels  = Mapel::all();
        $kelas   = Kelas::all();

        return view('admin.guru.index', compact('gurus', 'mapels', 'kelas'));
    }

    public function create()
    {
        return view('admin.guru.create');
    }

    /**
     * Tambah guru + bisa pilih banyak pasangan (mapel, kelas)
     * Input: mapel[] dan kelas[] dengan index yang bersesuaian
     */
    public function store(Request $request)
    {
        $request->validate([
            'nip'        => 'required|string|max:30|unique:gurus,nip',
            'nama'       => 'required|string|max:100',
            'password'   => 'required|string|min:6',
            'id_mapel'   => 'required|array|min:1',
            'id_mapel.*' => 'required|exists:mapels,id_mapel',
            'id_kelas'   => 'required|array|min:1',
            'id_kelas.*' => 'required|exists:kelas,id_kelas',
        ], [
            'id_mapel.required' => 'Pilih minimal 1 mata pelajaran.',
            'id_kelas.required' => 'Pilih minimal 1 kelas.',
        ]);

        $guru = Guru::create([
            'nip'      => $request->nip,
            'nama'     => $request->nama,
            'password' => Hash::make($request->password),
        ]);

        // Tiap mapel berpasangan dengan kelas di index yang sama
        foreach ($request->id_mapel as $i => $idMapel) {
            $idKelas = $request->id_kelas[$i] ?? $request->id_kelas[0];
            Mengajar::create([
                'id_guru'  => $guru->id_guru,
                'id_mapel' => $idMapel,
                'id_kelas' => $idKelas,
            ]);
        }

        return redirect()->route('admin.guru.index')
            ->with('success', 'Data guru berhasil ditambahkan.');
    }

    public function show(string $id)
    {
        $guru = Guru::findOrFail($id);
        return view('admin.guru.show', compact('guru'));
    }

    public function edit(string $id)
    {
        $guru = Guru::findOrFail($id);
        return view('admin.guru.edit', compact('guru'));
    }

    /**
     * Update guru — hapus semua mengajar lama, insert ulang
     */
    public function update(Request $request, string $id)
    {
        $guru = Guru::findOrFail($id);

        $request->validate([
            'nip'        => 'required|string|max:30|unique:gurus,nip,' . $guru->id_guru . ',id_guru',
            'nama'       => 'required|string|max:100',
            'password'   => 'nullable|string|min:6',
            'id_mapel'   => 'required|array|min:1',
            'id_mapel.*' => 'required|exists:mapels,id_mapel',
            'id_kelas'   => 'required|array|min:1',
            'id_kelas.*' => 'required|exists:kelas,id_kelas',
        ]);

        $guru->nip  = $request->nip;
        $guru->nama = $request->nama;
        if ($request->filled('password')) {
            $guru->password = Hash::make($request->password);
        }
        $guru->save();

        // Hapus semua data mengajar lama, insert ulang
        Mengajar::where('id_guru', $guru->id_guru)->delete();

        foreach ($request->id_mapel as $i => $idMapel) {
            $idKelas = $request->id_kelas[$i] ?? $request->id_kelas[0];
            Mengajar::create([
                'id_guru'  => $guru->id_guru,
                'id_mapel' => $idMapel,
                'id_kelas' => $idKelas,
            ]);
        }

        return redirect()->route('admin.guru.index')
            ->with('success', 'Data guru berhasil diupdate.');
    }

    public function destroy(string $id)
    {
        $guru = Guru::findOrFail($id);
        $guru->delete();

        return redirect()->route('admin.guru.index')
            ->with('success', 'Data guru berhasil dihapus.');
    }

    /**
     * API: Ambil kelas yang memiliki mapel tertentu (lewat tabel mengajars)
     * Dipanggil via AJAX saat admin pilih mapel di modal
     */
    public function getKelasByMapel(Request $request)
    {
        $idMapel = $request->id_mapel;

        // Cari kelas yang sudah punya mapel ini di tabel mengajars
        $kelasList = Kelas::whereHas('mengajars', function ($q) use ($idMapel) {
                $q->where('id_mapel', $idMapel);
            })
            ->get(['id_kelas', 'nama_kelas', 'tingkat']);

        return response()->json($kelasList);
    }
}