<?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 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'])
                    ->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.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('kirim', '1')
                              ->first();

        $cekproposal  = Proposal::where('created_user', auth()->user()->id)
                                ->where('periode_id', $periode->periode_id)
                                ->first();
        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
        ];

        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)
    {
        //
        $proposal   = $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',
            ]);

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

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

        Storage::disk('static')->put('simpkm/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,
            'date_upload'    => now(),
            'created_user'   => Auth::user()->id
        ]);

        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('simpkm/proposal/'.$pro->rPeriode->nama.'/'.$pro->upload_dokumen);

            $file_nama = $pro->rPeriode->nama.'_'.$pro->proposal_id.'.'.$proposal['file']->getClientOriginalExtension();
            Storage::disk('static')->put('simpkm/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('simpkm/proposal/'.$proposal->rPeriode->nama.'/'.$proposal->upload_dokumen);

        $proposal->delete();

        Alert::success('Berhasil dihapus');

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