<?php

namespace App\Exports;

use App\Models\Conveyance;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Carbon\Carbon;

class ClientConveyanceSummaryExport implements FromCollection, WithHeadings, ShouldAutoSize
{
    protected ?string $fromDate;
    protected ?string $toDate;
    protected ?int $sessionId;
    protected ?int $clientId;

    public function __construct(?string $fromDate = null, ?string $toDate = null, ?int $sessionId = null, ?int $clientId = null)
    {
        $this->fromDate  = $fromDate;
        $this->toDate    = $toDate;
        $this->sessionId = $sessionId;
        $this->clientId  = $clientId;
    }

    public function headings(): array
    {
        return [
            'Month',
            'Client Name',
            'Session',
            'Total Amount (₹)',
        ];
    }

    public function collection()
    {
        $q = Conveyance::with(['client', 'session'])
            ->where('status', 'submitted');

        // Apply date filters if provided
        if ($this->fromDate) {
            $q->whereDate('date', '>=', $this->fromDate);
        }
        if ($this->toDate) {
            $q->whereDate('date', '<=', $this->toDate);
        }

        // Apply session filter if provided
        if ($this->sessionId) {
            $q->where('session_id', $this->sessionId);
        }

        // Apply client filter if provided
        if ($this->clientId) {
            $q->where('client_id', $this->clientId);
        }

        $rows   = $q->orderBy('date', 'asc')->get();
        $groups = $rows->groupBy('client_id');

        $data = collect();
        $grandTotal = 0;

        foreach ($groups as $clientId => $items) {
            $client      = optional($items->first()->client);
            $sessionName = optional($items->first()->session)->name ?? '';

            // Month label from the earliest date in this client's items
            $firstDate   = $items->min('date');
            $monthLabel  = $firstDate
                ? Carbon::parse($firstDate)->format('M Y')
                : '';

            // Effective total per client (onward + return/custom)
            $totalAmount = $items->sum(function ($c) {
                $onward = (float) $c->amount;
                if ($c->is_return) {
                    $return = $c->return_amount !== null
                        ? (float) $c->return_amount
                        : $onward;
                    return $onward + $return;
                }
                return $onward;
            });

            $grandTotal += $totalAmount;

            $data->push([
                $monthLabel,
                $client->name ?? 'No Client Selected',
                $sessionName,
                number_format($totalAmount, 2, '.', ''),
            ]);
        }

        // Add a grand total row at the end
        if ($data->isNotEmpty()) {
            $data->push([
                '',
                'GRAND TOTAL',
                '',
                number_format($grandTotal, 2, '.', ''),
            ]);
        }

        return $data;
    }
}
