<?php

namespace App\Http\Controllers\Mahasiswa;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\GetDataApiController;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

use App\Models\Proposal;
use App\Models\Kelompok;
use App\Models\Periode;
use App\Models\Jenis;

use Session;
use Alert;
use App\Models\DaftarProposal;
use App\Models\SeleksiBelmawa;
use Auth;
use DB;

class SeleksiController extends Controller
{

    public function seleksiInternal(Request $request)
    {
        //
        $title    = 'Seleksi Internal Mahasiswa';
        $bio      = auth()->user()->rBiodata;
        $nim      = $bio->noidentitas;
        $periode  = Periode::query()->get();
        $year     = !is_null($request->year) ? $request->year : now()->year;

        $proposal = Proposal::with(['rKelompok', 'rJenis', 'rNilai', 'rDaftarPro'])
                    ->whereHas('rKelompok', function ($query) use($nim){
                        $query->whereHas('rAnggota', function ($query) use($nim){
                            $query->where('nim', $nim);
                        });
                    })
                    ->whereYear('created_at', $year)
                    ->orderBy('kelompok_id')
                    ->get();
                // dd($proposal);

        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'periode'   => $periode,
            'year'      => $year,
        ];

        return view('backend.mahasiswa.seleksi.index_internal', $data);
    }

    public function internalRevisi()
    {
        //
        $title      = 'Tambah Proposal Mahasiswa';
        $periode    = Periode::where('status', '1')->first();
        $getDosen   = GetDataApiController::getDosen();
        $jenis      = Jenis::pluck('nama','jenis_id');
        $bio        = auth()->user()->rBiodata;

        $kelompok   = Kelompok::where('created_user', auth()->user()->id)
                              ->where('periode_id', $periode->periode_id)
                              ->where('status', '1')
                              ->first();

        if(is_null($kelompok)){

            return redirect()->route('mahasiswa.proposal.index')->with('warning', 'Belum ada kelompok!');
        }

        $data = [
            'title'     => $title,
            'dosen'     => $getDosen['data'],
            'periode'   => $periode,
            'jenis'     => $jenis,
            'kelompok'  => $kelompok
        ];

        return view('backend.mahasiswa.seleksi.internal_revisi', $data);
    }


    public function seleksiBelmawa(Request $request)
    {
        //
        $title    = 'Seleksi Belmawa Mahasiswa';
        $bio      = auth()->user()->rBiodata;
        $nim      = $bio->noidentitas;
        $periode  = Periode::query()->get();
        $year     = !is_null($request->year) ? $request->year : now()->year;

        $proposal = Proposal::with(['rKelompok', 'rJenis', 'rNilai', 'rReviewProposal', 'rBelmawa'])
                    ->whereHas('rKelompok', function ($query) use($nim){
                        $query->whereHas('rAnggota', function ($query) use($nim){
                            $query->where('nim', $nim);
                        });
                    })
                    ->whereYear('created_at', $year)
                    ->orderBy('kelompok_id')
                    ->get();

        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'periode'   => $periode,
            'year'      => $year,
        ];

        return view('backend.mahasiswa.seleksi.index_belmawa', $data);
    }

    public function editBelmawa($id)
    {
        //
        $title    = 'Edit Proposal Belmawa';

        $proposal = Proposal::with(['rJenis', 'rNilai'])->find($id);

        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
        ];

        return view('backend.mahasiswa.seleksi.revisi_belmawa', $data);
    }

    public function uploadBelmawa(Request $request)
    {
        //
        $pro   = $request->except('_token');

        $this->validate($request,
            [
                'file' => 'required|mimes:pdf|max:5000'
            ], [
                'file.required' => 'Tidak ada file yang di upload',
                'file.mimes' => 'File harus pdf',
                'file.max' => 'File tidak boleh lebih dari 5 mb',
            ]);

        $proposal = Proposal::with(['rPeriode'])->find($pro['proposal_id']);

        $belmawa = SeleksiBelmawa::where('proposal_id', $pro['proposal_id'])->first();

        $file_nama  = $proposal->rPeriode->nama.'_'.$proposal->proposal_id.'.'.$pro['file']->getClientOriginalExtension();

        Storage::disk('static')->put('simpmw/proposal/revisi/'.$proposal->rPeriode->nama.'/'.$file_nama, file_get_contents($pro['file']->getRealPath()));

        $belmawa->upload_dokumen = $file_nama ;
        $belmawa->date_upload = now();
        $belmawa->save();

        return redirect()->route('mahasiswa.seleksi-belmawa')->with('success', 'Proposal Berhasil revisi');
    }

    public function lihatInternal(Request $request)
    {

        $item = DaftarProposal::where('proposal_id', $request->proposal_id)->first();

        // $nilai_1= DB::select("select ambil_jumlah_penilaian_seleksi('".$item->reviewer_proposal_id_1."', '".$item->jenis_id."')")[0]->ambil_jumlah_penilaian_seleksi;
        // $nilai_2= DB::select("select ambil_jumlah_penilaian_seleksi('".$item->reviewer_proposal_id_2."', '".$item->jenis_id."')")[0]->ambil_jumlah_penilaian_seleksi;
        // Hindari kirim string kosong ke fungsi Postgres (tipe uuid)
        if (!empty($item->reviewer_proposal_id_1)) {
            $res1 = DB::select(
                "select ambil_jumlah_penilaian_seleksi(?, ?) as nilai",
                [$item->reviewer_proposal_id_1, $item->jenis_id]
            );
            $nilai_1 = $res1[0]->nilai ?? 0;
        } else {
            $nilai_1 = 0;
        }

        if (!empty($item->reviewer_proposal_id_2)) {
            $res2 = DB::select(
                "select ambil_jumlah_penilaian_seleksi(?, ?) as nilai",
                [$item->reviewer_proposal_id_2, $item->jenis_id]
            );
            $nilai_2 = $res2[0]->nilai ?? 0;
        } else {
            $nilai_2 = 0;
        }

        // $rata = number_format((float) (($nilai_1 + $nilai_2) / 2), 0, '.', '');
        // Jika kedua nilai 0, anggap belum ada review
        $rata = ($nilai_1 == 0 && $nilai_2 == 0)
            ? null
            : number_format((float) (($nilai_1 + $nilai_2) / 2), 0, '.', '');

        $data = '';
        $no = 1;

            if($item->upload_dokumen){
                $dokumen = ' <a href="https://statik.unesa.ac.id/simpmw/proposal/'. $item->periode .'/'. $item->upload_dokumen.'"  target="_blank" class="btn btn-success btn-sm"> <i class="far fa-eye"></i> Lihat Proposal</a>
                             <iframe id="view-pdf" width="100%" height="400px" src="https://statik.unesa.ac.id/simpmw/proposal/'. $item->periode .'/'.$item->upload_dokumen .'" frameborder="0"></iframe>';
                }else{
                $dokumen = '<div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                <strong>Informasi!</strong><br/> File tidak ditemukan.
                            </div>';
                }

            if(is_null($item->status)){
                $status = '<span class="badge bg-danger">Menunggu Persetujuan Dosen</span>';
            }else{
                $status = '<span class="badge bg-success">Sudah Disetujui Dosen</span>';
            }

            $data .= "
                        <tr>
                            <td>Judul Proposal</td>
                            <td>" . $item->judul . "</td>
                        </tr>
                        <tr>
                            <td>Kategori PMW</td>
                            <td>" . $item->jenis_pkm . "</td>
                        </tr>
                        <tr>
                            <td>Status</td>
                            <td>" . $status . "</td>
                        </tr>
                        <tr>
                            <td>Proposal</td>
                            <td>" . $dokumen . "</td>
                        </tr>
                        <tr>
                            <td>Komentar</td>
                            <td>
                                <h4 class='card-title mb-4'>Status Nilai</h4>";

                    if (!is_null($rata)) {
                        $data .= "<p class='mb-4 pb-4'><span class='badge bg-success'>Telah direview.</span></p>";
                    } else {
                        $data .= "<p class='mb-4 pb-4'><span class='badge bg-danger'>Belum ada review.</span></p>";
                    }

            $data .= "
                        <h4 class='card-title mb-4'>Reviewer 1</h4>
                        <p class='text-muted mb-3 pb-4'>" . $item->reviewer_komentar_1 . "</p>
                        <h4 class='card-title mb-4'>Reviewer 2</h4>
                        <p class='text-muted mb-3 pb-4'>" . $item->reviewer_komentar_2 . "</p>
                    </td>
                </tr>
            ";

        // <p class='text-muted mb-3 pb-4'>" . $rata . "</p>

        $response['html'] = $data;
        echo json_encode($response);

    }

}
