<?php

namespace App\Exports;

use App\Models\DaftarProposal;

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

class ProposalExport 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 = '".$status."'";
        }

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

        $data = DaftarProposal::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;
                $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;

                $no++;
            }
        }

        $datas['list_proposal'] = $result;

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