<?php

namespace App\Exports;

use App\Models\User;
use App\Models\Subscription;
use App\Models\Region;
use App\Models\Package;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\WithHeadings;



class UsersExport implements FromCollection , WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
		$users = User::where('role', 2)->get();

		$data = collect();

		$headings = [
		    'Name',
		    'Email',
		    'Phone',
		    'Location',
		    'Region',
		    'Package',
		   // 'Status',
		];


		foreach ($users as $user) {
		    $region = Region::where('id', $user->region)->first();
		    $reg = $region ? $region->name : 'N/A';

		    if ($user->status != 1) {
		        $sub = Subscription::where('user_id', $user->id)->first();
		        $package = $sub ? Package::where('id', $sub->package)->first() : null;
		        $status = 'Inactive';
		    } else {
		        $sub = Subscription::where('user_id', $user->id)->where('status', 1)->first();
		        if (!$sub) {
		            $status = 'Active';
		            $pac = 'N/A';
		        } else {
		            $package = Package::where('id', $sub->package)->first();
		            $pac = $package ? $package->name : 'N/A';
		            $status = 'Inactive';
		        }
		    }

		    $userData = new Collection([
		        'name' => $user->name,
		        'email' => $user->email,
		        'phone' => $user->phone,
		        'location' => $user->location,
		        'region' => $reg,
		        'package' => $pac ?? 'N/A', // Use null coalescing to handle the case where $pac is not set
		       // 'status' => $status,
		    ]);

		    $data->push($userData);
		}


		return $data;


    }

    public function headings(): array
    {
        return [
            'Name',
            'Email',
            'Phone',
            'Location',
            'Region',
            'Package',
            // 'Status',
        ];
    }
}
