<?php

namespace App\Http\Controllers;

use PDF;
use Carbon\Carbon;
use App\Models\Tor;
use App\Models\User;
use App\Models\Dosen;
use App\Models\Prodi;
use App\Models\Pejabat;
use App\Models\Mahasiswa;
use Illuminate\Http\Request;
use App\Exports\NilaiUPExport;
use App\Imports\NilaiUPImport;
use App\Exports\TemplateNilaiUP;
use App\Exports\TorPotensiExport;
use App\Imports\TorPotensiImport;
use App\Exports\TemplateTorPotensi;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\Facades\DataTables;

class TorController extends Controller
{
    private $activeMenuTorPotensi = 'Home/Tor/Potensi';
    private $activeMenuTorPengajuan = 'Home/Tor/Pengajuan';
    private $activeMenuTorNilai = 'Home/Tor/Nilai';

    // Tor
    public function potensi(Request $request)
    {
        return view('pages.portal.tor.potensi.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Tor' => '/',
                'Potensi' => '/'
            ],
            'activeMenu' => $this->activeMenuTorPotensi,
            'prodis' => $this->getProdiCombo(),
            'kelass' =>  $this->getKelasCombo(),
            'periodes' => $this->getPeriodeTorCombo(),
        ]);
    }


    public function potensiList(Request $request)
    {

        if ($request->ajax()) {
            $where = '';

            if (!empty($request->periode)) {
                $where .= ' AND tors.periode ="' . $request->periode . '"';
            }

            if (!empty($request->prodi)) {
                $where .= ' AND tors.prodi_id = "' . $request->prodi . '"';
            }

            if (!empty($request->kelas)) {
                $where .= ' AND tors.kelas LIKE "%' . $request->kelas . '%"';
            }

            if (!empty($request->konfirmasi)) {
                $where .= ' AND tors.konfirmasi LIKE "%' . $request->konfirmasi . '%"';
            }

            if (!empty($request->status)) {
                $where .= ' AND tors.status LIKE "%' . $request->status . '%"';
            }

            if (!empty($request->sidang)) {
                $where .= ' AND tors.id NOT IN (SELECT tor_id FROM sidangs)';
            }

            if (auth()->user()->role == 'dosen') {
                $ids = Dosen::where('kode', auth()->user()->username)->first();
                $where .= ' AND (tors.pembimbing_1 = ' . $ids->id . ' OR tors.pembimbing_2 = ' . $ids->id . ')';
            }

            $data = Tor::query()
                ->leftjoin('mahasiswas as m', 'm.id', 'tors.mahasiswa_id')
                ->leftJoin('prodis as p', 'p.id', 'tors.prodi_id')
                ->leftJoin('dosens as pbb1', 'pbb1.id', 'tors.pembimbing_1')
                ->leftJoin('dosens as pbb2', 'pbb2.id', 'tors.pembimbing_2')
                ->leftJoin('forms as f', 'f.id', 'tors.form_id')
                ->selectRaw('
            tors.*,
            m.nim,
            m.nama,
            p.kode as kodeprodi,
            p.prodi as prodi,
            p.jurusan as jurusan,
            pbb1.kode as kodepbb1,
            pbb1.nama as pbb1,
            pbb2.kode as kodepbb2,
            pbb2.nama as pbb2,
            f.nama as namaform
            ')
                ->whereRaw('1 ' . $where)
                ->orderBy('tors.updated_at', 'desc');

            return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('judul', function (Tor $tor) {
                    $html = '<a href="javascript:void(0)" title="Detail" data-toggle="modal" data-target="#detail' . $tor->id . '">' . $tor->judul . '</a><br>Form: ' . $tor->namaform . '
                    <div class="modal fade" id="detail' . $tor->id . '">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-body text-left pb-0">

                                <div class="col-10 offset-1  text-center mb-3">
                                <img src="' . asset('images/logo.png') . '" width="60" style="position:absolute;left:0">
                                    <h6 class="text-center text-bold">' . env('APP_INSTITUTION') . '<br>FORMAT PENGAJUAN<BR>DRAFT USULAN PENELITIAN (UP) TA / PA / SKRIPSI</h6>   
                                </div>

                                <div class="col-10 offset-1 border border-dark mb-2 p-3">
                                    <dl class="row mb-0">
                                        <dt class="col-3 font-weight-normal">NAMA</dt>
                                        <dd class="col-9 mb-0">' . $tor->nama . '</dd>
                                        
                                        <dt class="col-3 font-weight-normal">NIM</dt>
                                        <dd class="col-9 mb-0">' . $tor->nim . '</dd>
                                        
                                        <dt class="col-3 font-weight-normal">JURUSAN</dt>
                                        <dd class="col-9 mb-0">' . ucwords(strtolower($tor->jurusan)) . '</dd>
                                    
                                        <dt class="col-3 font-weight-normal">PROGRAM STUDI</dt>
                                        <dd class="col-9 mb-0">' . ucwords(strtolower($tor->prodi)) . '</dd>
                                    </dl>
                                </div>
                                
                                <div class="col-10 offset-1  border border-dark mb-2 p-3">
                                        <h6 class="text-center text-bold">LATAR BELAKANG PENELITIAN<br>( Deskripsi dan Data Awal Penelitian)</h6>

                                        ' . nl2br($tor->latar_belakang) . '
                                </div>
                                
                                <div class="col-10 offset-1  border border-dark mb-2 p-3">
                                        <h6 class="text-center text-bold">TUJUAN DAN KEGUNAAN PENELITIAN</h6>

                                        ' . nl2br($tor->tujuan) . '
                                </div>
                                
                                <div class="col-10 offset-1  border border-dark mb-2 p-3">
                                        <h6 class="text-center text-bold">TOPIK / JUDUL / LOKUS</h6>

                                        <dl class="row mb-0">
                                            <dt class="col-2 font-weight-normal">TOPIK</dt>
                                            <dd class="col-10 mb-0">' .  ucwords(strtolower($tor->topik)) . '</dd>
                                            
                                            <dt class="col-2 font-weight-normal">JUDUL</dt>
                                            <dd class="col-10 mb-0">' . ucwords(strtolower($tor->judul)) . '</dd>
                                            
                                            <dt class="col-2 font-weight-normal">LOKUS</dt>
                                            <dd class="col-10 mb-0">' . $tor->lokus . '</dd>
                                        </dl>
                                </div>
                                
                                <div class="col-10 offset-1  border border-dark mb-2 p-3">
                                        <h6 class="text-center text-bold">USULAN PEMBIMBING</h6>
                                        1. ' . $tor->pbb1 . '<br>
                                        2. ' . $tor->pbb2 . '
                                </div>

                                </div>
                                <div class="modal-footer pt-0 border-0 justify-content-center">
                                        <a href="javascript:void(0)" class="btn mr-2" data-dismiss="modal">Kembali</a>
                                </div>
                            </div>
                        </div>
                    </div>
                    ';
                    return $html;
                })
                ->addColumn('konfirmasi', function (Tor $tor) {
                    $html = '';
                    if ($tor->judul !== null && $tor->pembimbing_1 !== null && $tor->pembimbing_2 !== null) {
                        if ($tor->konfirmasi == 'Diterima') {
                            $html = '<span class="text-primary font-weight-bold">Diterima</span>';
                        } else if ($tor->konfirmasi == 'Ditolak') {
                            $html = '<span class="text-danger font-weight-bold">Ditolak</span><br><small><p style="line-height:1rem">Notes:<br>' . nl2br($tor->catatan) . '</small></p>';
                        } else {
                            $html = '<div id="konf' . $tor->id . '"><button class="btn btn-danger btn-xs" title="Tolak" id="reject" data-toggle="modal" data-target="#modal" data-param="reject" data-grid="' . $tor->id . '"><i class="fas fa-times" ></i></button>
                    <button class="btn btn-primary btn-xs" title="Terima" id="accept" data-toggle="modal" data-target="#modal" data-param="accept" data-grid="' . $tor->id . '"><i class="fas fa-check"></i></button></div>
                        ';
                        }
                    }
                    return $html;
                })
                ->addColumn('action', function (Tor $tor) {
                    $actionBtn = '<a href="' . url("/tor/potensi/print/" . $tor->id . "") . '" target="_blank" class="print btn btn-primary btn-xs"><i class="fas fa-print fa-sm" title="Print"></i></a>';

                    if (auth()->user()->role == 'admin') {
                        $actionBtn .= '
                <a href="' . url("/tor/potensi/edit/" . $tor->id . "") . '" class="edit btn btn-primary btn-xs"><i class="fas fa-edit fa-sm" title="Edit"></i></a> 
                
                <a href="javascript:void(0)" class="delete btn btn-danger btn-xs" title="Hapus" data-toggle="modal" data-target="#del' . $tor->id . '"><i class="fas fa-trash fa-sm"></i></a>
                    <div class="modal fade" id="del' . $tor->id . '">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-body text-left pb-0">
                                <h4>Hapus data</h4>
                                    <p>Data yang dihapus tidak bisa dipulihkan kembali</p>
                                </div>
                                <div class="modal-footer pt-0 border-0 justify-content-end">
                                    <form action="' . url("/tor/potensi/delete/" . $tor->id . "") . '" method="post">
                                        <input type="hidden" name="_method" value="DELETE">
                                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                                        <a href="javascript:void(0)" class="btn mr-2" data-dismiss="modal">Kembali</a>
                                        <button class="btn btn-danger">Hapus</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    ';
                    }

                    if (auth()->user()->role == 'dosen') {
                        $actionBtn = '';
                    }

                    return $actionBtn;
                })
                ->rawColumns(['judul', 'konfirmasi', 'action'])
                ->make(true);
        }
    }

    public function potensiKonfirmasi(Request $request)
    {

        $id = $request->id;
        $notif = 'Meyetujui TOR Anda';
        $catatan = null;
        $konfirmasi = 'Diterima';
        $status = '<span class="text-primary font-weight-bold">Diterima</span>';

        if ($request->params == 'reject') {
            $notif = 'Menolak TOR Anda';
            $catatan = $request->catatan;
            $konfirmasi = 'Ditolak';
            $status = '<span class="text-danger font-weight-bold">Ditolak</span><br><small><p style="line-height:1rem">Notes:<br>' . nl2br($catatan) . '</small></p>';
        }

        Tor::find($id)->update([
            'konfirmasi' => $konfirmasi,
            'catatan' => $catatan,
        ]);

        $tor = Tor::find($id);
        $receiver = User::where('username', $tor->mahasiswa->nim)->first();

        $this->notificationStore($receiver->id, null, auth()->id(), $notif);

        $data = [
            'status' => $status
        ];


        return response()->json($data);
    }

    public function potensiForm(Request $request)
    {
        return view('pages.portal.tor.potensi.form', [
            'breadcrumb' => [
                'Home' => '/',
                'Tor' => '/',
                'Potensi' => '/tor/potensi',
                'Form Tambah' => '/'
            ],
            'activeMenu' => $this->activeMenuTorPotensi,
            'mahasiswas' => $this->getMhsCombo(),
            'kelass' => $this->getKelasCombo(),
            'prodis' => $this->getProdiCombo(),
            'dosens' => $this->getDosenCombo(),

        ]);
    }

    public function potensiStore(Request $request, Tor $tor)
    {
        $rules = [
            'mahasiswa_id' => 'required|numeric|unique:tors,mahasiswa_id,NULL,id,periode,' . session('periode_tor') . '',
            'kelas' => 'required',
            'prodi_id' => 'required|numeric',
            'pembimbing_1' => 'nullable',
            'pembimbing_2' => 'nullable',
        ];

        $dataValidated = $request->validate($rules);
        $dataValidated['periode'] = session('periode_tor');

        Tor::create($dataValidated);
        $mhs = Mahasiswa::find($dataValidated['mahasiswa_id']);
        // Aktivasi juga userlogin
        User::where('username', '' . $mhs->nim . '')->update([
            'access'    => 1,
        ]);
        return redirect('/tor/potensi')->with('success', 'Data berhasil disimpan');
    }

    public function potensiPrint($id)
    {
        if (auth()->user()->role == 'mahasiswa') {
            $id = Crypt::decrypt($id);
        }
        $data = [];
        $tor = Tor::where('tors.id', $id)
            ->leftjoin('mahasiswas as m', 'm.id', 'tors.mahasiswa_id')
            ->leftJoin('prodis as p', 'p.id', 'tors.prodi_id')
            ->leftJoin('dosens as pbb1', 'pbb1.id', 'tors.pembimbing_1')
            ->leftJoin('dosens as pbb2', 'pbb2.id', 'tors.pembimbing_2')
            ->selectRaw('
        tors.*,
        m.nim,
        m.nama,
        p.kode as kodeprodi,
        p.prodi as prodi,
        p.jurusan as jurusan,
        pbb1.kode as kodepbb1,
        pbb1.nama as pbb1,
        pbb2.kode as kodepbb2,
        pbb2.nama as pbb2')
            ->first();

        $kabagAdak = Pejabat::where('kode', 'kabag')
            ->where('bagian', 'adak')->first();

        $kajur = Pejabat::where('kode', 'kajur')
            ->where('bagian', $tor->jurusan)->first();

        $kaprodi = Pejabat::where('kode', 'kaprodi')
            ->where('bagian', $tor->kodeprodi)->first();

        $data = [
            'data' => $tor,
            'kabagAdak' => $kabagAdak,
            'kajur' => $kajur,
            'kaprodi' => $kaprodi,
            'tgl' => 'Bandung, ' . Carbon::parse(date('d M Y'))->translatedFormat('d F Y')
        ];

        $pdf = PDF::loadView('pages.portal.tor.potensi.cetak', $data);
        $fileName =  'TOR-' . $tor->nim . '-' . $tor->nama . '.pdf';
        return $pdf->stream($fileName);
    }

    public function potensiEdit($id)
    {
        return view('pages.portal.tor.potensi.form', [
            'breadcrumb' => [
                'Home' => '/',
                'Tor' => '/',
                'Potensi' => '/tor/potensi',
                'Form Edit' => '/'
            ],
            'activeMenu' => $this->activeMenuTorPotensi,
            'data' => Tor::find($id),
            'id' => $id,
            'mahasiswas' => $this->getMhsCombo(),
            'kelass' => $this->getKelasCombo(),
            'prodis' => $this->getProdiCombo(),
            'dosens' => $this->getDosenCombo(),


        ]);
    }

    public function potensiUpdate(Request $request)
    {
        $rules = [
            'kelas' => 'required',
            'prodi_id' => 'required|numeric',
            'pembimbing_1' => 'nullable',
            'pembimbing_2' => 'nullable',
        ];


        $dataValidated = $request->validate($rules);

        Tor::find($request->id)
            ->update($dataValidated);


        return redirect('/tor/potensi')->with('success', 'Data berhasil disimpan');
    }

    public function potensiDestroy($id)
    {
        $tor = Tor::find($id);
        $mhs = Mahasiswa::find($tor->mahasiswa_id);
        // Nonaktif juga userlogin
        User::where('username', '' . $mhs->nim . '')->update([
            'access'    => 0,
        ]);
        Tor::destroy($id);
        return redirect('/tor/potensi')->with('success', 'Data berhasil dihapus');
    }

    function potensiTemplate(Request $request)
    {
        return Excel::download(new TemplateTorPotensi, 'Tor-Template-Potensi.xlsx');
    }

    function potensiImport(Request $request)
    {
        $import = new TorPotensiImport;
        Excel::import($import, $request->file('file'));
        if ($import->getSuccessRowCount() == 0) {

            return back()->with('warning', '
            Silahkan lengkapi dahulu data master berikut
            <br>
            <dl class="row mb-0">
                <dt class="col-1 font-weight-normal">Mahasiswa</dt>
                <dd class="col-11 mb-0">: ' . $import->getMissingNim() . '</dd>
            </dl>
            <dl class="row mb-0">
                <dt class="col-1 font-weight-normal">Prodi</dt>
                <dd class="col-11">: ' . $import->getMissingProdi() . '</dd>
            </dl>');
        }

        return back()->with('success', $import->getSuccessRowCount() . ' dari ' . $import->getRowCount() . ' data berhasil disimpan');
    }

    function potensiExport($params)
    {
        $params = explode('/', $params);
        $periode = $params[0];
        $prodi = '';
        $kelas = '';
        $konfirmasi = '';

        if (!empty($params[1]))
            $prodi = $params[1];

        if (!empty($params[2]))
            $kelas = $params[2];

        if (!empty($params[3]))
            $konfirmasi = $params[3];

        return Excel::download(new TorPotensiExport($periode, $prodi, $kelas, $konfirmasi), 'Tor-Data-Potensi-' . date('Ymd') . '.xlsx');
    }

    // Pengajuan TOR
    public function pengajuan(Request $request)
    {
        $data = Tor::where('m.nim', auth()->user()->username)
            ->leftjoin('mahasiswas as m', 'm.id', 'tors.mahasiswa_id')
            ->leftJoin('prodis as p', 'p.id', 'tors.prodi_id')
            ->leftJoin('dosens as pbb1', 'pbb1.id', 'tors.pembimbing_1')
            ->leftJoin('dosens as pbb2', 'pbb2.id', 'tors.pembimbing_2')
            ->leftJoin('forms as f', 'f.id', 'tors.form_id')
            ->selectRaw('
            tors.*,
            m.nim,
            m.nama,
            p.kode as kodeprodi,
            p.prodi as prodi,
            p.id as prodi_id,
            p.jurusan as jurusan,
            pbb1.kode as kodepbb1,
            pbb1.nama as pbb1,
            pbb2.kode as kodepbb2,
            pbb2.nama as pbb2,
            f.nama as namaform')
            ->orderBy('tors.updated_at', 'desc')
            ->first();

        return view('pages.portal.tor.pengajuan.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Tor' => '/',
                'Pengajuan' => '/'
            ],
            'activeMenu' => $this->activeMenuTorPengajuan,
            'data' => $data,
            'forms' => $this->getFormProdiCombo(' AND prodi_id = "' . $data->prodi_id . '"'),

        ]);
    }

    public function pengajuanStore(Request $request)
    {
        $rules = [
            'latar_belakang' => 'required|min:10',
            'tujuan' => 'required|min:10',
            'form_id' => 'required|numeric|min:1',
            'topik' => 'required|min:3',
            'judul' => 'required|min:3',
            'lokus' => 'required|min:3',
        ];

        $dataValidated = $request->validate($rules);
        $dataValidated['konfirmasi'] = 'Menunggu Konfirmasi';

        $mhs = Mahasiswa::where('nim', auth()->user()->username)->first();
        Tor::where('mahasiswa_id', '' . $mhs->id . '')->update($dataValidated);

        $this->notificationStore(0, 'admin', auth()->id(), 'Memperbaharui TOR');

        return redirect('/tor/pengajuan')->with('success', 'Data berhasil disimpan');
    }

    // Nilai UP
    public function nilai()
    {
        return view('pages.portal.tor.nilai.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Tor' => '/',
                'Nilai UP' => '/'
            ],
            'activeMenu' => $this->activeMenuTorNilai,
            'prodis' => $this->getProdiCombo(),
            'kelass' =>  $this->getKelasCombo(),
            'periodes' => $this->getPeriodeTorCombo(),

        ]);
    }


    public function nilaiList(Request $request)
    {
        if ($request->ajax()) {

            $where = '';

            if (!empty($request->periode)) {
                $where .= ' AND tors.periode ="' . $request->periode . '"';
            }

            if (!empty($request->prodi)) {
                $where .= ' AND tors.prodi_id LIKE "%' . $request->prodi . '%"';
            }

            if (!empty($request->kelas)) {
                $where .= ' AND tors.kelas LIKE "%' . $request->kelas . '%"';
            }

            if (!empty($request->status)) {
                $where .= ' AND tors.status LIKE "%' . $request->status . '%"';
            }

            if (auth()->user()->role == 'dosen') {
                $ids = Dosen::where('kode', auth()->user()->username)->first();
                $where .= ' AND (tors.pembimbing_1 = ' . $ids->id . ' OR tors.pembimbing_2 = ' . $ids->id . ')';
            }

            $data = Tor::query()
                ->leftjoin('mahasiswas as m', 'm.id', 'tors.mahasiswa_id')
                ->leftJoin('prodis as p', 'p.id', 'tors.prodi_id')
                ->selectRaw('
            tors.*,
            m.nim,
            m.nama,
            p.kode as kodeprodi,
            p.prodi as prodi,
            p.jurusan as jurusan
            ')
                ->where('tors.konfirmasi', 'Diterima')
                ->whereRaw('1 ' . $where)
                ->orderBy('tors.updated_at', 'desc');

            return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('nilai', function (Tor $tor) {
                    $html = '';
                    if ($tor->nilai === null) {
                        $html = '-';
                    } else {
                        $html =  number_format($tor->nilai, 2, '.', '');
                    }

                    return $html;
                })
                ->editColumn('status', function (Tor $tor) {
                    $html = '';
                    if ($tor->status == 'TDK LULUS') {
                        $html =  '<span class="text-danger font-weight-bold">TDK LULUS</span>';
                    } else if ($tor->status == 'LULUS') {
                        $html =  '<span class="text-primary font-weight-bold">LULUS</span>';
                    } else {
                        $html = '-';
                    }

                    return $html;
                })
                ->addColumn('action', function (Tor $tor) {
                    $actionBtn = '-';
                    if (auth()->user()->role == 'admin') {
                        if ($tor->periode == session('periode_tor')) {
                            $actionBtn = '
                <a href="javascript:void(0)" data-toggle="modal" data-target="#modal" data-id="' . $tor->id . '" data-nilai="' . number_format($tor->nilai, 2, '.', ',') . '" data-status="' . $tor->status . '" class="edit btn btn-primary btn-xs"><i class="fas fa-edit fa-sm" title="Edit"></i></a>
                    ';
                        }
                    }
                    return $actionBtn;
                })
                ->rawColumns(['nilai', 'status', 'action'])
                ->make(true);
        }
    }

    public function nilaiMhs(Request $request)
    {
        return view('pages.portal.tor.nilai.nilaimhs', [
            'breadcrumb' => [
                'Home' => '/',
                'Tor' => '/',
                'Nilai UP' => '/'
            ],
            'activeMenu' => $this->activeMenuTorNilai,
            'data' => Mahasiswa::where('nim', auth()->user()->username)->first()

        ]);
    }

    public function nilaiUpdate(Request $request)
    {
        $rules = [
            'nilai' => 'required|numeric',
            'status' => 'required',
        ];


        $dataValidated = $request->validate($rules);

        Tor::find($request->id)->update($dataValidated);

        $tor = Tor::find($request->id);

        $receiver = User::where('username', $tor->mahasiswa->nim)->first();

        $this->notificationStore($receiver->id, null, auth()->id(), 'Memperbaharui Nilai UP Anda');

        return back()->with('success', 'Data berhasil disimpan');
    }

    function nilaiTemplate(Request $request)
    {
        return Excel::download(new TemplateNilaiUP, 'UP-Template-Nilai.xlsx');
    }

    function nilaiImport(Request $request)
    {
        $import = new NilaiUPImport;
        Excel::import($import, $request->file('file'));

        return back()->with('success', $import->getSuccessRowCount() . ' dari ' . $import->getRowCount() . ' data berhasil disimpan');
    }

    function nilaiExport($params)
    {
        $params = explode('/', $params);
        $periode = $params[0];
        $prodi = '';
        $kelas = '';
        $status = '';

        if (!empty($params[1]))
            $prodi = $params[1];

        if (!empty($params[2]))
            $kelas = $params[2];

        if (!empty($params[3]))
            $status = $params[3];

        return Excel::download(new NilaiUPExport($periode, $prodi, $kelas, $status), 'UP-Data-Nilai-' . date('Ymd') . '.xlsx');
    }

    // Grafik
    public function grafik(Request $request)
    {
        $data = [];
        $kategori = [];
        $potensi = [];
        $blmNilai = [];
        $lulus = [];
        $tdkLulus = [];
        $tdkmengajukan = [];

        $where = '1';

        if (auth()->user()->role == 'admin prodi' || auth()->user()->role == 'kaprodi') {
            $where .= ' AND id = ' . auth()->user()->position;
        }

        $prodis = Prodi::query()
            ->whereRaw($where)
            ->get();

        foreach ($prodis as $prodi) {

            $tor = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->count();

            $nunggu = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Menunggu Konfirmasi')
                ->count();

            $terima = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Diterima')
                ->count();

            $tolak = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Ditolak')
                ->count();

            $tdk = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->whereNull('konfirmasi')
                ->count();

            $kategori[] = $prodi->kode;
            $potensi[] = $tor;
            $blmNilai[] = $nunggu;
            $lulus[] = $terima;
            $tdkLulus[] = $tolak;
            $tdkmengajukan[] = $tdk;
        }

        $data[] = [
            "name" => "Potensi",
            "data" => $potensi
        ];

        $data[] = [
            "name" => "Menunggu",
            "data" => $blmNilai
        ];

        $data[] = [
            "name" => "Diterima",
            "data" => $lulus
        ];

        $data[] = [
            "name" => "Ditolak",
            "data" => $tdkLulus
        ];

        $data[] = [
            "name" => "Tdk mengajukan",
            "data" => $tdkmengajukan
        ];

        $datax = [];
        $datax = [
            "kategori" => $kategori,
            "series" => $data
        ];
        /*  $tor = Tor::where('status', 'LULUS')
            ->groupBy('prodi_id')
            ->get(); */

        return response()->json($datax);
    }

    public function grafikUp(Request $request)
    {
        $data = [];
        $kategori = [];
        $potensi = [];
        $blmNilai = [];
        $lulus = [];
        $tdkLulus = [];

        $where = '1';

        if (auth()->user()->role == 'admin prodi' || auth()->user()->role == 'kaprodi') {
            $where .= ' AND id = ' . auth()->user()->position;
        }

        $prodis = Prodi::query()
            ->whereRaw($where)
            ->get();

        foreach ($prodis as $prodi) {

            $tor = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Diterima')
                ->count();

            $blm = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Diterima')
                ->whereNull('status')
                ->count();

            $lls = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Diterima')
                ->where('status', 'LULUS')
                ->count();

            $tdk = Tor::where('prodi_id', $prodi->id)
                ->where('periode', $request->periodetor)
                ->where('konfirmasi', 'Diterima')
                ->where('status', 'TDK LULUS')
                ->count();

            $kategori[] = $prodi->kode;
            $potensi[] = $tor;
            $blmNilai[] = $blm;
            $lulus[] = $lls;
            $tdkLulus[] = $tdk;
        }

        $data[] = [
            "name" => "Potensi",
            "data" => $potensi
        ];

        $data[] = [
            "name" => "Blm dinilai",
            "data" => $blmNilai
        ];

        $data[] = [
            "name" => "Lulus",
            "data" => $lulus
        ];

        $data[] = [
            "name" => "Tdk Lulus",
            "data" => $tdkLulus
        ];

        $datax = [];
        $datax = [
            "kategori" => $kategori,
            "series" => $data
        ];

        return response()->json($datax);
    }
}
