<?php
namespace App\Exports;

use App\Models\Link;
use App\Enums\LinkStatus;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class PaymentsExport implements FromCollection, WithHeadings, WithMapping
{
    protected $campaignId, $from, $to, $type, $totalAmount = 0;

    public function __construct($campaignId=null, $from=null, $to=null, $type='all')
    {
        $this->campaignId = $campaignId;
        $this->from       = $from;
        $this->to         = $to;
        $this->type       = $type;
    }

    public function collection()
    {
        $query = Link::with(['campaign', 'donateur', 'payments'])
            ->whereHas('payments');

        if ($this->campaignId) {
            $query->where('campaign_id', $this->campaignId);
        }
        if ($this->from) {
            $query->whereDate('created_at', '>=', $this->from);
        }
        if ($this->to) {
            $query->whereDate('created_at', '<=', $this->to);
        }

        if ($this->type === 'paid') {
            $query->where('status', LinkStatus::Paid);
        } elseif ($this->type === 'pending') {
            $query->where('status', LinkStatus::Pending);
        }

        $links = $query->get();
        $this->totalAmount = $links->sum(fn($l) => $l->payments->sum('amount'));

        $summary = new \stdClass();
        $summary->is_summary  = true;
        $summary->currency    = $links->first()->payments->first()->currency ?? '';
        $summary->totalAmount = $this->totalAmount;

        $links->push($summary);

        return $links;
    }

    public function headings(): array
    {
        return ['Campaign','Donateur','Email','Téléphone','Token','Status','Montant','Devise','Paid At'];
    }

    public function map($link): array
    {
        if (isset($link->is_summary)) {
            return ['', '', '', '', '', 'Total', $link->totalAmount, $link->currency, ''];
        }

        $payment = $link->payments->first();
        $total   = $link->payments->sum('amount');

        return [
            $link->campaign->name,
            $link->donateur->nom.' '.$link->donateur->prenom,
            $link->donateur->email,
            $link->donateur->telephone,
            $link->token,
            $payment->status,
            $total,
            $payment->currency,
            $payment->paid_at,
        ];
    }
}

