<?php

namespace App\Http\Controllers;

use App\Models\P5UndanganUjian;
use App\Models\Mahasiswa;
use App\Traits\AutoNumber;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class P5Controller extends Controller
{
    use AutoNumber;

    protected $table = 'p5_undangan_ujian';

    public function index()
    {
        $p5 = P5UndanganUjian::with('mahasiswa')->get();
        return view('p5.undangan_ujian.index', compact('p5'));
    }

    public function create()
    {
        $mahasiswa = Mahasiswa::all();
        $nosrt = $this->generateNumber('P5');
        return view('p5.undangan_ujian.create', compact('mahasiswa', 'nosrt'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'nosrt' => 'required',
            'nim' => 'required',
            'judul_skripsi' => 'required',
            'tanggal_ujian' => 'required',
            'jam' => 'required',
            'tempat' => 'required',
        ]);

        $mhs = Mahasiswa::where('nim', $request->nim)->first();

        P5UndanganUjian::create(array_merge($request->all(), [
            'nama' => $mhs->nama,
            'tanggal' => now()
        ]));

        return redirect()->route('p5.undangan_ujian.index')->with('success', 'Undangan ujian berhasil ditambahkan.');
    }

    public function edit($nosrt)
    {
        $p5 = P5UndanganUjian::findOrFail($nosrt);
        $mahasiswa = Mahasiswa::all();
        return view('p5.undangan_ujian.edit', compact('p5', 'mahasiswa'));
    }

    public function update(Request $request, $nosrt)
    {
        $request->validate([
            'nim' => 'required',
            'judul_skripsi' => 'required',
            'tanggal_ujian' => 'required',
            'jam' => 'required',
            'tempat' => 'required',
        ]);

        $mhs = Mahasiswa::where('nim', $request->nim)->first();

        $p5 = P5UndanganUjian::findOrFail($nosrt);
        $p5->update(array_merge($request->all(), [
            'nama' => $mhs->nama
        ]));

        return redirect()->route('p5.undangan_ujian.index')->with('success', 'Undangan ujian berhasil diperbarui.');
    }

    public function destroy($nosrt)
    {
        $p5 = P5UndanganUjian::findOrFail($nosrt);
        $p5->delete();
        return redirect()->route('p5.undangan_ujian.index')->with('success', 'Undangan ujian berhasil dihapus.');
    }

    public function cetak_pdf($nosrt)
    {
        $p5 = P5UndanganUjian::with('mahasiswa')->findOrFail($nosrt);
        $pdf = Pdf::loadView('p5.undangan_ujian.pdf', compact('p5'));
        return $pdf->stream('p5_' . $p5->nim . '.pdf');
    }
}

