<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Mapel;
use App\Models\Kelas;
use App\Models\Mengajar;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class MapelController extends Controller
{

    public function index(Request $request)
    {
        $query = Mapel::with('kelas');

        // SEARCH
        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('nama_mapel', 'like', "%$request->search%")
                  ->orWhere('id_mapel', 'like', "%$request->search%");
            });
        }

        // FILTER KELAS
        if ($request->filter_kelas) {
            $query->whereHas('kelas', function ($q) use ($request) {
                $q->where('kelas.id_kelas', $request->filter_kelas);
            });
        }

        $perPage = $request->get('perPage', 10);

        $mapels = $query->paginate($perPage)->appends($request->all());

        $kelass = Kelas::orderBy('tingkat')
            ->orderBy('nama_kelas')
            ->get();

        return view('admin.mapel.index', compact('mapels', 'kelass'));
    }



    public function store(Request $request)
{
    $request->validate([
        'nama_mapel' => 'required|max:100',
        'kelas'      => 'required|array',
    ]);

    // Cek duplikat nama mapel di tiap kelas yang dipilih
    foreach ($request->kelas as $idKelas) {
        $sudahAda = Mengajar::whereHas('mapel', function ($q) use ($request) {
                $q->where('nama_mapel', $request->nama_mapel);
            })
            ->where('id_kelas', $idKelas)
            ->exists();

        if ($sudahAda) {
            $namaKelas = \App\Models\Kelas::find($idKelas);
            return redirect()->back()
                ->withInput()
                ->with('error_from', 'tambah')
                ->withErrors([
                    'nama_mapel' => 'Mapel "' . $request->nama_mapel . '" sudah ada di kelas ' . optional($namaKelas)->nama_kelas . '!'
                ]);
        }
    }

    $mapel = Mapel::create([
        'nama_mapel' => $request->nama_mapel,
    ]);

    foreach ($request->kelas as $kelas) {
        Mengajar::create([
            'id_mapel' => $mapel->id_mapel,
            'id_kelas' => $kelas,
            'id_guru'  => null,
        ]);
    }

    return redirect()->route('admin.mapel.index')
        ->with('success', 'Data mata pelajaran berhasil ditambahkan!');
}

    public function update(Request $request, $id)
    {

        $request->validate([
            'nama_mapel' => 'required|max:100',
            'kelas' => 'required|array'
        ]);

        $mapel = Mapel::findOrFail($id);

        $mapel->update([
            'nama_mapel' => $request->nama_mapel
        ]);

        // hapus relasi lama
        Mengajar::where('id_mapel', $mapel->id_mapel)->delete();

        // simpan relasi baru
        foreach ($request->kelas as $kelas) {

            Mengajar::create([
                'id_mapel' => $mapel->id_mapel,
                'id_kelas' => $kelas,
                'id_guru' => null
            ]);
        }

        return redirect()->route('admin.mapel.index')
            ->with('success', 'Data mata pelajaran berhasil diupdate!');
    }

    public function destroy($id)
    {

        $mapel = Mapel::findOrFail($id);

        Mengajar::where('id_mapel', $id)->delete();

        $mapel->delete();

        return redirect()->route('admin.mapel.index')
            ->with('success', 'Data mata pelajaran berhasil dihapus!');
    }

    public function downloadPdf(Request $request)
{
    $query = Mapel::with('kelas');
    if ($request->filled('search')) {
        $query->where(function($q) use ($request) {
            $q->where('nama_mapel', 'like', "%$request->search%")
              ->orWhere('id_mapel', 'like', "%$request->search%");
        });
    }
    if ($request->filled('filter_kelas')) {
        $query->whereHas('kelas', function($q) use ($request) {
            $q->where('kelas.id_kelas', $request->filter_kelas);
        });
    }
    $mapels = $query->get();

    $pdf = Pdf::loadView('admin.mapel.pdf', compact('mapels'))
              ->setPaper('a4', 'portrait');

    return $pdf->download('daftar-mapel-' . date('Ymd') . '.pdf');
}

public function downloadExcel(Request $request)
{
    $query = Mapel::with('kelas');
    if ($request->filled('search')) {
        $query->where(function($q) use ($request) {
            $q->where('nama_mapel', 'like', "%$request->search%")
              ->orWhere('id_mapel', 'like', "%$request->search%");
        });
    }
    if ($request->filled('filter_kelas')) {
        $query->whereHas('kelas', function($q) use ($request) {
            $q->where('kelas.id_kelas', $request->filter_kelas);
        });
    }
    $mapels = $query->get();

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

    $callback = function () use ($mapels) {
        $file = fopen('php://output', 'w');
        fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($file, ['No', 'ID Mapel', 'Nama Mata Pelajaran', 'Kelas']);
        foreach ($mapels as $i => $mapel) {
            $kelas = $mapel->kelas->map(fn($k) => $k->tingkat . ' ' . $k->nama_kelas)->join(', ');
            fputcsv($file, [$i + 1, $mapel->id_mapel, $mapel->nama_mapel, $kelas]);
        }
        fclose($file);
    };

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