<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class UserAppDownloadExport implements FromCollection, WithHeadings, WithMapping
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $request = request();
        $users = User::downloadAppUserList()
            ->searchable(['username', 'email', 'system_id'])
            ->dateFilter('app_downloaded_at')
            ->orderBy('id', 'desc');

        if (!empty($request->query('coupon_issued'))) {
            if ($request->query('coupon_issued') == 'yes') {
                $users = $users->whereNotNull('coupon_issued_at');
            } elseif ($request->query('coupon_issued') == 'no') {
                $users = $users->whereNull('coupon_issued_at');
            }
        }

        $users = $users->get();
        return $users;
    }

    public function map($row): array
    {
        return [
            $row->system_id,
            $row->username,
            $row->fullname,
            $row->email,
            "+{$row->mobile}",
            $row->app_downloaded_at ? $row->app_downloaded_at->format('d-m-Y h:i A') : null,
            $row->coupon_issued_at ? 'yes' : 'no'
        ];
    }

    public function headings(): array
    {
        return [
            __('UserId'),
            __('Username'),
            __('Name'),
            __('Email'),
            __('Mobile'),
            __('App downloaded at'),
            __('coupon issued'),
        ];
    }
}
