<?php

namespace App\Http\Controllers\Dosen;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\GetDataApiController;

use App\Models\Kelompok;
use App\Models\KelompokDetail;
use App\Models\Periode;

use Session;
use Alert;

class KelompokController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        $title      = 'Daftar Kelompok';
        $bio        = auth()->user()->rBiodata;
        $getDosen   = GetDataApiController::getDosen();
        // $periode    = Periode::where('status', 1)->first();
        $periode    = Periode::query()->get();
        $year       = !is_null($request->year) ? $request->year : now()->year;

        $kelompok = Kelompok::with(['rAnggota'])
                    ->where('nidn_dosen', $bio->noidentitas)
                    ->where('kirim', '1')
                    ->whereYear('created_at', $year)
                    ->orderBy('kode')
                    ->get();

        $cekKel   = $kelompok->where('created_user', auth()->user()->id)->count();

        $data = [
            'kelompok'  => $kelompok,
            'title'     => $title,
            'cekKel'    => $cekKel,
            'dosen'     => $getDosen['data'],
            'periode'   => $periode,
            'year'      => $year,
        ];

        return view('backend.dosen.kelompok.index', $data);
    }

    public function tolak(Request $request)
    {
        $kel = $request->except('_token');

        $kelompok = Kelompok::query()->find(decrypt($kel['id']));

        $kelompok->status = 2;
        $kelompok->save();

        Alert::success('Berhasil disimpan');

        return redirect()->route('dosen.kelompok.index');
    }

    public function terima(Request $request)
    {
        $kel = $request->except('_token');

        $kelompok = Kelompok::query()->find(decrypt($kel['id']));

        $kelompok->status = 1;
        $kelompok->save();

        Alert::success('Berhasil disimpan');

        return redirect()->route('dosen.kelompok.index');
    }

}
