<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Siswa;
use App\Models\Kelas;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Barryvdh\DomPDF\Facade\Pdf;

class SiswaController extends Controller
{
    public function index(Request $request)
    {
        $query = Siswa::with('kelas');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('nama', 'like', "%$search%")
                  ->orWhere('nisn', 'like', "%$search%");
            });
        }

        if ($request->filled('filter_kelas')) {
            $query->where('id_kelas', $request->filter_kelas);
        }

        $perPage = $request->get('perPage', 10);
        $siswas  = $query->paginate($perPage)->appends($request->all());
        $kelass  = Kelas::orderBy('tingkat')->orderBy('nama_kelas')->get();

        return view('admin.siswa.index', compact('siswas', 'kelass'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nisn'          => 'required|string|max:20|unique:siswas,nisn',
            'nama'          => 'required|string|max:100',
            'tempat_lahir'  => 'required|string|max:50',
            'tanggal_lahir' => 'required|date',
            'id_kelas'      => 'required|exists:kelas,id_kelas',
            'password'      => 'required|string|min:6',
        ], [
            'nisn.required'          => 'NISN wajib diisi',
            'nisn.unique'            => 'NISN sudah terdaftar',
            'nama.required'          => 'Nama wajib diisi',
            'tempat_lahir.required'  => 'Tempat lahir wajib diisi',
            'tanggal_lahir.required' => 'Tanggal lahir wajib diisi',
            'id_kelas.required'      => 'Kelas wajib dipilih',
            'id_kelas.exists'        => 'Kelas tidak valid',
            'password.required'      => 'Password wajib diisi',
            'password.min'           => 'Password minimal 6 karakter',
        ]);

        Siswa::create([
            'nisn'          => $validated['nisn'],
            'nama'          => $validated['nama'],
            'tempat_lahir'  => $validated['tempat_lahir'],
            'tanggal_lahir' => $validated['tanggal_lahir'],
            'id_kelas'      => $validated['id_kelas'],
            'password'      => Hash::make($validated['password']),
        ]);

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

    public function update(Request $request, $id)
    {
        $siswa = Siswa::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'nama'          => 'required|string|max:100',
            'tempat_lahir'  => 'required|string|max:50',
            'tanggal_lahir' => 'required|date',
            'id_kelas'      => 'required|exists:kelas,id_kelas',
            'password'      => 'nullable|string|min:6',
        ], [
            'nama.required'          => 'Nama wajib diisi',
            'tempat_lahir.required'  => 'Tempat lahir wajib diisi',
            'tanggal_lahir.required' => 'Tanggal lahir wajib diisi',
            'id_kelas.required'      => 'Kelas wajib dipilih',
            'id_kelas.exists'        => 'Kelas tidak valid',
            'password.min'           => 'Password minimal 6 karakter',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error_from', 'edit')
                // Simpan data siswa yang sedang diedit ke session
                // supaya JavaScript bisa mengisi form edit secara otomatis
                ->with('edit_siswa', [
                    'id_siswa'      => $siswa->id_siswa,
                    'nisn'          => $siswa->nisn,
                    'nama'          => $request->nama ?? $siswa->nama,
                    'tempat_lahir'  => $request->tempat_lahir ?? $siswa->tempat_lahir,
                    'tanggal_lahir' => $request->tanggal_lahir ?? $siswa->tanggal_lahir,
                    'id_kelas'      => $request->id_kelas ?? $siswa->id_kelas,
                ]);
        }

        $siswa->nama          = $request->nama;
        $siswa->tempat_lahir  = $request->tempat_lahir;
        $siswa->tanggal_lahir = $request->tanggal_lahir;
        $siswa->id_kelas      = $request->id_kelas;

        if ($request->filled('password')) {
            $siswa->password = Hash::make($request->password);
        }

        $siswa->save();

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

    public function destroy($id)
    {
        $siswa = Siswa::findOrFail($id);
        $siswa->delete();

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

    public function downloadPdf(Request $request)
    {
        $query = Siswa::with('kelas');
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('nama', 'like', "%$search%")
                  ->orWhere('nisn', 'like', "%$search%");
        }
        if ($request->filled('filter_kelas')) {
            $query->where('id_kelas', $request->filter_kelas);
        }
        $siswas = $query->get();

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

        $dompdf = new \Dompdf\Dompdf($options);
        $dompdf->loadHtml(view('admin.siswa.pdf', compact('siswas'))->render());
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();

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

    public function downloadExcel(Request $request)
    {
        $query = Siswa::with('kelas');
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('nama', 'like', "%$search%")
                  ->orWhere('nisn', 'like', "%$search%");
        }
        if ($request->filled('filter_kelas')) {
            $query->where('id_kelas', $request->filter_kelas);
        }
        $siswas = $query->get();

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

        $callback = function () use ($siswas) {
            $file = fopen('php://output', 'w');
            fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($file, ['No', 'NISN', 'Nama', 'Tempat Lahir', 'Tanggal Lahir', 'Kelas']);
            foreach ($siswas as $i => $siswa) {
                fputcsv($file, [
                    $i + 1,
                    $siswa->nisn,
                    $siswa->nama,
                    $siswa->tempat_lahir,
                    \Carbon\Carbon::parse($siswa->tanggal_lahir)->format('d M Y'),
                    $siswa->kelas->tingkat . ' - ' . $siswa->kelas->nama_kelas,
                ]);
            }
            fclose($file);
        };

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