<?php

namespace App\Exports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class StockExport implements FromQuery, WithHeadings, WithMapping, WithStyles, WithTitle, ShouldAutoSize
{
    public function query()
    {
        return Product::with('category')->where('is_active', true)->orderBy('name');
    }

    public function headings(): array
    {
        return [
            'SKU', 'Nama Produk', 'Kategori', 'Satuan',
            'Harga Modal (Rp)', 'Harga Jual (Rp)', 'Margin (%)',
            'Stok', 'Min. Stok', 'Status Stok',
            'Nilai Modal (Rp)', 'Nilai Jual (Rp)',
        ];
    }

    public function map($p): array
    {
        return [
            $p->sku,
            $p->name,
            $p->category?->name ?? '-',
            $p->unit,
            $p->cost_price,
            $p->selling_price,
            number_format($p->margin, 1) . '%',
            $p->track_stock ? $p->stock : '∞',
            $p->min_stock,
            $p->is_low_stock ? 'MENIPIS' : 'Aman',
            $p->track_stock ? $p->cost_price * $p->stock : '-',
            $p->track_stock ? $p->selling_price * $p->stock : '-',
        ];
    }

    public function styles(Worksheet $sheet): array
    {
        return [
            1 => ['font' => ['bold' => true], 'fill' => ['fillType' => 'solid', 'startColor' => ['rgb' => '1D4ED8']]],
        ];
    }

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