<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use App\Models\IamPrincipal;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class customer_export_selected implements FromCollection, WithHeadings
{
    protected $ids;

    public function __construct($ids)
    {
        $this->ids = explode(',', $ids); // Ensure ids are split into an array
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        // Log the ids for debugging purposes
        Log::info('Fetching data for IDs: ' . implode(',', $this->ids));

        $selected_customers = IamPrincipal::whereIn('id', $this->ids)
            ->with(['state:id,name', 'isSubscribed']) // Eager load the state and subscription relationships
            ->orderBy('id', 'desc')
            ->select(
                'id',
                'first_name',
                'last_name',
                'email_address',
                'date_of_birth',
                'state_xid',
                'phone_number'
            )
            ->get();

        $serial = 1;
        $mappedCustomers = $selected_customers->map(function ($customer) use (&$serial) {
            $subscription = $customer->isSubscribed->first();
            $dateTime = now();
            $formattedDateTime = $dateTime->format('Y-m-d H:i:s');
            $isSubscribed = $subscription && $subscription->next_payment_date >= $formattedDateTime && $subscription->status == 'complete' ? 'Subscribed' : 'Unsubscribed';
            return [
                'Sr No.' => $serial++, // Increment serial number
                'id' => $customer->id,
                'first_name' => $customer->first_name,
                'last_name' => $customer->last_name,
                'email_address' => $customer->email_address,
                'date_of_birth' => \Carbon\Carbon::parse($customer->date_of_birth)->format('m/d/Y'), // Format the date
                'state_xid' => $customer->state->name ?? '', // Access the state name and handle null
                'phone_number' => $customer->phone_number,
                'subscription_status' => $isSubscribed, // Add the subscription status
            ];
        });

        // Log the fetched data for debugging purposes
        Log::info('Fetched customer data: ' . $mappedCustomers->toJson());

        return new Collection($mappedCustomers);
    }

    public function headings(): array
    {
        return [
            'Sr No.',
            'User Id',
            'First Name',
            'Last Name',
            'Email Address',
            'Date of Birth',
            'State Name',
            'Phone Number',
            'Subscription Status' // Add the heading for subscription status
        ];
    }
}
