<?php

namespace App\Http\Controllers\tables;

use App\Exports\NilaiExport;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use App\Models\Nilai;
use App\Models\Siswa;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NilaiController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        if ($user->role == "Siswa") {
            $nilai = Nilai::join("siswa", "siswa.user_id", "=", "nilai.user_id")->where("siswa.user_id", $user->id)->get();
        } else {
            $nilai = Nilai::join("siswa", "siswa.user_id", "=", "nilai.user_id")->get(["siswa.*", "nilai.*", "nilai.id as nilai_id"]);
        }
        return view('content.nilai.index', compact('nilai'));
    }

    public function create()
    {
        $siswa = Siswa::whereNotIn('user_id', function ($query) {
            $query->select('user_id')->from('nilai');
        })->get();

        return view('content.nilai.create', compact('siswa'));
    }

    public function edit(Request $request, $nilaiId)
    {
        $nilai = Nilai::join("siswa", "siswa.user_id", "=", "nilai.user_id")->where("nilai.id", $nilaiId)->first(["siswa.*", "nilai.*", "nilai.id as nilai_id"]);
        return view('content.nilai.edit', compact('nilai'));
    }

    public function insert(Request $request)
    {
        Nilai::create([
            "user_id" => $request->id,
            "writing" => $request->writing,
            "reading" => $request->reading,
            "listening" => $request->listening,
            "speaking" => $request->speaking,
        ]);

        return redirect()->route("nilai")->with("success", "Data Berhasil Disimpan!");
    }
    public function update(Request $request, $nilaiId)
    {
        $nilai = Nilai::find($nilaiId);
        $nilai->fill($request->input())->save();

        return redirect()->route("nilai")->with("success", "Data Berhasil Diperbarui!");
    }

    public function destroy(Request $request, $nilaiId)
    {
        $id = $nilaiId;
        $nilai = Nilai::find($id);

        $nilai->delete();

        return redirect()->route("nilai")->with("success", "Data Berhasil Dihapus!");
    }

    public function export(Request $request)
    {
        switch ($request->output) {
            case "pdf":
                $nilai = Nilai::join("siswa", "siswa.user_id", "=", "nilai.user_id")->get();
                $pdf = Pdf::loadView('content.nilai.export-pdf', ['nilai' => $nilai]);
                $pdf->setPaper('A4', 'portrait');
                return $pdf->download('data-nilai.pdf');
            default:
                return Excel::download(new NilaiExport, 'nilai.xlsx');
        }
    }
}
