<?php

namespace App\Http\Controllers\tables;

use App\Exports\JadwalExport;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Jadwal;
use App\Models\Tutor;
use Illuminate\Support\Facades\Auth;

class JadwalController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $jadwal = Jadwal::join("tutor", "tutor.id", "=", "jadwal.tutor_id");
        if ($user->role != "Admin") {
            $jadwal = $jadwal->where("kelas", "=", $user->kelas);
        }

        $jadwal = $jadwal->get(["tutor.*", "jadwal.*", "jadwal.id as jadwal_id"]);
        return view('content.jadwal.index', compact('jadwal'));
    }

    public function create()
    {
        $tutor = Tutor::all();
        return view('content.jadwal.create', compact('tutor'));
    }

    public function edit(Request $request, $jadwalId)
    {
        $tutor = Tutor::all();
        $jadwal = Jadwal::join("tutor", "tutor.id", "=", "jadwal.tutor_id")->where("jadwal.id", "=", $jadwalId)->first(["tutor.*", "jadwal.*", "jadwal.id as jadwal_id"]);
        return view('content.jadwal.edit', compact('jadwal', 'tutor'));
    }

    public function insert(Request $request)
    {
        Jadwal::create([
            "tutor_id" => $request->tutor,
            "kelas" => $request->kelas,
            "hari" => $request->hari,
            "jam" => $request->jam,
        ]);

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

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

    public function destroy(Request $request, $jadwalId)
    {
        $id = $jadwalId;
        $jadwal = Jadwal::find($id);

        $jadwal->delete();

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

    public function export(Request $request)
    {
        switch ($request->output) {
            case "pdf":
                $jadwal = Jadwal::join("tutor", "tutor.id", "=", "jadwal.tutor_id")->get();
                $pdf = Pdf::loadView('content.jadwal.export-pdf', ['jadwal' => $jadwal]);
                $pdf->setPaper('A4', 'portrait');
                return $pdf->download('data-jadwal.pdf');
            default:
                return Excel::download(new JadwalExport, 'jadwal.xlsx');
        }
    }
}
