<?php

namespace App\Http\Controllers;

use App\Models\Dosen;
use App\Models\Jadwal;
use App\Models\Sidang;
use App\Models\Mahasiswa;
use App\Models\Formdetail;
use App\Models\SidangNilai;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Exports\JadwalExport;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\Facades\DataTables;

class JadwalController extends Controller
{
    private $activeMenu = 'Home/Sidang/Jadwal';

    // Admin
    public function index()
    {
        return view('pages.portal.jadwal.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Jadwal' => '/jadwal'
            ],
            'activeMenu' => $this->activeMenu,
            'prodis' => $this->getProdiCombo(),
            'kelass' =>  $this->getKelasCombo(),
            'periodes' => $this->getPeriodeSidangCombo(),
            'bulans' => $this->getBulanSidangCombo(),
        ]);
    }

    public function list(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->hari)) {
                $where .= ' AND j.hari LIKE "%' . $request->hari . '%"';
            }

            if (auth()->user()->role == 'dosen') {
                $dsn = Dosen::where('kode', auth()->user()->username)->first();
                $where .= ' AND (j.penguji_1 = ' . $dsn->id . ' OR j.penguji_2 = ' . $dsn->id . ' OR j.pimpinan = ' . $dsn->id . ')';
            }

            $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,
                    j.bentrok_penguji_1,
                    j.bentrok_penguji_2,
                    j.bentrok_pimpinan,
                    t.kelas,
                    m.nim,
                    m.nama,
                    p.kode as kodeprodi,
                    p.prodi as prodi
                ')
                ->whereNotNull('clcard_status')
                ->whereRaw('1 ' . $where)
                ->orderBy('t.prodi_id')
                ->orderBy('t.kelas')
                ->orderBy('m.nim');

            return DataTables::of($data)
                ->addIndexColumn()
                ->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;
                })
                ->editColumn('penguji_1', function (Sidang $sidang) {
                    $html = '-';
                    if (!empty($sidang->penguji_1)) {
                        $dsn = Dosen::find($sidang->penguji_1);
                        $html = '';
                        $html .= $dsn->kode;
                        if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak') {
                            $html .= '<a href="javascript:void(0)" data-toggle="modal" 
                            data-jid="' . $sidang->jid . '"
                            data-sid="' . $sidang->id . '"
                            data-pid="' . $sidang->jadwal->penguji_1 . '"
                            data-target="#modal-nilai"  
                            data-penilai="penguji_1"
                            class="isi-nilai" ><i class="ml-1 fas fa-edit fa-sm" title="isi nilai"></i></a>';
                        }

                        $html .= '<a href="' . url("/sidang/nilai/print/" . $sidang->id . "/pji1/" . $sidang->jadwal->penguji_1) . '"  target="_blank"><i class="ml-1 fas fa-print fa-sm text-secondary" title="Print"></i></a>';


                        if ($sidang->bentrok_penguji_1 == 1) {
                            $html .= '<i title="Bentrok" class="fas fa-info-circle fa-sm text-danger ml-1"></i>';
                        }
                    }
                    return $html;
                })
                ->editColumn('penguji_2', function (Sidang $sidang) {
                    $html = '-';

                    if (!empty($sidang->penguji_1)) {
                        $dsn = Dosen::find($sidang->penguji_2);
                        $html = '';

                        $html .= $dsn->kode;
                        if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak') {
                            $html .= '<a href="javascript:void(0)" data-toggle="modal" 
                            data-jid="' . $sidang->jid . '"
                            data-sid="' . $sidang->id . '"
                            data-pid="' . $sidang->jadwal->penguji_2 . '"
                            data-target="#modal-nilai"  
                            data-penilai="penguji_2"
                            class="isi-nilai" ><i class="ml-1 fas fa-edit fa-sm" title="isi nilai"></i></a>';
                        }

                        $html .= '<a href="' . url("/sidang/nilai/print/" . $sidang->id . "/pji2/" . $sidang->jadwal->penguji_2) . '" target="_blank"><i class="ml-1 fas fa-print fa-sm text-secondary" title="Print"></i></a>';


                        if ($sidang->bentrok_penguji_2 == 1) {
                            $html .= '<i title="Bentrok" class="fas fa-info-circle fa-sm text-danger ml-1"></i>';
                        }
                    }
                    return $html;
                })
                ->editColumn('pimpinan', function (Sidang $sidang) {
                    $html = '-';
                    if ($sidang->pimpinan != '' || $sidang->pimpinan != null) {
                        $dsn = Dosen::find($sidang->pimpinan);
                        $html = '';

                        $html .= $dsn->kode;

                        $html .= '<a href="javascript:void(0)" data-toggle="modal" 
                        data-jid="' . $sidang->jid . '"
                        data-sid="' . $sidang->id . '"
                        data-pid="' . $sidang->jadwal->pimpinan . '"
                        data-ctt="' . $sidang->sidang_ctt_ppm . '"
                        data-form="' . $sidang->tor->form->nama . '"
                        data-target="#modal-catatan"  
                        class="isi-catatan" ><i class="ml-1 fas fa-edit fa-sm" title="isi catatan"></i></a>';

                        if ($sidang->bentrok_pimpinan == 1) {
                            $html .= '<i title="Bentrok" class="fas fa-info-circle fa-sm text-danger mr-1"></i>';
                        }
                    }
                    return $html;
                })
                ->editColumn('hari', function (Sidang $sidang) {
                    $html = '-';
                    if ($sidang->hari != '' || $sidang->hari != null) {
                        $html = $sidang->hari;
                    }
                    return $html;
                })
                ->editColumn('jam', function (Sidang $sidang) {
                    $html = '-';
                    if ($sidang->jam_awal != '' && $sidang->jam_akhir != '') {
                        $html = '<p class="mb-n3" style="line-height:1.1em">' . Carbon::parse($sidang->jam_awal)->format('H:i') . ' - ' . Carbon::parse($sidang->jam_akhir)->format('H:i') . '<br><small>R. ' . $sidang->ruang . '</small><p>';
                    }
                    return $html;
                })
                ->addColumn('edit', function (Sidang $sidang, Request $req) {
                    $html = '-';
                    if (session('periode_sidang') == $req->periode && session('bulan_sidang') == $req->bulan) {
                        if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak') {
                            $html = '<a href="javascript:void(0)" data-target="#modal-edit" data-toggle="modal" class="btn btn-xs btn-primary edit-jadwal" data-jid="' . $sidang->jid . '" data-sid="' . $sidang->id . '" data-nim="' . $sidang->mahasiswa->nim . '" data-nama="' . $sidang->mahasiswa->nama . '"><i class="fas fa-edit fa-sm"></i></a>';
                        } elseif (auth()->user()->role == 'dosen') {

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

                            $html = '';

                            if ($sidang->penguji_1 == $dsn->id || $sidang->penguji_2 == $dsn->id) {

                                $penguji = 'penguji_1';
                                $pji = 'pji1';

                                if ($sidang->penguji_2 == $dsn->id) {
                                    $penguji = 'penguji_2';
                                    $pji = 'pji2';
                                }

                                $html .= '<a href="javascript:void(0)" data-toggle="modal" 
                                data-jid="' . $sidang->jid . '"
                                data-sid="' . $sidang->id . '"
                                data-pid="' . $dsn->id . '"
                                data-target="#modal-nilai"  
                                data-penilai="' . $penguji . '"
                                class="isi-nilai" >Nilai</a>';

                                $html .= '<a href="' . url("/sidang/nilai/print/" . $sidang->id . "/" . $pji . "/" . $dsn->id) . '" target="_blank"><i class="ml-1 fas fa-print fa-sm text-secondary" title="Print"></i></a> |';
                            }

                            if ($sidang->pimpinan == $dsn->id) {

                                $html .= '<a href="javascript:void(0)" data-toggle="modal" 
                                data-jid="' . $sidang->jid . '"
                                data-sid="' . $sidang->id . '"
                                data-pid="' . $dsn->id . '"
                                data-ctt="' . $sidang->sidang_ctt_ppm . '"
                                data-form="' . $sidang->tor->form->nama . '"
                                data-target="#modal-catatan"  
                                class="isi-catatan ml-1" >Catatan</a> |';
                            }

                            // $html = Str::beforeLast($html, ' |');
                        } else {
                            $html = '';
                        }

                        $html .= '<a href="' . url("/sidang/beritaacara/print/" . $sidang->id) . '" target="_blank" class="ml-1 btn btn-xs btn-primary" title="Berita acara"><i class="fas fa-print fa-sm"></i></a>';
                    }
                    return $html;
                })
                ->addColumn('sebagai', function (Sidang $sidang, Request $req) {
                    $html = '';
                    if (auth()->user()->role == 'dosen') {
                        $dsn = Dosen::where('kode', auth()->user()->username)->first();

                        $html = '';
                        if ($sidang->penguji_1 == $dsn->id) {
                            $html .= 'Penguji 1, ';
                        }

                        if ($sidang->penguji_2 == $dsn->id) {
                            $html .= 'Penguji 2, ';
                        }

                        if ($sidang->pimpinan == $dsn->id) {
                            $html .= 'Pimpinan, ';
                        }

                        $html = Str::beforeLast($html, ', ');
                    }
                    return $html;
                })
                ->rawColumns(['nama', 'penguji_1', 'penguji_2', 'pimpinan', 'hari', 'jam', 'edit', 'sebagai'])
                ->make(true);
        }
    }

    public function cekjadwal(Request $request)
    {
        $data = [
            'status' => 'Data tidak terkirim ke server'
        ];

        if ($request->ajax()) {
            // Cek ke tabel jadwal
            $jadwal = Jadwal::where('sidang_id', $request->sid)->first();
            if (!$jadwal) {
                $jadwal['hari'] = '';
                $jadwal['penguji_1'] = '';
                $jadwal['penguji_2'] = '';
                $jadwal['pimpinan'] = '';
                $jadwal['jam_awal'] = '';
                $jadwal['jam_akhir'] = '';
                $jadwal['ruang'] = '';
                $jadwal['link'] = '';
                $jadwal['passcode'] = '';
            }
            $data = [
                'status' => 'Ok',
                'row' => $jadwal,
                'haris' => $this->getHariCombo(),
                'dosens' => $this->getDosenCombo()
            ];
        }

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

    public function getDuplicate(Request $request)
    {
        $data = [
            'status' => 'Data tidak terkirim ke server'
        ];

        if ($request->ajax()) {
            $jamawal = $request->jamawal . ':00';
            $jamakhir = $request->jamakhir . ':00';

            $alert = '';
            $altPenguji1 = 0;
            $altPenguji2 = 0;
            $altPimpinan = 0;
            if ($request->penguji1 != '') {
                $jadwalPenguji1 = Jadwal::where('periode', $request->periode)
                    ->where('bulan', $request->bulan)
                    ->whereRaw('(penguji_1 = "' . $request->penguji1 . '" OR penguji_2 = "' . $request->penguji1 . '" OR pimpinan = "' . $request->penguji1 . '") AND sidang_id !=' . $request->sid . '')
                    ->where('hari', $request->hari)
                    ->where('jam_awal', '<=', $jamawal)
                    ->where('jam_akhir', '>=', $jamakhir)
                    ->count();

                if ($jadwalPenguji1 > 0) {
                    $altPenguji1 = 1;
                    $alert .= 'Penguji 1 sudah memiliki jadwal pada hari & jam tersebut<br>';
                }
            }


            if ($request->penguji2 != '') {
                $jadwalPenguji2 = Jadwal::where('periode', $request->periode)
                    ->where('bulan', $request->bulan)
                    ->whereRaw('(penguji_1 = "' . $request->penguji2 . '" OR penguji_2 = "' . $request->penguji2 . '" OR pimpinan = "' . $request->penguji2 . '") AND sidang_id !=' . $request->sid . '')
                    ->where('hari', $request->hari)
                    ->where('jam_awal', '<=', $jamawal)
                    ->where('jam_akhir', '>=', $jamakhir)
                    ->count();

                if ($jadwalPenguji2 > 0) {
                    $altPenguji2 = 1;
                    $alert .= 'Penguji 2 sudah memiliki jadwal pada hari & jam tersebut<br>';
                }
            }

            if ($request->pimpinan != '') {
                $jadwalpimpinan = Jadwal::where('periode', $request->periode)
                    ->where('bulan', $request->bulan)
                    ->whereRaw('(penguji_1 = "' . $request->pimpinan . '" OR penguji_2 = "' . $request->pimpinan . '" OR pimpinan = "' . $request->pimpinan . '") AND sidang_id !=' . $request->sid . '')
                    ->where('hari', $request->hari)
                    ->where('jam_awal', '<=', $jamawal)
                    ->where('jam_akhir', '>=', $jamakhir)
                    ->count();

                if ($jadwalpimpinan > 0) {
                    $altPimpinan = 1;
                    $alert .= 'Pimpinan sudah memiliki jadwal pada hari & jam tersebut<br>';
                }
            }


            $data = [
                'alert' => $alert,
                'alt' => [$altPenguji1, $altPenguji2, $altPimpinan],
                'jam' => $jadwalPenguji1
            ];
        }

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

    public function store(Request $request)
    {

        // dd($data);
        if ($request->jid == '') {
            Jadwal::create([
                'periode' => $request->modalperiode,
                'bulan' => $request->modalbulan,
                'sidang_id' => $request->id,
                'pimpinan' => $request->modalpimpinan,
                'penguji_1' => $request->modalpenguji1,
                'penguji_2' => $request->modalpenguji2,
                'hari' => $request->modalhari,
                'jam_awal' => $request->jamawal . ':00',
                'jam_akhir' => $request->jamakhir . ':00',
                'ruang' => $request->modalruang,
                'link' => $request->modallink,
                'passcode' => $request->modalpasscode,
                'bentrok_penguji_1' => $request->bentrok_penguji_1,
                'bentrok_penguji_2' => $request->bentrok_penguji_2,
                'bentrok_pimpinan' => $request->bentrok_pimpinan
            ]);
        } else {
            Jadwal::find($request->jid)
                ->update([
                    'pimpinan' => $request->modalpimpinan,
                    'penguji_1' => $request->modalpenguji1,
                    'penguji_2' => $request->modalpenguji2,
                    'hari' => $request->modalhari,
                    'jam_awal' => $request->jamawal . ':00',
                    'jam_akhir' => $request->jamakhir . ':00',
                    'ruang' => $request->modalruang,
                    'link' => $request->modallink,
                    'passcode' => $request->modalpasscode,
                    'bentrok_penguji_1' => $request->bentrok_penguji_1,
                    'bentrok_penguji_2' => $request->bentrok_penguji_2,
                    'bentrok_pimpinan' => $request->bentrok_pimpinan
                ]);
        }
        return back()->with('success', 'Data berhasil disimpan');
    }

    public function getformnilai(Request $request)
    {
        $data = [
            'status' => 'Data tidak terkirim ke server'
        ];

        if ($request->ajax()) {
            $sidang = Sidang::find($request->sid);

            $table = '';

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

            $totbxn = $sidang->sidang_bxn_pji1;
            $fntotal = $sidang->sidang_nilai_pji1;
            $ctt = $sidang->sidang_ctt_pji1;

            if ($request->penilai == 'penguji_2') {
                $totbxn = $sidang->sidang_bxn_pji2;
                $fntotal = $sidang->sidang_nilai_pji2;
                $ctt = $sidang->sidang_ctt_pji2;
            }

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

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

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

                // Kriteria
                $table .= '<tr data-fid="' . $sidang->tor->form_id . '" data-fdid="' . $data->id . '">';

                $table .= '<td>' . $data->nourut . '</td>';

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

                $table .= '<td class="text-center bobot" style="width:10%" >' . $data->bobot . '</td>';

                $table .= '<td style="width:15%">';
                if ($data->bobot != '') {

                    $table .= '<input type="text" class="form-control form-control-sm input-nilai" id="' . $data->id . '" value="' . ((!empty($nil->nilai)) ? number_format($nil->nilai, 2, '.') : '') . '">';
                }

                $table .= '</td>';

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

                $table .= '</tr>';

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

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

                    $table .= '<tr data-fid="' . $sidang->tor->form_id . '" data-fdid="' . $sub->id . '">';

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

                    $table .= '<td class="pl-4">' . $sub->deskripsi . '</td>';

                    $table .= '<td class="text-center bobot" style="width:10%">' . $sub->bobot . '</td>';

                    $table .= '<td style="width:15%">';
                    if ($sub->bobot != '') {

                        $table .= '<input type="text" class="form-control form-control-sm input-nilai" id="' . $sub->id . '" value="' . ((!empty($nil->nilai)) ? number_format($nil->nilai, 2, '.') : '') . '">';
                    }

                    $table .= '</td>';

                    $table .= '<td class="bxn">' . ((!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">' . ((!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">' . ((!empty($fntotal)) ? number_format($fntotal, 2, '.') : '') . '</td>';

            $table .= '</tr>';

            // Feedback
            $data = [
                'status' => 'Ok',
                'form' => $sidang->tor->form->nama,
                'table' => $table,
                'ctt' => $ctt,
            ];
        }

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

    public function catatanStore(Request $request)
    {
        Sidang::find($request->sid)->update([
            'sidang_ctt_ppm' => $request->ctt_ppm
        ]);

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

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

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

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

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

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

        return Excel::download(new JadwalExport($periode, $bulan, $prodi, $kelas, $hari, $status), 'Jadwal-Sidang-' . date('Ymd') . '.xlsx');
    }

    // Mahasiswa
    public function jadwalmahasiswa()
    {
        $mhs = Mahasiswa::where('nim', auth()->user()->username)->first();
        return view('pages.portal.jadwal.jadwalmhs', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Jadwal' => '/jadwal'
            ],
            'activeMenu' => $this->activeMenu,
            'data' => Sidang::where('mahasiswa_id', $mhs->id)->first()
        ]);
    }
}
