<?php

namespace App\Http\Controllers;

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

class P3Controller extends Controller
{
    use AutoNumber;

    protected $table = 'p3_surat_penelitian';

    public function index()
    {
        $p3 = P3SuratPenelitian::with('mahasiswa')->get();
        return view('p3.surat_penelitian.index', compact('p3'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'nosrt' => 'required',
            'nim_mahasiswa' => 'required',
            'judul' => 'required',
            'kepada' => 'required',
        ]);

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

        return redirect()->route('p3.surat_penelitian.index')->with('success', 'Surat penelitian berhasil ditambahkan.');
    }

    public function edit($nosrt)
    {
        $p3 = P3SuratPenelitian::findOrFail($nosrt);
        $mahasiswa = Mahasiswa::all();
        return view('p3.surat_penelitian.edit', compact('p3', 'mahasiswa'));
    }

    public function update(Request $request, $nosrt)
    {
        $request->validate([
            'nim_mahasiswa' => 'required',
            'judul' => 'required',
            'kepada' => 'required',
        ]);

        $p3 = P3SuratPenelitian::findOrFail($nosrt);
        $p3->update($request->all());

        return redirect()->route('p3.surat_penelitian.index')->with('success', 'Surat penelitian berhasil diperbarui.');
    }

    public function destroy($nosrt)
    {
        $p3 = P3SuratPenelitian::findOrFail($nosrt);
        $p3->delete();

        return redirect()->route('p3.surat_penelitian.index')->with('success', 'Surat penelitian berhasil dihapus.');
    }

    public function cetak_pdf($nosrt)
    {
        $p3 = P3SuratPenelitian::with('mahasiswa')->findOrFail($nosrt);
        $pdf = Pdf::loadView('p3.surat_penelitian.pdf', compact('p3'));
        return $pdf->stream('p3_' . $p3->nim_mahasiswa . '.pdf');
    }
}

