<?php

namespace App\Http\Controllers;

use PDF;
use App\Models\Tor;
use App\Models\User;
use App\Models\Dosen;
use App\Models\Prodi;
use App\Models\Sidang;
use App\Models\Pejabat;
use App\Models\Formdetail;
use App\Models\SidangNilai;
use Illuminate\Support\Str;
use App\Exports\NilaiExport;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Exports\SidangPotensiExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\Facades\DataTables;

class SidangController extends Controller
{
    private $activeMenuSidangPotensi = 'Home/Sidang/Potensi';
    private $activeMenuSidangNilai = 'Home/Sidang/Nilai';

    // Sidang
    public function potensi(Request $request)
    {
        return view('pages.portal.sidang.potensi.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Potensi' => '/'
            ],
            'activeMenu' => $this->activeMenuSidangPotensi,
            'prodis' => $this->getProdiCombo(),
            'kelass' =>  $this->getKelasCombo(),
            'periodes' => $this->getPeriodeSidangCombo(),
            'tors' => $this->getPeriodeTorCombo(),
            'bulans' => $this->getBulanSidangCombo(),
        ]);
    }

    public function generate(Request $request)
    {
        $periode_tor = $request->periodeTor;

        $tors = Tor::where('periode', $periode_tor)->get();

        foreach ($tors as $tor) {

            $cek = Sidang::where('tor_id', $tor->id)
                ->where('periode', session('periode_sidang'))
                ->where('bulan', session('bulan_sidang'))
                ->first();

            if (!$cek) {
                Sidang::create([
                    'periode' => session('periode_sidang'),
                    'bulan' => session('bulan_sidang'),
                    'mahasiswa_id' => $tor->mahasiswa_id,
                    'tor_id' => $tor->id,
                    'pbb1_net' => $tor->pembimbing_1,
                    'pbb2_net' => $tor->pembimbing_2,
                    'judul_net' => $tor->judul,
                ]);

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

                $this->notificationStore($receiver->id, null, auth()->id(), 'Menu bimbingan Anda telah diaktifkan');
            } else {
                Sidang::where('tor_id', $tor->id)->update([
                    'pbb1_net' => $tor->pembimbing_1,
                    'pbb2_net' => $tor->pembimbing_2,
                    'judul_net' => $tor->judul,
                ]);
            }
        }

        $data = [
            'msg' => 'Data berhasil di generate'
        ];

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

    public function potensiList(Request $request)
    {
        if ($request->ajax()) {
            $where = '';

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

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

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

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

            if (isset($request->param)) {
                if ($request->param == 'bimbingan') {
                    if ($request->selesai == 'Selesai') {
                        $where .= ' AND sidangs.sls_pbb1 ="Selesai" AND sidangs.sls_pbb2 ="Selesai"';
                    } else if ($request->selesai == 'Blm selesai') {
                        $where .= ' AND sidangs.sls_pbb1 IS NULL OR sidangs.sls_pbb2 IS NULL';
                    }
                }
            }

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

            $data = Sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->leftJoin('mahasiswas as m', 'm.id', 't.mahasiswa_id')
                ->leftJoin('prodis as p', 'p.id', 't.prodi_id')
                ->leftJoin('dosens as pbb1', 'pbb1.id', 'sidangs.pbb1_net')
                ->leftJoin('dosens as pbb2', 'pbb2.id', 'sidangs.pbb2_net')
                ->leftJoin('forms as f', 'f.id', 't.form_id')
                ->selectRaw('
                    sidangs.*,
                    t.kelas,
                    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('t.prodi_id')
                ->orderBy('t.kelas')
                ->orderBy('m.nim');

            return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('judul_net', function (Sidang $sidang) {
                    $html = '' . $sidang->judul_net . '<br>Form: ' . $sidang->namaform . '
                    ';
                    return $html;
                })
                ->addColumn('detail', function (Sidang $sidang) {
                    $html = '<a href="javascript:void(0)" class="detail" data-mid="' . $sidang->mahasiswa_id . '" data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" data-prodi="' . $sidang->tor->prodi->kode . '" data-kelas="' . $sidang->tor->kelas . '">Detail</a>
                    ';
                    return $html;
                })
                ->addColumn('action', function (Sidang $sidang, Request $req) {

                    $actionBtn = '-';
                    if (session('periode_sidang') == $sidang->periode && session('bulan_sidang') == $sidang->bulan) {
                        if ($req->param == 'bimbingan') {

                            $actionBtn = '';
                            if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak' || auth()->user()->role == 'dosen') {

                                $actionBtn .= '<a href="#" class="selesai btn btn-xs btn-primary" data-id="' . $sidang->id . '" data-mid="' . $sidang->mahasiswa_id . '">Selesai</a>';

                                if ($sidang->sls_pbb1 == 'Selesai' && $sidang->sls_pbb2 == 'Selesai') {
                                    $actionBtn = 'Selesai';
                                }

                                if (auth()->user()->role == 'dosen') {

                                    $idd = Dosen::where('kode', auth()->user()->username)->first();

                                    if ($idd->id == $sidang->pbb1_net && $sidang->sls_pbb1 == 'Selesai') {
                                        $actionBtn = 'Selesai';
                                    }

                                    if ($idd->id == $sidang->pbb2_net && $sidang->sls_pbb2 == 'Selesai') {
                                        $actionBtn = 'Selesai';
                                    }
                                }
                            }
                        } else {
                            if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak') {
                                $actionBtn = '
                <a href="' . url("/sidang/potensi/edit/" . $sidang->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' . $sidang->id . '"><i class="fas fa-trash fa-sm"></i></a>
                    <div class="modal fade" id="del' . $sidang->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("/sidang/potensi/delete/" . $sidang->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>
                    ';
                            }
                        }
                    }
                    return $actionBtn;
                })
                ->editColumn('nilai_pbb1', function (Sidang $sidang) {
                    $html = '';
                    if (session('periode_sidang') == $sidang->periode && session('bulan_sidang') == $sidang->bulan) {

                        if (auth()->user()->role == 'dosen') {
                            $dsn = Dosen::where('kode', auth()->user()->username)->first();
                            if ($sidang->pbb1_net == $dsn->id) {
                                if ($sidang->nilai_pbb1 === null) {
                                    $html = '<a href="javascript:void(0)" class="isi-nilai" data-sid="' . $sidang->id . '"  data-mid="' . $sidang->mahasiswa_id . '" 
                                    data-periode="' . $sidang->periode . '"  data-bulan="' . $sidang->bulan . '"  data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" 
                                    data-nilai="pbb1" data-pbb="' . $sidang->pbb1_net . '" data-prodi="' . Str::title($sidang->tor->prodi->prodi) . '" data-kelas="' . $sidang->tor->kelas . '">Isi nilai</a>';
                                } else {
                                    $html = '<a href="javascript:void(0)" class="isi-nilai" data-sid="' . $sidang->id . '"  data-mid="' . $sidang->mahasiswa_id . '" data-periode="' . $sidang->periode . '"  data-bulan="' . $sidang->bulan . '" data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" data-nilai="pbb1" data-pbb="' . $sidang->pbb1_net . '"   data-prodi="' . Str::title($sidang->tor->prodi->prodi) . '" data-kelas="' . $sidang->tor->kelas . '">' . number_format($sidang->nilai_pbb1, 2, '.') . '</a>';
                                }

                                $html .= '<a href="' . url("/bimbingan/nilai/print/" . $sidang->id . "/pbb1") . '" target="_blank"  class="print-pbb1 ml-2 text-secondary" data-id="' . $sidang->id . '"><i class="fas fa-print fa-sm"></i></a>';
                            } else {
                                $html = number_format($sidang->nilai_pbb1, 2, '.');
                                if ($sidang->nilai_pbb1 === null) {

                                    $html = 'Blm Isi';
                                }
                            }
                        } else {

                            $nilai = number_format($sidang->nilai_pbb1, 2, '.');

                            if ($sidang->nilai_pbb1 === null) {

                                $nilai = 'Blm Isi';
                            }

                            $html = '<a href="javascript:void(0)" class="isi-nilai" data-sid="' . $sidang->id . '"  data-mid="' . $sidang->mahasiswa_id . '" data-periode="' . $sidang->periode . '"  data-bulan="' . $sidang->bulan . '" data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" data-nilai="pbb1" data-pbb="' . $sidang->pbb1_net . '" data-prodi="' . Str::title($sidang->tor->prodi->prodi) . '" data-kelas="' . $sidang->tor->kelas . '">' . $nilai . '</a>';



                            $html .= '<a href="' . url("/bimbingan/nilai/print/" . $sidang->id . "/pbb1") . '" target="_blank"  class="print-pbb1 ml-2 text-secondary" data-id="' . $sidang->id . '"><i class="fas fa-print fa-sm"></i></a>';
                        }
                    }
                    return $html;
                })
                ->editColumn('nilai_pbb2', function (Sidang $sidang) {
                    $html = '';
                    if (session('periode_sidang') == $sidang->periode && session('bulan_sidang') == $sidang->bulan) {

                        if (auth()->user()->role == 'dosen') {
                            $dsn = Dosen::where('kode', auth()->user()->username)->first();
                            if ($sidang->pbb2_net == $dsn->id) {
                                if ($sidang->nilai_pbb2 === null) {
                                    $html = '<a href="javascript:void(0)" class="isi-nilai" data-sid="' . $sidang->id . '"  data-mid="' . $sidang->mahasiswa_id . '" 
                                    data-periode="' . $sidang->periode . '"  data-bulan="' . $sidang->bulan . '"  data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" 
                                    data-nilai="pbb2" data-pbb="' . $sidang->pbb2_net . '" data-prodi="' . Str::title($sidang->tor->prodi->prodi) . '" data-kelas="' . $sidang->tor->kelas . '">Isi nilai</a>';
                                } else {
                                    $html = '<a href="javascript:void(0)" class="isi-nilai" data-sid="' . $sidang->id . '"  data-mid="' . $sidang->mahasiswa_id . '" data-periode="' . $sidang->periode . '"  data-bulan="' . $sidang->bulan . '" data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" data-nilai="pbb2" data-pbb="' . $sidang->pbb2_net . '"   data-prodi="' . Str::title($sidang->tor->prodi->prodi) . '" data-kelas="' . $sidang->tor->kelas . '">' . number_format($sidang->nilai_pbb2, 2, '.') . '</a>';
                                }

                                $html .= '<a href="' . url("/bimbingan/nilai/print/" . $sidang->id . "/pbb2") . '" target="_blank"  class="print-pbb2 ml-2 text-secondary" data-id="' . $sidang->id . '"><i class="fas fa-print fa-sm"></i></a>';
                            } else {
                                $html = number_format($sidang->nilai_pbb2, 2, '.');
                                if ($sidang->nilai_pbb2 === null) {

                                    $html = 'Blm Isi';
                                }
                            }
                        } else {
                            $nilai = number_format($sidang->nilai_pbb2, 2, '.');

                            if ($sidang->nilai_pbb2 === null) {

                                $nilai = 'Blm Isi';
                            }

                            $html = '<a href="javascript:void(0)" class="isi-nilai" data-sid="' . $sidang->id . '"  data-mid="' . $sidang->mahasiswa_id . '" data-periode="' . $sidang->periode . '"  data-bulan="' . $sidang->bulan . '" data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '" data-nilai="pbb2" data-pbb="' . $sidang->pbb2_net . '" data-prodi="' . Str::title($sidang->tor->prodi->prodi) . '" data-kelas="' . $sidang->tor->kelas . '">' . $nilai . '</a>';



                            $html .= '<a href="' . url("/bimbingan/nilai/print/" . $sidang->id . "/pbb2") . '" target="_blank"  class="print-pbb2 ml-2 text-secondary" data-id="' . $sidang->id . '"><i class="fas fa-print fa-sm"></i></a>';
                        }
                    }
                    return $html;
                })
                ->addColumn('na', function (Sidang $sidang) {
                    $n_pbb1 = $sidang->nilai_pbb1;
                    if ($n_pbb1 === null)
                        $n_pbb1 = 0;

                    $n_pbb2 = $sidang->nilai_pbb2;
                    if ($n_pbb2 === null)
                        $n_pbb2 = 0;

                    $na = ($n_pbb1 + $n_pbb2) / 2;

                    $html = number_format($na, 2, '.');
                    return $html;
                })
                ->rawColumns(['judul_net', 'detail', 'nilai_pbb1', 'nilai_pbb2', 'na', 'action'])
                ->make(true);
        }
    }

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

        ]);
    }

    public function potensiStoreManual(Request $request)
    {
        if ($request->ajax()) {
            $id = $request->id;
            $tor = Tor::find($id);
            Sidang::create([
                'periode' => session('periode_sidang'),
                'bulan' => session('bulan_sidang'),
                'mahasiswa_id' => $tor->mahasiswa_id,
                'tor_id' => $tor->id,
                'pbb1_net' => $tor->pembimbing_1,
                'pbb2_net' => $tor->pembimbing_2,
                'judul_net' => $tor->judul,
            ]);

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

            $this->notificationStore($receiver->id, null, auth()->id(), 'Menu bimbingan Anda telah diaktifkan');

            $data = [
                'msg' => 'Data berhasil ditambahkan'
            ];

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

        $data = [
            'msg' => 'Data gagal ditambahkan'
        ];

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

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


        ]);
    }

    public function potensiUpdate(Request $request)
    {
        $rules = [
            'judul_net' => 'required',
            'pbb1_net' => 'nullable',
            'pbb2_net' => 'nullable',
        ];


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

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


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

    public function potensiDestroy($id)
    {
        Sidang::destroy($id);
        return redirect('/sidang/potensi')->with('success', 'Data berhasil dihapus');
    }

    function sidangPotensiExport($params)
    {
        $params = explode('/', $params);
        $periode = $params[0];
        $bulan = $params[1];
        $prodi = '';
        $kelas = '';

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

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

        /* if (!empty($params[4]))
            $kelas = $params[4]; */


        return Excel::download(new SidangPotensiExport($periode, $bulan, $prodi, $kelas), 'Sidang-Data-Potensi-' . date('Ymd') . '.xlsx');
    }

    // Penilaian
    public function nilai(Request $request)
    {
        return view('pages.portal.sidang.nilai.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Nilai' => '/'
            ],
            'activeMenu' => $this->activeMenuSidangNilai,
            'prodis' => $this->getProdiCombo(),
            'kelass' =>  $this->getKelasCombo(),
            'periodes' => $this->getPeriodeSidangCombo(),
            'tors' => $this->getPeriodeTorCombo(),
            'bulans' => $this->getBulanSidangCombo(),
        ]);
    }

    public function nilaiList(Request $request)
    {
        if ($request->ajax()) {
            $where = '';

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

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

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

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

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

            $data = Sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->leftJoin('jadwals as j', 'j.sidang_id', 'sidangs.id')
                ->leftJoin('mahasiswas as m', 'm.id', 't.mahasiswa_id')
                ->leftJoin('prodis as p', 'p.id', 't.prodi_id')
                ->selectRaw('
                    sidangs.*,
                    j.id as jid,
                    j.penguji_1,
                    j.penguji_2,
                    j.pimpinan,
                    j.hari,
                    j.jam_awal,
                    j.jam_akhir,
                    j.ruang,
                    j.link,
                    j.passcode,
                    t.kelas,
                    t.nilai as nilai_up,
                    m.nim,
                    m.nama,
                    p.kode as kodeprodi,
                    p.prodi as prodi,
                    p.jenjang
                ')
                ->whereNotNull('clcard_status')
                ->whereRaw('1 ' . $where)
                ->orderBy('t.prodi_id')
                ->orderBy('t.kelas')
                ->orderBy('m.nim');

            $datas = $data->get();
            foreach ($datas as $dt) {
                if (!empty($dt->sidang_nilai_pji1) && !empty($dt->sidang_nilai_pji2)) {
                    $na = $this->hitungNa($dt->nilai_up, $dt->nilai_pbb1, $dt->nilai_pbb2, $dt->sidang_nilai_pji1, $dt->sidang_nilai_pji2);

                    $na = number_format($na, 2, '.');

                    $index = $this->getIndex($na);
                    $konversi = $this->getKonversi($index);

                    $finalNa = 0;
                    $yudisium = '';

                    if (!empty($dt->sks) && !empty($dt->tot_bobot) && !empty($dt->tot_sks)) {
                        $finalNa = $this->getFinalNa($konversi, $dt->sks, $dt->tot_bobot, $dt->tot_sks);

                        $yudisium = $this->getYudisium($finalNa, $dt->jenjang);
                    }

                    Sidang::find($dt->id)->update([
                        'na' => $na,
                        'index' => $index,
                        'konversi' => $konversi,
                        'final_na' => $finalNa,
                        'yudisium' => $yudisium
                    ]);
                }
            }
            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function (Sidang $sidang, Request $req) {
                    $html = '-';
                    if (session('periode_sidang') == $req->periode && session('bulan_sidang') == $req->bulan) {
                        $html = '';
                        if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak') {
                            $html .= '<a href="javascript:void(0)" data-toggle="modal"
                            data-sid="' . $sidang->id . '"
                            data-sks="' . $sidang->sks . '"
                            data-tot_bobot="' . $sidang->tot_bobot . '"
                            data-tot_sks="' . $sidang->tot_sks . '"
                            data-target="#modal-nilai"  
                            class="isi-nilai" ><i class="ml-1 fas fa-edit fa-sm" title="isi nilai"></i></a>';
                        }

                        $html .= '<a href="javascript:void(0)" data-toggle="modal"
                        data-sid="' . $sidang->id . '"
                        data-sidang_ctt_ppm="' . $sidang->sidang_ctt_ppm . '"
                        data-sidang_ctt_pji1="' . $sidang->sidang_ctt_pji1 . '"
                        data-sidang_ctt_pji2="' . $sidang->sidang_ctt_pji2 . '"
                        data-target="#modal-catatan"  
                        class="detail-catatan" ><i class="ml-1 fas fa-comment fa-sm text-secondary" title="Catatan"></i></a>';

                        $html .= '<a href="' . url("/sidang/beritaacara/print/" . $sidang->id) . '" target="_blank" class="ml-1" title="Berita acara"><i class="fas fa-print fa-sm text-secondary"></i></a>';
                    }
                    return $html;
                })
                ->editColumn('nama', function (Sidang $sidang) {

                    $html = '<a href="javascript:void(0)" title="Detail" data-toggle="modal" data-target="#detail' . $sidang->id . '">' . $sidang->nama . '</a>
                    <div class="modal fade" id="detail' . $sidang->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 mb-2 p-3">
                                <h6 class="text-center text-bold">DETAIL MAHASISWA</h6> 
                                    <dl class="row mb-0">
                                        <dt class="col-3 font-weight-normal">NAMA</dt>
                                        <dd class="col-9 mb-0">' . $sidang->nama . '</dd>
                                        
                                        <dt class="col-3 font-weight-normal">NIM</dt>
                                        <dd class="col-9 mb-0">' . $sidang->nim . '</dd>
                                        
                                        <dt class="col-3 font-weight-normal">JURUSAN</dt>
                                        <dd class="col-9 mb-0">' . ucwords(strtolower($sidang->tor->prodi->jurusan)) . '</dd>
                                    
                                        <dt class="col-3 font-weight-normal">PROGRAM STUDI</dt>
                                        <dd class="col-9 mb-0">' . ucwords(strtolower($sidang->tor->prodi->prodi)) . '</dd>
                                    </dl>
                                </div>
                                
                                <div class="col-10 offset-1  mb-2 p-3">
                                        <h6 class="text-center text-bold">JUDUL & PEMBIMBING (NET)</h6>

                                        <dl class="row mb-0">
                                            <dt class="col-3 font-weight-normal">JUDUL NET</dt>
                                            <dd class="col-9 mb-0">' . ucwords(strtolower($sidang->judul_net)) . '</dd>
                                            
                                            <dt class="col-3 font-weight-normal">JENIS FORM</dt>
                                            <dd class="col-9 mb-0">' . ucwords(strtolower($sidang->tor->form->nama)) . '</dd>
                                            
                                            <dt class="col-3 font-weight-normal">PEMBIMBING 1</dt>
                                            <dd class="col-9 mb-0">' . $sidang->pbbs1->nama . '</dd>
                                            
                                            <dt class="col-3 font-weight-normal">PEMBIMBING 2</dt>
                                            <dd class="col-9 mb-0">' . $sidang->pbbs2->nama . '</dd>
                                        </dl>
                                </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('nilai_up', function (Sidang $sidang) {
                    $html = number_format($sidang->nilai_up, 2, '.');

                    return $html;
                })
                ->editColumn('nilai_pbb1', function (Sidang $sidang) {
                    $html = number_format($sidang->nilai_pbb1, 2, '.');

                    return $html;
                })
                ->editColumn('nilai_pbb2', function (Sidang $sidang) {
                    $html = number_format($sidang->nilai_pbb2, 2, '.');

                    return $html;
                })
                ->editColumn('sidang_nilai_pji1', function (Sidang $sidang) {
                    $html = number_format($sidang->sidang_nilai_pji1, 2, '.');

                    return $html;
                })
                ->editColumn('sidang_nilai_pji2', function (Sidang $sidang) {
                    $html = number_format($sidang->sidang_nilai_pji2, 2, '.');

                    return $html;
                })
                ->addColumn('na', function (Sidang $sidang) {
                    $html = number_format($sidang->na, 2, '.');
                    return $html;
                })
                ->editColumn('pimpinan', function (Sidang $sidang) {
                    $html = '-';
                    if (!empty($sidang->penguji_1)) {
                        $html = $sidang->jadwal->ppm->kode;
                    }

                    return $html;
                })
                ->rawColumns(['action', 'nama', 'nilai_up', 'nilai_pbb1', 'nilai_pbb2', 'sidang_nilai_pji1', 'sidang_nilai_pji2', 'na', 'pimpinan'])
                ->make(true);
        }
    }

    public function nilaiStore(Request $request)
    {

        $data = [
            'status' => 'Data tidak terkirim ke server'
        ];

        if ($request->ajax()) {

            $sid = $request->sid;
            $penilai = $request->penilai;
            $pid = $request->pid;
            $bxn = $request->bxn;
            $na = $request->na;
            $catatan = $request->catatan;
            $details = $request->data;

            // Cek dosen penguji 1 atau 2

            $sdg = Sidang::find($sid);
            $bxnCol = 'sidang_bxn_pji2';
            $nilaiCol = 'sidang_nilai_pji2';
            $cttCol = 'sidang_ctt_pji2';

            if ($penilai == 'penguji_1') {
                $bxnCol = 'sidang_bxn_pji1';
                $nilaiCol = 'sidang_nilai_pji1';
                $cttCol = 'sidang_ctt_pji1';
            }

            // Update nilai sidang
            $sdg->update([
                $bxnCol => $bxn,
                $nilaiCol => $na,
                $cttCol => $catatan,
            ]);

            // Loop form nilai
            foreach ($details as $detail) {

                // Cek sidang nilai
                $pjiNilai = SidangNilai::where('sidang_id', $sid)
                    ->where('penilai', $pid)
                    ->where('formdetail_id', $detail[2])
                    ->first();

                if ($pjiNilai) {
                    SidangNilai::where('sidang_id', $sid)
                        ->where('penilai', $pid)
                        ->where('formdetail_id', $detail[2])
                        ->update([
                            'nilai' => $detail[5],
                            'bxn' => $detail[6],
                        ]);
                } else {
                    SidangNilai::create([
                        'periode' => $sdg->periode,
                        'bulan' => $sdg->bulan,
                        'mahasiswa_id' => $sdg->mahasiswa_id,
                        'sidang_id' => $detail[0],
                        'form_id' => $detail[1],
                        'formdetail_id' => $detail[2],
                        'penilai' => $detail[3],
                        'bobot' => $detail[4],
                        'nilai' => $detail[5],
                        'bxn' => $detail[6]
                    ]);
                }
            }

            $data = [
                'status' => 'Data berhasil disimpan'
            ];
        }


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

    public function nllUpdate(Request $request)
    {
        $rules = [
            'sks' => 'required|numeric',
            'tot_bobot' => 'required|numeric',
            'tot_sks' => 'required|numeric',
        ];

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

        Sidang::find($request->sid)->update($dataValidated);

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

    public function nilaiPrint($sid, $pji, $pid)
    {
        $data = [];
        $sdg = Sidang::find($sid);

        $penguji = $sdg->jadwal->penguji_2;
        $pjis = $sdg->jadwal->pjis2->nama;
        $nidn = $sdg->jadwal->pjis2->nidn;
        $totbxn = $sdg->sidang_bxn_pji2;
        $totnilai = $sdg->sidang_nilai_pji2;
        $catatan = $sdg->sidang_ctt_pji2;

        if ($pji == 'pji1') {
            $penguji = $sdg->jadwal->penguji_1;
            $pjis = $sdg->jadwal->pjis1->nama;
            $nidn = $sdg->jadwal->pjis1->nidn;
            $totbxn = $sdg->sidang_bxn_pji1;
            $totnilai = $sdg->sidang_nilai_pji1;
            $catatan = $sdg->sidang_ctt_pji1;
        }

        $datas = Formdetail::where('form_id', $sdg->tor->form_id)
            ->where('jenis', 'judul')
            ->orderBy('nourut', 'asc')
            ->get();

        $table = '';

        $table .= '
        <table width="100%" class="detail">
            <thead>
                <tr>
                <th width="20" class="text-center">No</th>
                <th width="300" class="text-center">Kriteria Penilaian</th>
                <th width="30" class="text-center">Bobot</th>
                <th width="40" class="text-center">Nilai</th>
                <th width="40" class="text-center">B x N</th>
                </tr>
            </thead>
            <tbody>';


        $totBobot = 0;
        foreach ($datas as $data) {

            $totBobot = $totBobot + $data->bobot;
            $subs = Formdetail::where('parent_id', $data->nourut)
                ->where('form_id', $sdg->tor->form_id)
                ->orderBy('id', 'asc')
                ->get();

            // Cek di sidang_nilai
            $nil = SidangNilai::where('sidang_id', $sid)
                ->where('penilai', $pid)
                ->where('formdetail_id', $data->id)->first();

            // Kriteria
            $table .= '<tr>';

            $table .= '<td class="text-center">' . $data->nourut . '</td>';

            $table .= '<td class="font-weight-bold">' . $data->deskripsi . '</td>';

            $table .= '<td class="text-center bobot" >' . $data->bobot . '</td>';

            $table .= '<td class="text-center">';
            if ($data->bobot != '') {

                $table .=  ((!empty($nil->nilai)) ? number_format($nil->nilai, 2, '.') : '');
            }

            $table .= '</td>';

            $table .= '<td class="text-center">' . ((!empty($nil->bxn)) ? number_format($nil->bxn, 2, '.') : '') . '</td>';

            $table .= '</tr>';

            foreach ($subs as $sub) {
                // Cek di sidang_nilai
                $nil = SidangNilai::where('sidang_id', $sid)
                    ->where('penilai', $pid)
                    ->where('formdetail_id', $sub->id)->first();

                // Sub kriteria
                $totBobot = $totBobot + $sub->bobot;

                $table .= '<tr>';

                $table .= '<td></td>';

                $table .= '<td class="pl-4" style="width:200px">' . $sub->deskripsi . '</td>';

                $table .= '<td class="text-center bobot">' . $sub->bobot . '</td>';

                $table .= '<td class="text-center">';
                if ($sub->bobot != '') {

                    $table .= ((!empty($nil->nilai)) ? number_format($nil->nilai, 2, '.') : '');
                }

                $table .= '</td>';

                $table .= '<td class="text-center">' . ((!empty($nil->bxn)) ? number_format($nil->bxn, 2, '.') : '') . '</td>';

                $table .= '</tr>';
            }
        }

        // Total
        $table .= '<tr>';

        $table .= '<td></td>';

        $table .= '<td class="text-center font-weight-bold">TOTAL</td>';

        $table .= '<td class="text-center bobot">' . $totBobot . '</td>';

        $table .= '<td></td>';

        $table .= '<td class="totbxn text-center">' . ((!empty($totbxn)) ? number_format($totbxn, 2, '.') : '') . '</td>';

        $table .= '</tr>';

        // Nilai Akhir
        $table .= '<tr>';

        $table .= '<td></td>';

        $table .= '<td class="text-center font-weight-bold">NILAI AKHIR</td>';

        $table .= '<td class="text-center"></td>';

        $table .= '<td></td>';

        $table .= '<td class="fntotal font-weight-bold text-center">' . ((!empty($totnilai)) ? number_format($totnilai, 2, '.') : '') . '</td>';

        $table .= '</tr>';

        $table .= '</tbody></table>';

        $data = [
            'nilai' => $sdg,
            'table' => $table,
            'totbxn' => $totbxn,
            'totnilai' => $totnilai,
            'catatan' => $catatan,
            'ttd' => $pjis,
            'nidn' => $nidn,
            'tgl' => 'Bandung, ' . Carbon::parse(date('d M Y'))->translatedFormat('d F Y')
        ];

        $pdf = PDF::loadView('pages.portal.jadwal.cetak', $data)->setPaper('a4', 'portrait');
        $fileName =  'Penilaian-Ujian-Sidang-' . $sdg->mahasiswa->nim . '-' . $sdg->mahasiswa->nama . '.pdf';
        return $pdf->stream($fileName);
    }

    public function baPrint($sid)
    {
        $data = [];
        $sdg = Sidang::find($sid);
        $status = $this->cekLulus($sdg->yudisium);

        if ($status == 'LULUS') {
            $status = 'LULUS / <span style="text-decoration:line-through">TIDAK LULUS</span>';
        } else {
            $status = '<span style="text-decoration:line-through">LULUS</span> / TIDAK LULUS';
        }
        $data = [
            'data' => $sdg,
            'direktur' => Pejabat::where('kode', 'ketua')->first(),
            'puket1' => Pejabat::where('kode', 'puket1')->first(),
            'status' => $status,
            'tgl' => 'Bandung, ' . Carbon::parse(date('d M Y'))->translatedFormat('d F Y')
        ];

        $pdf = PDF::loadView('pages.portal.jadwal.bacetak', $data)->setPaper('a4', 'portrait');
        $fileName =  'Berita-Acara-' . $sdg->mahasiswa->nim . '-' . $sdg->mahasiswa->nama . '.pdf';
        return $pdf->stream($fileName);
    }

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

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

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

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


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

    // Validasi dokumen
    public function bavalidasi($id)
    {
        $id = Crypt::decrypt($id);
        $sdg = Sidang::find($id);

        return view(
            'pages.portal.sidang.validasi.index',
            [
                'data' => $sdg,
                'nim' => $sdg->mahasiswa->nim,
                'nama' => $sdg->mahasiswa->nama,
                'direktur' => Pejabat::where('kode', 'ketua')->first(),
                'status' => $this->cekLulus('Memuaskan')
            ]
        );
    }

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

        $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) {

            $sidang = sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->where('t.prodi_id', $prodi->id)
                ->where('sidangs.periode', $request->periodesidang)
                ->where('sidangs.bulan', $request->bulansidang)
                ->count();

            $pst = sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->where('t.prodi_id', $prodi->id)
                ->where('sidangs.periode', $request->periodesidang)
                ->where('sidangs.bulan', $request->bulansidang)
                ->whereNotNull('sidangs.clcard_status')
                ->count();

            $lls = sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->where('t.prodi_id', $prodi->id)
                ->where('sidangs.periode', $request->periodesidang)
                ->where('sidangs.bulan', $request->bulansidang)
                ->whereRaw('sidangs.yudisium IN ("Memuaskan","Sangat Memuaskan","Dengan Pujian")')
                ->count();

            $tdk = sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->where('t.prodi_id', $prodi->id)
                ->where('sidangs.periode', $request->periodesidang)
                ->where('sidangs.bulan', $request->bulansidang)
                ->where('sidangs.yudisium', 'Tdk Lulus')
                ->count();

            $blm = sidang::query()
                ->leftJoin('tors as t', 't.id', 'sidangs.tor_id')
                ->where('t.prodi_id', $prodi->id)
                ->where('sidangs.periode', $request->periodesidang)
                ->where('sidangs.bulan', $request->bulansidang)
                ->whereNull('sidangs.yudisium')
                ->count();


            $kategori[] = $prodi->kode;
            $potensi[] = $sidang;
            $peserta[] = $pst;
            $lulus[] = $lls;
            $tdkLulus[] = $tdk;
            $tdkNilai[] = $blm;
        }

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

        $data[] = [
            "name" => "Peserta",
            "data" => $peserta
        ];

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

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

        $data[] = [
            "name" => "Blm Dinilai",
            "data" => $tdkNilai
        ];

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

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