<?php

namespace App\Http\Controllers\Mahasiswa;

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

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

use Session;
use Alert;
use Auth;

class ProposalController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        $title    = 'Proposal 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', 'rProposalUrl'])
                    ->whereHas('rKelompok', function ($query) use($nim){
                        $query->whereHas('rAnggota', function ($query) use($nim){
                            $query->where('nim', $nim);
                        });
                    })
                    ->whereYear('proposal.created_at', $year)
                    ->orderBy('kelompok_id')
                    ->get();
                    // dd($proposal->pluck('rProposalUrl.url')->toArray());
        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'periode'   => $periode,
            'year'      => $year,
        ];

        return view('backend.mahasiswa.proposal.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $title      = 'Upload Proposal Mahasiswa';
        $periode    = Periode::where('status', '1')->first();
        $getDosen   = GetDataApiController::getDosen();
        $jenis      = Jenis::pluck('nama','jenis_id');
        $bio        = auth()->user()->rBiodata;
        $proposal   = null;

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

        $cekproposal  = Proposal::where('created_user', auth()->user()->id)
                                ->where('periode_id', $periode->periode_id)
                                ->first();

        $jadwal   = JadwalKegiatan::where('periode_id', $periode->where('status', 1)->first()->periode_id)
                                    ->where('nama','Upload Proposal Seleksi Internal')->first();

        // dd($jadwal->tanggal_sekesai);

        if(($jadwal->tanggal_mulai <= Carbon::now()) && ($jadwal->tanggal_selesai <= Carbon::now())){
            return redirect()->route('mahasiswa.proposal.index')->with('warning', 'Batas Pengajuan telah berakhir!');
        }

        if($cekproposal) {
            return redirect()->route('mahasiswa.proposal.index')->with('warning', 'Sudah ada Proposal yang di ajukan!');
        }

        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,
            'proposal'  => $proposal,
            'jadwal'    => $jadwal
        ];

        return view('backend.mahasiswa.proposal.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        //
        $proposal   = $request->except('_token');

        $this->validate($request,
            [
                'file' => 'required|mimes:pdf|max:5000',
                'jenis' => 'required|not_in:Pilih Jenis',
            ], [
                'file.required' => 'Tidak ada file yang diupload.',
                'file.file' => 'File harus berupa file.',
                'file.mimes' => 'File harus berupa file PDF.',
                'file.max' => 'Ukuran file maksimal adalah 5 MB.',
                'jenis.required' => 'Harap pilih Kategori PMW.',
                'jenis.not_in' => 'Harap pilih Kategori PMW yang valid.',
            ]);

        $periode    = Periode::where('status', '1')->first();
        $uuid       = Str::uuid();

        $file_nama  = $periode->nama.'_'.$uuid.'.'.$proposal['file']->getClientOriginalExtension();

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

        $kel = Proposal::create([
            'proposal_id'    => $uuid,
            'kelompok_id'    => $proposal['kode_kelompok'],
            'jenis_id'       => $proposal['jenis'],
            'periode_id'     => $proposal['periode_id'],
            'judul'          => $proposal['judul'],
            'status'         => '0',
            'upload_dokumen' => $file_nama,
            'usulan_dana'    => $proposal['usulan_dana'],
            'date_upload'    => now(),
            'created_user'   => Auth::user()->id
        ]);
        if ($kel) {
            ProposalUrl::create([
                'id' => $uuid,
                'url_name' => $proposal['url_name'],
                'url' => $proposal['url'],
                'deskripsi' => $proposal['deskripsi'],
                'proposal_id' => $kel->proposal_id,
                'created_at' => $kel->date_upload,
                'updated_at' => $kel->date_upload
            ]);
        }

        return redirect()->route('mahasiswa.proposal.index')->with('success', 'Proposal Berhasil ditambahkan');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $title      = 'Edit Upload Proposal Mahasiswa';
        $periode    = Periode::where('status', '1')->first();
        $getDosen   = GetDataApiController::getDosen();
        $jenis      = Jenis::pluck('nama','jenis_id');

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

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

        return view('backend.mahasiswa.proposal.create', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $proposal   = $request->except('_token');
        // dd($proposal);
        $this->validate($request,
        [
            'file' => 'mimes:pdf|max:5000'
        ], [
            'file.mimes' => 'File harus pdf',
            'file.max' => 'File tidak boleh lebih dari 5 mb',
        ]);

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

        if(!isset($proposal['file'])){
            $file_nama = $pro->upload_dokumen;
        } else {
            // Storage::disk('static')->delete('simpmw/proposal/'.$pro->rPeriode->nama.'/'.$pro->upload_dokumen);

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

        $pro->jenis_id          = $proposal['jenis'];
        $pro->judul             = $proposal['judul'];
        $pro->upload_dokumen    = $file_nama;
        $pro->date_upload       = now();
        $pro->updated_at        = now();
        $pro->updated_user       = Auth::user()->id;

        $pro->save();

        return redirect()->route('mahasiswa.proposal.index')->with('success', 'Proposal Berhasil di revisi');
    }

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

        $proposal = Proposal::query()->find(decrypt($pro['id']));

        Storage::disk('static')->delete('simpmw/proposal/'.$proposal->rPeriode->nama.'/'.$proposal->upload_dokumen);

        $proposal->delete();

        Alert::success('Berhasil dihapus');

        return redirect()->route('mahasiswa.proposal.index');
    }
}
