<?php

namespace App\Http\Controllers;

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

class P1Controller extends Controller
{
    use AutoNumber;

    protected $table = 'p1_persetujuan_penelitian';

    public function index()
    {
        $p1 = P1PersetujuanPenelitian::all();
        return view('p1.persetujuan.index', compact('p1'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'nosrt' => 'required|unique:p1_persetujuan_penelitian,nosrt',
            'nim' => 'required',
            'lokasi_penelitian' => 'required',
            'judul' => 'required',
        ]);

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

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

        return redirect()->route('p1.persetujuan.index')->with('success', 'Data P1 berhasil ditambahkan.');
    }

    public function edit(P1PersetujuanPenelitian $p1_persetujuan_penelitian)
    {
        $mahasiswa = Mahasiswa::all();
        $p1 = $p1_persetujuan_penelitian;
        return view('p1.persetujuan.edit', compact('p1', 'mahasiswa'));
    }

    public function update(Request $request, P1PersetujuanPenelitian $p1_persetujuan_penelitian)
    {
        $request->validate([
            'nim' => 'required',
            'lokasi_penelitian' => 'required',
            'judul' => 'required',
        ]);

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

        $p1_persetujuan_penelitian->update(array_merge($request->all(), [
            'nama' => $mhs->nama,
            'jurusan' => $mhs->jurusan,
            'alamat' => $mhs->alamat,
        ]));

        return redirect()->route('p1.persetujuan.index')->with('success', 'Data P1 berhasil diperbarui.');
    }

    public function destroy(P1PersetujuanPenelitian $p1_persetujuan_penelitian)
    {
        $p1_persetujuan_penelitian->delete();
        return redirect()->route('p1.persetujuan.index')->with('success', 'Data P1 berhasil dihapus.');
    }

    public function cetak_pdf(P1PersetujuanPenelitian $p1)
    {
        $pdf = Pdf::loadView('p1.persetujuan.pdf', compact('p1'));
        return $pdf->stream('p1_' . $p1->nim . '.pdf');
    }
}

