<?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_customer = IamPrincipal::whereIn('id', $this->ids)
            ->with('state:id,name') // Eager load the state relationship
            ->orderBy('id', 'desc')
            ->select(
                'first_name',
                'last_name',
                'email_address',
                'date_of_birth',
                'state_xid',
                'phone_number'
            )
            ->get()
            ->map(function ($customer) {
                return [
                    '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,
                ];
            });

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

        return new Collection($selected_customer);
    }

    public function headings(): array
    {
        return [
            'First Name',
            'Last Name',
            'Email Address',
            'Date of Birth',
            'State Name',
            'Phone Number'
        ];
    }
}
