<?php

namespace App\Exports;

use App\Models\Laporan;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class LaporanExport implements FromView, ShouldAutoSize
{
    protected $bulan;
    protected $tahun;

    public function __construct($bulan, $tahun)
    {
        $this->bulan = $bulan;
        $this->tahun = $tahun;
    }

    public function view(): View
    {
        $query = Laporan::with(['gl', 'manpower', 'details'])
            ->whereBetween('tanggal', [
                Carbon::create($this->tahun, $this->bulan, 1)->startOfMonth(),
                Carbon::create($this->tahun, $this->bulan, 1)->endOfMonth(),
            ])->orderBy('tanggal', 'desc');

        if (Auth::check() && Auth::user()->role !== 'administrator') {
            $query->where('user_id', Auth::id());
        }

        $data = $query->get();

        return view('exports.laporan', [
            'laporans' => $data
        ]);
    }
}
