<?php

namespace App\Exports;

use App\Models\HasilPrediksi;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Illuminate\Support\Facades\Auth;

class PrediksiExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
{
    protected $year;
    protected $month;
    private $rowNumber = 0;

    public function __construct($year, $month) {
        $this->year  = $year;
        $this->month = $month;
    }

    public function collection() {
        return HasilPrediksi::where('user_id', Auth::id())
            ->whereRaw('YEAR(tanggal) = ?', [$this->year])
            ->whereRaw('MONTH(tanggal) = ?', [$this->month])
            ->orderBy('tanggal', 'asc')
            ->get();
    }

    public function headings(): array {
        return ["No", "Tanggal", "Estimasi (Tabung)", "Batas Bawah", "Batas Atas"];
    }

    public function map($row): array {
        $this->rowNumber++;
        return [
            $this->rowNumber,
            \Carbon\Carbon::parse($row->tanggal)->translatedFormat('d F Y'),
            (int)($row->estimasi    ?? 0),
            (int)($row->batas_bawah ?? 0),
            (int)($row->batas_atas  ?? 0),
        ];
    }
}