<?php

namespace App\Exports;

use App\Models\Order;
use App\Models\SalaryPayment;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ReportExport implements FromCollection, WithHeadings
{
    public function __construct(
        protected string $tab,
        protected int $shopId,
        protected $from,
        protected $to
    ) {}

    public function collection()
    {
        return match ($this->tab) {
            'pipeline' => Order::where('shop_id', $this->shopId)
                ->with('customer')
                ->get()
                ->map(fn ($o) => [
                    $o->id, $o->customer->name ?? '—', $o->stage, $o->total_amount,
                ]),
            'balances' => Order::where('shop_id', $this->shopId)
                ->where('balance_amount', '>', 0)
                ->with('customer')
                ->get()
                ->map(fn ($o) => [
                    $o->id, $o->customer->name ?? '—', $o->total_amount, $o->advance_amount, $o->balance_amount,
                ]),
            'salary' => SalaryPayment::where('shop_id', $this->shopId)
                ->whereBetween('paid_on', [$this->from, $this->to])
                ->with('staff')
                ->get()
                ->map(fn ($p) => [
                    $p->staff->name ?? '—', $p->staff->staff_code ?? '—', $p->amount, $p->paid_on->format('Y-m-d'), $p->notes,
                ]),
            default => Order::where('shop_id', $this->shopId)
                ->whereBetween('created_at', [$this->from, $this->to])
                ->with('customer')
                ->get()
                ->map(fn ($o) => [
                    $o->id, $o->customer->name ?? '—', $o->created_at->format('Y-m-d'),
                    $o->total_amount, $o->advance_amount, $o->balance_amount,
                ]),
        };
    }

    public function headings(): array
    {
        return match ($this->tab) {
            'pipeline' => ['Order ID', 'Customer', 'Stage', 'Total ₹'],
            'balances' => ['Order ID', 'Customer', 'Total ₹', 'Advance ₹', 'Balance ₹'],
            'salary' => ['Staff', 'Staff ID', 'Amount ₹', 'Paid On', 'Notes'],
            default => ['Order ID', 'Customer', 'Date', 'Total ₹', 'Advance ₹', 'Balance ₹'],
        };
    }
}
