<?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 ObatKeluarExport 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_keluars')
            ->join('obat_masuks', 'obat_keluars.obat_masuk_id', '=', 'obat_masuks.id')
            ->leftJoin('satuans', 'obat_masuks.satuan_id', '=', 'satuans.id')
            ->whereNotIn('obat_keluars.status', ['proses', 'dibatalkan'])
            ->whereBetween('obat_keluars.tanggal_pengeluaran', [$this->startDate, $this->endDate])
            ->select(
                'obat_keluars.nama_obat',
                'satuans.nama as satuan',
                DB::raw('SUM(obat_keluars.jumlah) as total_jumlah')
            )
            ->groupBy('obat_keluars.nama_obat', 'satuans.nama')
            ->orderBy('obat_keluars.nama_obat')
            ->get();
    }

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

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