<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\Mapel;
use App\Models\Materi;
use App\Models\Tugas;
use App\Models\Mengajar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MapelController extends Controller
{
    public function index()
    {
        $guru = Auth::guard('guru')->user();

        // Ambil mengajar dengan relasi mapel & kelas
        // Group by id_mapel agar tidak duplikat jika guru ajar mapel sama di kelas berbeda
        $mengajars = Mengajar::with(['mapel', 'kelas'])
            ->where('id_guru', $guru->id_guru)
            ->get()
            ->groupBy('id_mapel'); // group by mapel

        return view('guru.mapel.index', compact('mengajars'));
    }

    /**
     * Simpan materi baru
     */
    public function storeMateri(Request $request)
    {
        $guru = Auth::guard('guru')->user();

        $request->validate([
            'id_mengajar'     => 'required|exists:mengajars,id_mengajar',
            'judul_materi'    => 'required|string|max:200',
            'deskripsi'       => 'nullable|string',
            'lampiran_materi' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png,ppt,pptx|max:10240',
        ], [
            'lampiran_materi.mimes' => 'Format file: pdf, doc, docx, jpg, png, ppt, pptx.',
            'lampiran_materi.max'   => 'Ukuran file maksimal 10MB.',
        ]);

        // Pastikan mengajar ini milik guru yang login
        $mengajar = Mengajar::where('id_mengajar', $request->id_mengajar)
            ->where('id_guru', $guru->id_guru)
            ->firstOrFail();

        $path = null;
        if ($request->hasFile('lampiran_materi')) {
            $file = $request->file('lampiran_materi');
            $filename = 'materi_' . $guru->id_guru . '_' . time() . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs('materi', $filename, 'public');
        }

        Materi::create([
            'id_mengajar'     => $request->id_mengajar,
            'judul_materi'    => $request->judul_materi,
            'deskripsi'       => $request->deskripsi,
            'lampiran_materi' => $path,
        ]);

        return redirect()->route('guru.mapel.index')
            ->with('success', 'Materi berhasil diupload!');
    }

    /**
     * Simpan tugas baru
     */
    public function storeTugas(Request $request)
    {
        $guru = Auth::guard('guru')->user();

        $request->validate([
            'id_mengajar' => 'required|exists:mengajars,id_mengajar',
            'judul_tugas' => 'required|string|max:200',
            'keterangan'  => 'nullable|string',
            'deadline'    => 'required|date|after:now',
        ], [
            'deadline.after' => 'Deadline harus lebih dari waktu sekarang.',
        ]);

        // Pastikan mengajar ini milik guru yang login
        $mengajar = Mengajar::where('id_mengajar', $request->id_mengajar)
            ->where('id_guru', $guru->id_guru)
            ->firstOrFail();

        Tugas::create([
            'id_mengajar' => $request->id_mengajar,
            'judul_tugas' => $request->judul_tugas,
            'keterangan'  => $request->keterangan,
            'deadline'    => $request->deadline,
        ]);

        return redirect()->route('guru.mapel.index')
            ->with('success', 'Tugas berhasil dibuat!');
    }

    /**
     * History semua materi yang dibuat guru ini
     */
    public function historyMateri()
    {
        $guru = Auth::guard('guru')->user();

        // Ambil id_mengajar milik guru ini
        $idMengajars = Mengajar::where('id_guru', $guru->id_guru)
            ->pluck('id_mengajar');

        $materiList = Materi::with(['mengajar.mapel', 'mengajar.kelas'])
            ->whereIn('id_mengajar', $idMengajars)
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('guru.materi.history', compact('materiList'));
    }

    /**
     * Hapus materi
     */
    public function destroyMateri($id)
    {
        $guru = Auth::guard('guru')->user();

        $idMengajars = Mengajar::where('id_guru', $guru->id_guru)->pluck('id_mengajar');

        $materi = Materi::whereIn('id_mengajar', $idMengajars)
            ->where('id_materi', $id)
            ->firstOrFail();

        // Hapus file jika ada
        if ($materi->lampiran_materi && \Storage::disk('public')->exists($materi->lampiran_materi)) {
            \Storage::disk('public')->delete($materi->lampiran_materi);
        }

        $materi->delete();

        return redirect()->route('guru.materi.history')
            ->with('success', 'Materi berhasil dihapus.');
    }

    /**
     * History semua tugas yang dibuat guru ini
     */
    public function historyTugas()
    {
        $guru = Auth::guard('guru')->user();

        $idMengajars = Mengajar::where('id_guru', $guru->id_guru)
            ->pluck('id_mengajar');

        $tugasList = Tugas::with(['mengajar.mapel', 'mengajar.kelas', 'pengumpulanTugas'])
            ->whereIn('id_mengajar', $idMengajars)
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('guru.tugas.history', compact('tugasList'));
    }

    /**
     * Detail tugas + daftar pengumpulan siswa
     */
    public function detailTugas($id)
    {
        $guru = Auth::guard('guru')->user();

        $idMengajars = Mengajar::where('id_guru', $guru->id_guru)->pluck('id_mengajar');

        $tugas = Tugas::with([
                'mengajar.mapel',
                'mengajar.kelas',
                'pengumpulanTugas.siswa',
            ])
            ->whereIn('id_mengajar', $idMengajars)
            ->where('id_tugas', $id)
            ->firstOrFail();

        return view('guru.tugas.detail', compact('tugas'));
    }

    /**
     * Hapus tugas
     */
    public function destroyTugas($id)
    {
        $guru = Auth::guard('guru')->user();

        $idMengajars = Mengajar::where('id_guru', $guru->id_guru)->pluck('id_mengajar');

        $tugas = Tugas::whereIn('id_mengajar', $idMengajars)
            ->where('id_tugas', $id)
            ->firstOrFail();

        $tugas->delete();

        return redirect()->route('guru.tugas.history')
            ->with('success', 'Tugas berhasil dihapus.');
    }
}