<?php

namespace App\Exports;
use EloquentBuilder;
use Maatwebsite\Excel\Excel;
use Illuminate\Contracts\Support\Responsable;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use App\Models\atmodels\Airtime_sending_record;
use App\Models\atmodels\Airtime_group;
use App\Models\atmodels\Airtime_contact;
use App\Models\atmodels\Currency_credit;
use Illuminate\Http\Request;
use Auth;
use Carbon\Carbon;

use Maatwebsite\Excel\Concerns\FromCollection;

class AirtimeHistory implements Responsable, FromCollection, WithHeadings, WithMapping
{
    private $fileName;
    use Exportable;
    protected $request;
    /**
    * It's required to define the fileName within
    * the export class when making use of Responsable.
    */

 // Get the current date and time
 public function __construct()
 {
     $current = Carbon::now();
     $this->fileName = $current->format('d-m-y_H-i-s') . 'Topup_History.xlsx';
 }
    /**
    * Optional Writer Type
    */
    private $writerType = Excel::XLSX;

    /**
    * Optional headers
    */
    private $headers = [
        'Content-Type' => 'text/csv',
    ];

    // public function __construct($request)
    // {
    //     $this->request = $request;
    // }

    public function headings(): array
    {
        return [
            'RequestID',
            'Date',
            'Airtime Sent',
            'Recipient',
            'Name',
            'Group',
            'Status',
        ];
    }

    public function map($history): array
    {
        $contact = Airtime_contact::where('customer_id',Auth::user()->userShopUser['customer_id'])->where('contact','LIKE',"%".$history->recipient."%")->with('contactGroup')->first();
        return [
            $history->requestid,
            $history->date_sent,
            $history->airtime_sent,
            $history->recipient,
            isset($contact) ? $contact->fname : '',
            isset($contact->contactGroup) ? $contact->contactGroup->name : '',
            $history->status,
        ];
    }

    public function collection()
    {
        // return Customer::all();
        $query = Airtime_sending_record::where('customer_id', Auth::user()->userShopUser['customer_id']);
        $history = EloquentBuilder::to($query, request()->all())->get();
        return $history;
    }
}
