<?php

namespace App\Http\Controllers;

use PDF;
use DateTime;
use DateTimeZone;
use App\Models\User;
use App\Models\Dosen;
use App\Models\Sidang;
use App\Models\Bimbingan;
use App\Models\Mahasiswa;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Models\Bimbingan_nilai;
use App\Exports\BimbinganExport;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class BimbinganController extends Controller
{
    private $activeMenuMahasiswa = 'Home/Sidang/Bimbingan';

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

    public function mahasiswa()
    {
        // $mhs = Mahasiswa::where('nim', )
        return view('pages.portal.sidang.bimbingan.mahasiswa', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Bimbingan' => '/',
            ],
            'activeMenu' => $this->activeMenuMahasiswa,
            'pembimbings' => $this->getPembimbingCombo(),
            'sidang' => Sidang::where('mahasiswa_id', auth()->user()->mahasiswa->id)->orderByDesc('id')->first(),
        ]);
    }


    public function mahasiswaList(Request $request)
    {

        if ($request->ajax()) {
            $where = '1';
            $where .= ' AND periode="' . session('periode_sidang') . '" AND bulan="' . session('bulan_sidang') . '"';

            $usr = User::find(auth()->id());
            if (auth()->user()->role == 'mahasiswa') {
                $r = Mahasiswa::where('nim', $usr->username)->first();
                $where .= ' AND mahasiswa_id = ' . $r->id . '';
            }

            if (auth()->user()->role == 'dosen') {
                $r = Dosen::where('kode', $usr->username)->first();
                $where .= ' AND pembimbing_id = ' . $r->id . '';
            }

            if ($request->mid) {
                $where .= ' AND mahasiswa_id = ' . $request->mid . '';
            }

            $data = Bimbingan::whereRaw($where)->orderBy('tanggal', 'desc');

            return DataTables::of($data)
                ->addIndexColumn()
                ->editColumn('pembimbing_id', function (Bimbingan $bbg) {
                    $return = '<small>' . $bbg->dosen->kode . ' - ' . $bbg->dosen->nama . '</small>';

                    return $return;
                })
                ->editColumn('tanggal', function (Bimbingan $bbg) {
                    $tanggal = Carbon::parse($bbg->tanggal)->translatedFormat('d M Y');

                    return $tanggal;
                })
                ->editColumn('konfirmasi', function (Bimbingan $bbg) {
                    $return = '<span class="text-muted">Menunggu</span>';

                    if ($bbg->konfirmasi !== null && $bbg->konfirmasi != '')
                        $return = '<span class="text-primary">' . $bbg->konfirmasi . '</span>';

                    return $return;
                })
                ->addColumn('action', function (Bimbingan $bbg) {
                    if (auth()->user()->role == 'admin' || auth()->user()->role == 'admin adak' || auth()->user()->role == 'dosen') {
                        $actionBtn = '';
                    } elseif (auth()->user()->role == 'mahasiswa') {
                        $actionBtn = '<a href="' . url("/bimbingan/mahasiswa/edit/" . $bbg->id . "") . '" class="edit btn btn-primary btn-xs"><i class="fas fa-edit fa-sm" title="Edit"></i></a>
                    ';

                        if ($bbg->konfirmasi == 'Diterima') {
                            $actionBtn = '';
                        }
                    }
                    return $actionBtn;
                })
                ->rawColumns(['pembimbing_id', 'tanggal', 'konfirmasi', 'action'])
                ->make(true);
        }
    }

    public function mahasiswaForm(Request $request)
    {
        return view('pages.portal.sidang.bimbingan.mhsform', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Bimbingan' => '/bimbingan/mahasiswa',
                'Form Tambah' => '/'
            ],
            'activeMenu' => $this->activeMenuMahasiswa,
            'pembimbings' => $this->getPembimbingCombo()

        ]);
    }

    public function mahasiswaStore(Request $request)
    {
        $rules = [
            'tanggal' => 'required|date_format:Y-m-d',
            'topik' => 'required|min:5',
            'pembimbing_id' => 'required',
        ];

        $usr = User::find(auth()->id());
        $mhs = Mahasiswa::where('nim', $usr->username)->first();

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

        $dataValidated['periode'] = session('periode_sidang');
        $dataValidated['bulan'] = session('bulan_sidang');
        $dataValidated['mahasiswa_id'] = $mhs->id;
        $dataValidated['sidang_id'] = $mhs->sidang->id;

        Bimbingan::create($dataValidated);

        $receiver = Dosen::leftJoin('users as usr', 'usr.username', 'dosens.kode')
            ->select('usr.id')
            ->where('dosens.id', $dataValidated['pembimbing_id'])->first();

        $this->notificationStore($receiver->id, null, auth()->id(), 'Telah mengisi form bimbingan');


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

    public function mahasiswaEdit($id)
    {
        return view('pages.portal.sidang.bimbingan.mhsform', [
            'breadcrumb' => [
                'Home' => '/',
                'Sidang' => '/',
                'Bimbingan' => '/bimbingan/mahasiswa',
                'Form Edit' => '/'
            ],
            'activeMenu' => $this->activeMenuMahasiswa,
            'pembimbings' => $this->getPembimbingCombo(),
            'data' => Bimbingan::find($id),
            'id' => $id

        ]);
    }

    public function mahasiswaUpdate(Request $request)
    {
        $rules = [
            'topik' => 'required|min:5',
            'pembimbing_id' => 'required',
        ];

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

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

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

    public function konfirmasi(Request $request)
    {

        $id = $request->id;
        $konfirmasi = 'Diterima';
        $status = '<span class="text-primary font-weight-bold">Diterima</span>';

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

        $bbg = Bimbingan::find($id);

        $notif = 'Meyetujui bimbingan Anda';

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

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

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


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

    public function selesai(Request $request)
    {
        $where = '1';
        if (auth()->user()->role == 'dosen') {
            $idd = Dosen::where('kode', auth()->user()->username)->first();
            $where .= ' AND pembimbing_id=' . $idd->id;

            $sdg = Sidang::find($request->sid);
            $column = 'sls_pbb2';
            if ($sdg->pbb1_net == $idd->id) {
                $column = 'sls_pbb1';
            }

            Sidang::find($request->sid)->update([
                $column => 'Selesai'
            ]);
        } else {
            Sidang::find($request->sid)->update([
                'sls_pbb1' => 'Selesai',
                'sls_pbb2' => 'Selesai'
            ]);
        }

        Bimbingan::where('sidang_id', $request->sid)
            ->whereRaw($where)
            ->update([
                'konfirmasi' => 'Diterima'
            ]);


        $receiver = Mahasiswa::leftJoin('users as usr', 'usr.username', 'mahasiswas.nim')
            ->select('usr.id')
            ->where('mahasiswas.id', $request->mid)->first();

        $this->notificationStore($receiver->id, null, auth()->id(), 'Menyelesaikan seluruh bimbingan Anda');
        return back()->with('success', 'Data berhasil disimpan');
    }

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

        if ($request->ajax()) {

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

            // Cek dosen pembimbing 1 atau 2
            // $idd = Dosen::where('kode', auth()->user()->username)->first();
            $idd = $request->pid;

            $sdg = Sidang::find($sid);
            $bxnCol = 'bxn_pbb2';
            $nilaiCol = 'nilai_pbb2';
            $cttCol = 'ctt_pbb2';

            if ($request->npbb == 'pbb1') {
                $bxnCol = 'bxn_pbb1';
                $nilaiCol = 'nilai_pbb1';
                $cttCol = 'ctt_pbb1';
            }

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

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

                // Cek bimbingan nilai
                $bbgNilai = Bimbingan_nilai::where('sidang_id', $sid)
                    ->where('pembimbing', $idd)
                    ->where('no', $detail[0])
                    ->first();

                if ($bbgNilai) {
                    Bimbingan_nilai::where('sidang_id', $sid)
                        ->where('pembimbing', $idd)
                        ->where('no', $detail[0])
                        ->update([
                            'nilai' => $detail[3],
                            'bxn' => $detail[4],
                        ]);
                } else {
                    Bimbingan_nilai::create([
                        'sidang_id' => $sid,
                        'pembimbing' => $idd,
                        'no' => $detail[0],
                        'kriteria' => $detail[1],
                        'bobot' => $detail[2],
                        'nilai' => $detail[3],
                        'bxn' => $detail[4],
                    ]);
                }
            }

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


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

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

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

            $pbb = $sdg->pbb2_net;
            if ($request->nilaipbb == 'pbb1') {
                $pbb = $sdg->pbb1_net;
            }

            $detail = Bimbingan_nilai::where('sidang_id', $request->sid)
                ->where('pembimbing', $pbb)
                ->get();

            $data = [
                'nilai' => $sdg,
                'detail' => $detail,
            ];
        }

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

    public function nilaiPrint($id, $pbb_req)
    {
        $data = [];
        $sdg = Sidang::find($id);

        $pbb = $sdg->pbb2_net;
        $pbbs = $sdg->pbbs2;
        $totbxn = $sdg->bxn_pbb2;
        $totnilai = $sdg->nilai_pbb2;
        $catatan = $sdg->ctt_pbb2;

        if ($pbb_req == 'pbb1') {
            $pbb = $sdg->pbb1_net;
            $pbbs = $sdg->pbbs1;
            $totbxn = $sdg->bxn_pbb1;
            $totnilai = $sdg->nilai_pbb1;
            $catatan = $sdg->ctt_pbb1;
        }

        $detail = Bimbingan_nilai::where('sidang_id', $id)
            ->where('pembimbing', $pbb)
            ->get();

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

        $pdf = PDF::loadView('pages.portal.sidang.bimbingan.cetak', $data)->setPaper('a4', 'landscape');
        $fileName =  'Form-Bimbingan-' . $sdg->mahasiswa->nim . '-' . $sdg->mahasiswa->nama . '.pdf';
        return $pdf->stream($fileName);
    }

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

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

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

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


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