<?php

namespace App\Exports;

use DateTime;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use App\Http\Controllers\LicenseRegisteredController;

class ServicesReport implements FromCollection,WithHeadings
{
    public function dataProcessing()
    {
        $request  = new Request(request()->all());
        $collection = (new LicenseRegisteredController)->serviceReport($request, $request->type, 'export');

        return $collection;
    }

    public function collection()
    {
        $data = $this->dataProcessing();
        $rows = [];

        foreach ($data as $key => $record) {
            $remainingDays              = '';
            $rows[$key]['license_no']   = $record->license_no;
            $rows[$key]['license_date'] = formatedDate($record->license_date);
            // $rows[$key]['project']   = $record->project->title . ' - ' . $record->project->code;
            $rows[$key]['cus_name']  = $record->name;
            $rows[$key]['cus_email'] = $record->email;
            $rows[$key]['cus_phone'] = $record->phone_no;

            if (isset($record->expiry_date)) {
                $expiryDate = \Carbon\Carbon::parse($record->expiry_date);
                $currentDate = \Carbon\Carbon::now();
                $remainingDays = $currentDate->diffInDays($expiryDate);
            }

            $expiry_date = '';

            if (isset($record->expiry_date)) {
                $expiry_date = formatedDate($record->expiry_date);
            }

            if ($remainingDays != '') {
                $expiry_date .= ' (' . $remainingDays . ' Days)';
            }

            $rows[$key]['expiry_date'] = $expiry_date;
        }

        return collect($rows);
    }

    public function headings(): array
    {
        $headings = [
            'License Number',
            'License Date',
            // 'Project',
            'Customer Name',
            'Customer Email',
            'Customer Phone',
            'Expiry Date',
        ];

        return $headings;
    }
}