<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Facades\Log;  
use Carbon\Carbon;// Add this
class LeadsExport implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    protected $leads;
    protected $users;
    protected $lead_status;
    public function __construct($leads,$users,$lead_status)
    {
        $this->leads = $leads;
        $this->users = $users;
        $this->lead_status=$lead_status;
        // Log the count of leads
        Log::info('Number of leads passed to export: ' . count($this->leads));
 // Iterate through leads and log assigned user if available
 foreach ($this->leads as $lead) {
// Get lead_status title if it exists
     // Match lead_status to lead_title_url and get the title
     if (isset($lead->lead_status)) {
        $leadStatus = $lead->lead_status;
        // Iterate through the $lead_status array to find a match
        $matchedStatus = null;
        foreach ($this->lead_status as $status) {
            if (isset($status->lead_title_url) && $status->lead_title_url == $leadStatus) {
                $matchedStatus = $status->title ?? 'N/A'; // Get the title if it exists
                break;
            }
        }

        // Log the result
        Log::info('Lead Status Title: ' . ($matchedStatus ?: 'N/A'));
    } else {
        Log::info('Lead Status: Unavailable (no lead_status property)');
    }


}
    }

    public function collection()
    {
        return collect($this->leads)->map(function ($lead) {
            // Ensure $lead is an object before accessing its properties
            if (is_object($lead) && isset($lead->assigned_to)) {
                // Check if the assigned user exists in the $users array
                $assignedUser = null;
                foreach ($this->users as $user) {
                    if ($user->id == $lead->assigned_to) {
                        $assignedUser = $user;
                        break; // Stop searching once the user is found
                    }
                }
    
                // Set the assignedRep and timezone based on the found user
                if ($assignedUser) {
                    $assignedRep = $assignedUser->first_name . ' ' . $assignedUser->last_name;
                    $timezone = $assignedUser->timezone ?? 'UTC'; // Default to UTC if timezone is not set
                } else {
                    $assignedRep = 'Unassigned';
                    $timezone = 'UTC'; // Default timezone for unassigned leads
                }
    
                // Format the updated_at field with the proper timezone if available
                $updatedAt = isset($lead->updated_at)
                    ? \Carbon\Carbon::parse($lead->updated_at)
                        ->setTimezone($timezone)
                        ->format('m/d/Y H:i A')
                    : 'N/A'; // Default value if updated_at is missing
            } else {
                $assignedRep = 'Unassigned';
                $timezone = 'UTC';
                $updatedAt = 'N/A';
            }
        // Match lead_status to lead_title_url and get the title
        if (isset($lead->lead_status)) {
            $leadStatus = $lead->lead_status;
            // Iterate through the $lead_status array to find a match
            $matchedStatus = null;
            foreach ($this->lead_status as $status) {
                if (isset($status->lead_title_url) && $status->lead_title_url == $leadStatus) {
                    $matchedStatus = $status->title ?? 'N/A'; // Get the title if it exists
                    break;
                }
            }
    
            // Log the result
            Log::info('Lead Status Title: ' . ($matchedStatus ?: 'N/A'));
        } else {
            Log::info('Lead Status: Unavailable (no lead_status property)');
        }
            // Return the formatted lead data
            return [
                $lead->first_name,        // Fallback if first_name is missing
                $lead->last_name,         // Fallback if last_name is missing
                $lead->email,             // Fallback if email is missing
                " " .$lead->phone_number,      // Fallback if phone_number is missing
                $lead->company_name,      // Fallback if company_name is missing
                $matchedStatus,       // Fallback if lead_status is missing
                $updatedAt,                        // Formatted 'updated_at' value
                $assignedRep,                      // Assigned user or 'Unassigned'
            ];
        });
    }
    
    


    public function headings(): array
    {
        return [
            'First Name',
            'Last Name',
            'Email',
            'Mobile',
            'Legal Company Name',
            'Lead Status',
            'Modified Date',
            'Assigned Rep',


            // Add other relevant fields here
        ];
    }
    
}
