<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Admin\MsBidangPenelitianKategori;
use App\Models\Admin\MsInstitusi;
use App\Models\Admin\MsTujuanSosialKategori;
use App\Models\Biodata;
use App\Models\User\PenelitianSumber;
use App\Models\User\PenelitianSumberAnggota;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Validator;

class PenelitianSumberDanaController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['rs'] = PenelitianSumber::query()->with(['bidang', 'tujuan', 'institusi'])->orderBy('updated_at', 'desc')->get();
        $data['sumber_dana'] = PenelitianSumber::SUMBER_DANA;
        return view('user.penelitiansumber.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data['kategori_bidang'] = MsBidangPenelitianKategori::query()->orderBy('namabidang', 'asc')->get();
        $data['kategori_tujuan'] = MsTujuanSosialKategori::query()->orderBy('namatujuan', 'asc')->get();
        $data['institusi'] = MsInstitusi::query()->orderBy('nama', 'asc')->get();
        $data['jenis'] = PenelitianSumber::JENIS_PENELITIAN;
        $data['sumber'] = PenelitianSumber::SUMBER_DANA;
        $data['edit'] = false;
        return view('user.penelitiansumber.create', $data);
    }

    public function simpan(Request $request)
    {
        // try{
            // $penelitian =
        // }
    }

    public function cekSimpan(Request $request)
    {
        # code...
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->except('_token');

        Validator::make($data, PenelitianSumber::RULES, PenelitianSumber::ERROR_MESSAGES)->validate();

        $data['userid_created'] = Auth::user()->id;
        $data['userid_updated'] = Auth::user()->id;
        $data['bidang_id'] = decrypt($data['bidang_id']);
        $data['tujuan_id'] = decrypt($data['tujuan_id']);
        $data['institusi_id'] = decrypt($data['institusi_id']);

        try{
            $penelitian = PenelitianSumber::query()->create($data);

            return redirect()->route('penelitiansumber.next-form', ['id' => encrypt($penelitian->id)]);
        }
        catch(Exception $ex){
            return redirect()->back()->withInput();
        }

        return redirect()->back()->withInput();
    }

    public function nextForm(Request $request, $id)
    {
        $anggota = PenelitianSumberAnggota::query()->with('biodata')->where('penelitiansumber_id', decrypt($id))->get();

        if(count($anggota) < 1 || is_null($request->next_state)){
            $data['id'] = $id;
            $data['keanggotaan'] = PenelitianSumberAnggota::KEANGGOTAAN;
            $data['dosen_anggota'] = $anggota->whereIn('jenis', ['t', 'd']);
            $data['non_dosen_anggota'] = $anggota->whereIn('jenis', ['l']);

            return view('user.penelitiansumber.create_anggota', $data);
        }
        else if($request->next_state == 'finish' && count($anggota) > 0){
            return redirect()->route('penelitiansumber.index');
        }
    }

    public function editAnggota(Request $request, $id)
    {
        $anggota = PenelitianSumberAnggota::query()->with('biodata')->where('penelitiansumber_id', decrypt($id))->get();
        $data['id'] = $id;
        $data['keanggotaan'] = PenelitianSumberAnggota::KEANGGOTAAN;
        $data['dosen_anggota'] = $anggota->whereIn('jenis', ['t', 'd']);
        $data['non_dosen_anggota'] = $anggota->whereIn('jenis', ['l']);

        return view('user.penelitiansumber.create_anggota', $data);
    }

    public function deleteAnggota(Request $request)
    {
        try{
            $anggota = PenelitianSumberAnggota::query()->find(decrypt($request->id))->delete();

            return response('Success', 200);
        }
        catch(Exception $ex){
            return response('Error', 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data['kategori_bidang'] = MsBidangPenelitianKategori::query()->orderBy('namabidang', 'asc')->get();
        $data['kategori_tujuan'] = MsTujuanSosialKategori::query()->orderBy('namatujuan', 'asc')->get();
        $data['institusi'] = MsInstitusi::query()->orderBy('nama', 'asc')->get();
        $data['jenis'] = PenelitianSumber::JENIS_PENELITIAN;
        $data['sumber'] = PenelitianSumber::SUMBER_DANA;
        $data['edit'] = true;
        $data['data'] = PenelitianSumber::query()->find(decrypt($id));
        return view('user.penelitiansumber.create', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->except('_token');

        Validator::make($data, PenelitianSumber::RULES, PenelitianSumber::ERROR_MESSAGES)->validate();

        $data['userid_updated'] = Auth::user()->id;
        $data['bidang_id'] = decrypt($data['bidang_id']);
        $data['tujuan_id'] = decrypt($data['tujuan_id']);
        $data['institusi_id'] = decrypt($data['institusi_id']);

        try{
            PenelitianSumber::query()->find(decrypt($id))->update($data);
            return redirect()->route('penelitiansumber.index');
        }
        catch(Exception $ex){
            return redirect()->back()->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try{
            DB::beginTransaction();

            $penelitian = PenelitianSumber::query()->find(decrypt($id));
            $anggota = $penelitian->anggota;

            $anggota->delete();
            $penelitian->delete();

            DB::commit();
            return redirect()->route('penelitiansumber.index');
        }
        catch(Exception $ex){
            DB::rollBack();
            return redirect()->route('penelitiansumber.index');
        }
    }

    public function simpanAnggota(Request $request, $id)
    {
        $allAnggota = PenelitianSumberAnggota::where('penelitiansumber_id', decrypt($id))->get();

        $anggota = $allAnggota->where('nidn', $request->nidn);

        $ketua = $allAnggota->where('peran', PenelitianSumberAnggota::KEANGGOTAAN['k']);

        if( count($ketua) > 0 && $request->keanggotaan == PenelitianSumberAnggota::KEANGGOTAAN['k']){

            return response('Ketua tidak boleh lebih dari satu', 500);
        }

        if(count($anggota) < 1){
            $dosen = Biodata::query()->where('nidn', $request->nidn)->first();

            $data = $this->arrayDataAnggota($request);

            $store = $this->getStoredArrayDataAnggota($request, $id, $dosen);

            if(is_null($dosen) && $request->name == 'dosen'){

                return response('NIDN tidak terdaftar sebagai dosen atau belum tervalidasi', 500);
            }
            elseif(!is_null($dosen) && $request->name == 'non_dosen'){

                return response('NIDN terdaftar sebagai dosen', 500);
            }

            try{
                Validator::make($store, PenelitianSumberAnggota::RULES, PenelitianSumberAnggota::ERROR_MESSAGES)->validate();

                $anggota = PenelitianSumberAnggota::query()->create($store);
                $data['id'] = $anggota->id;

                return view('user.penelitiansumber.row_anggota', $data);
            }
            catch(Exception $ex){
                return response('Data yang diberikan tidak lengkap atau tidak valid', 500);
            }
        }
        return response('Data sudah ada', 500);
    }

    private function arrayDataAnggota(Request $request)
    {
        $data['no'] = $request->no;
        $data['nama'] = $request->nama;
        $data['keanggotaan'] = $request->keanggotaan;
        $data['prodi'] = $request->prodi;
        $data['nidn'] = encrypt($request->nidn);
        $data['name'] = $request->name;

        return $data;
    }

    public function getStoredArrayDataAnggota(Request $request, $id, $dosen)
    {
        $store['penelitiansumber_id'] = decrypt($id);
        $store['nidn'] = $request->nidn;
        $store['peran'] = $request->keanggotaan;


        if (!is_null($dosen) && $request->name == 'dosen') {
            $store['jenis'] = $dosen->jenis;
            $store['nama'] = $dosen->nama;

        } elseif (is_null($dosen) && $request->name == 'non_dosen') {
            $store['jenis'] = 'l';
            $store['institusi'] = $request->prodi;
            $store['nama'] = $request->nama;
        }

        return $store;
    }
}
