<?php

namespace App\Exports;

use App\User;
use App\Models\Kota;
use App\Models\Provinsi;
use App\Models\Kecamatan;
use App\Models\Kelurahan;
use App\Models\Kuesioner;
use App\Models\UsersDetil;
use App\Models\KuesionerPage;
use App\Models\KuesionerField;
use App\Models\KuesionerAnswer;
use App\Models\KuesionerSection;
use Illuminate\Support\Facades\DB;
use App\Models\KuesionerAnswerDetil;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class KelompokExport implements FromCollection,WithHeadings,ShouldAutoSize,WithTitle
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function __construct($fakultas,$prodi,$lulusan,$group)
    {
        $this->fakultas = $fakultas;
        $this->prodi = $prodi;
        $this->lulusan = $lulusan;
        $this->group = $group;
    }

    public function title(): string
    {
        return 'Users';
    }

    public function collection()
    {
        $statement = " IS_ACTIVE = '1' ";

        if($this->fakultas != "0")
        {
            $statement .= " AND b.fakultas_id = '".$this->fakultas."'";
        }

        if($this->prodi != "0" && $this->prodi != "")
        {
            $statement .= " AND b.prodi_id = '".$this->prodi."'";
        }

        if($this->lulusan != "0")
        {
            $statement .= " AND b.tahun_lulus = '".$this->lulusan."'";
        }

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

        $data = User::join('users_detil as b', 'users.id', '=', 'b.users_id')
        ->join('users_group as e', 'users.role', '=', 'e.nama')
        ->leftjoin('fakultas as c', 'b.fakultas_id', '=', 'c.id')
        ->leftjoin('prodi as d', 'b.prodi_id', '=', 'd.id')
        ->whereRaw($statement)
        ->select('nim', 'users.email', 'users.name', 'c.nama as nama_fakultas', 'd.nama as nama_prodi', 'tahun_lulus', 'b.no_tlp')
        ->get();

        return collect($data);
    }

    public function headings(): array
    {
        return ["NIM", "Email", "Nama", "Fakultas", "Prodi", "Lulusan", "No HP"];
    }
}
