<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use App\Models\Subscriptions;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Collection;
use Carbon\Carbon;


class DashboardSelectedExportUser implements FromCollection, WithHeadings
{
    protected $ids;

    public function __construct($ids)
    {
        $this->ids = $ids; // Expecting $ids to be an array
    }

    public function collection()
    {
        $selectedTransactions = Subscriptions::whereIn('id', $this->ids)
            ->with(['iamPrincipal', 'subscriptionProduct'])
            ->get()
            ->toArray();

        $serial = 1;
        $mappedTransactions = collect($selectedTransactions)->map(function ($transaction) use (&$serial) {
            return [
                'Sr No.' => $serial++, // Increment serial number
                'Name' => ($transaction['iam_principal']['first_name'] ?? '') . ' ' . ($transaction['iam_principal']['last_name'] ?? ''),
                'Customer Id' => $transaction['iam_principal']['id'] ?? '',
                'Product Name' => $transaction['subscription_product']['product_name'] ?? '',
                'Product Detail' => $transaction['subscription_product']['product_details'] ?? '',
                'Amount' => $transaction['amount'],
                'Payment Details' => $transaction['stripe_customer_id'],
                'Subscription status' => $transaction['status'],
                'Subscription Start Date' => Carbon::parse($transaction['current_period_start'])->format('m/d/Y h:i A'),
                'Subscription End Date' => Carbon::parse($transaction['current_period_end'])->format('m/d/Y h:i A'),
                'Next Payment Date' => Carbon::parse($transaction['next_payment_date'])->format('m/d/Y h:i A')
            ];
        });

        return new Collection($mappedTransactions);
    }

    public function headings(): array
    {
        return [
            'Sr No.',
            'Full Name',
            'Customer Id',
            'Product Name',
            'Product Detail',
            'Amount',
            'Payment Details',
            'Subscription status',
            'Subscription Start Date',
            'Subscription End Date',
            'Next Payment Date'
        ];
    }
}
