<?php

namespace App\Exports;

use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class ObatMasukExport implements FromCollection, WithHeadings, WithMapping
{
    protected $startDate;
    protected $endDate;

    public function __construct($startDate, $endDate)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
    }

    public function collection()
    {
        return DB::table('obat_masuks')
            ->join('satuans', 'obat_masuks.satuan_id', '=', 'satuans.id')
            ->whereBetween('tanggal_penerimaan', [$this->startDate, $this->endDate])
            ->select(
                'obat_masuks.nama_obat',
                'satuans.nama as satuan',
                DB::raw('SUM(obat_masuks.stok) as total_jumlah')
            )
            ->groupBy('obat_masuks.nama_obat', 'satuans.nama')
            ->orderBy('obat_masuks.nama_obat')
            ->get();
    }

    public function headings(): array
    {
        return [
            'Nama Obat',
            'Satuan',
            'Total Jumlah Masuk',
        ];
    }

    public function map($row): array
    {
        return [
            $row->nama_obat ?? 'N/A',
            $row->satuan ?? '-',
            $row->total_jumlah,
        ];
    }
}
