<?php

namespace App\Exports;

use App\Models\DaftarProposalBelmawa;

use Illuminate\Support\Facades\DB;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class DaftarProposalMonevExport implements FromView,ShouldAutoSize
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function __construct($jenis,$status,$tahun)
    {
        $this->jenis= $jenis;
        $this->status = $status;
        $this->tahun= $tahun;
    }

    public function view(): View
    {
        $statement = " STATUS_HAPUS = '0' ";

        if($this->jenis != "0")
        {
            $statement .= " AND jenis_id = '".$this->jenis."'";
        }

        if($this->status != "0")
        {
            // dikurang 1 karena di view mulai dari 0 sedangkan 0 itu menunggu persetujuan
            $status = $this->status - 1;
            $statement .= " AND STATUS_FINAL = '".$status."'";
        }

        if($this->tahun != "0")
        {
            $statement .= " AND PERIODE = '".$this->tahun."'";
        }

        $data = DaftarProposalBelmawa::with('rKelompokDetil')->whereRaw($statement)->get();
        $result = [];

        $no = 0;

        foreach ($data as $key => $value) {
            $dospem = "(".str_replace("###",") ",$value->identitas_dospem);
            $url = "https://statik.unesa.ac.id/simpkm/proposal/".$value->periode."/".$value->upload_dokumen;

            $urut = 1;
            foreach ($value->rKelompokDetil as $keys => $detil) {

                if($detil->status_ketua == '1')
                {
                    $keanggotaan = "Ketua";
                }
                else
                {
                    $keanggotaan = "Anggota ".$urut;
                    $urut++;
                }

                $result[$no]['rowspan'] = count($value->rKelompokDetil);
                $result[$no]['kode'] = $value->kode_kelompok;
                $result[$no]['jenis'] = $value->jenis_pkm;
                $result[$no]['fak'] = $detil->fakultas;
                $result[$no]['nama'] = $detil->nama;
                $result[$no]['nim'] = $detil->nim;
                $result[$no]['keanggotaan'] = $keanggotaan;
                $result[$no]['judul'] = $value->judul;
                $result[$no]['dospem'] = $dospem;
                $result[$no]['link'] = $url;
                $result[$no]['status'] = $value->status_desc;

                $no++;
            }
        }

        $datas['list_proposal'] = $result;
        $datas['jenis_monev'] = 'Seleksi Belmawa';

        return view('backend.operator.daftar_proposal.excel', $datas);
    }
}
