<?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;
use Barryvdh\DomPDF\Facade\Pdf;

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),
        ]);

        foreach ($request->id_mapel as $i => $idMapel) {
        $idKelas = $request->id_kelas[$i] ?? $request->id_kelas[0];

        Mengajar::updateOrCreate(
            [
                'id_mapel' => $idMapel,
                'id_kelas' => $idKelas,
                'id_guru'  => null,  
            ],
            [
                'id_guru'  => $guru->id_guru,
            ]
        );
    }

        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::updateOrCreate(
                [
                    'id_mapel' => $idMapel,
                    'id_kelas' => $idKelas,
                    'id_guru'  => null,
                ],
                [
                    'id_guru'  => $guru->id_guru,
                ]
            );
        }

        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.');
    }

    public function downloadPdf(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%");
        });
    }
    $gurus = $query->get();

    // Override DomPDF options langsung
    $options = new \Dompdf\Options();
    $options->setChroot(base_path('public'));
    $options->setIsRemoteEnabled(true);

    $dompdf = new \Dompdf\Dompdf($options);

    $html = view('admin.guru.pdf', compact('gurus'))->render();
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->render();

    return response($dompdf->output(), 200, [
        'Content-Type'        => 'application/pdf',
        'Content-Disposition' => 'attachment; filename="daftar-guru-' . date('Ymd') . '.pdf"',
    ]);
}

public function downloadExcel(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%");
        });
    }
    $gurus = $query->get();

    $filename = 'daftar-guru-' . date('Ymd') . '.csv';
    $headers  = [
        'Content-Type'        => 'text/csv',
        'Content-Disposition' => "attachment; filename=\"$filename\"",
    ];

    $callback = function () use ($gurus) {
        $file = fopen('php://output', 'w');
        // BOM agar Excel bisa baca UTF-8
        fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($file, ['No', 'Nama', 'NIP', 'Mata Pelajaran', 'Kelas']);
        foreach ($gurus as $i => $guru) {
            $mapels = $guru->mengajars->map(fn($m) => optional($m->mapel)->nama_mapel ?? '-')->join(', ');
            $kelas  = $guru->mengajars->map(fn($m) => (optional($m->kelas)->tingkat . ' ' . optional($m->kelas)->nama_kelas))->join(', ');
            fputcsv($file, [$i + 1, $guru->nama, $guru->nip, $mapels, $kelas]);
        }
        fclose($file);
    };

    return response()->stream($callback, 200, $headers);
}

    /**
     * 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);
    }
}