<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\General\Helper;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Models\Company;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class ExportsCompanies implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
    use Exportable;

    protected $startDate;
    protected $endDate;

    public function __construct($startDate = null, $endDate = null) {
        $this->startDate = $startDate ? Carbon::parse($startDate)->startOfDay() : Carbon::now()->subMonths(1);
        $this->endDate = $endDate ? Carbon::parse($endDate)->endOfDay() : Carbon::now();
    }

    public function headings(): array
    {
        return [
            'TIN',
            'IdentityNo',
            'Name',
            'IdentityType',
            'TaxClassification',
            'MSICCode',
            'BusinessActivityDesc',
            'DebtorCode',
            'TradeName',
            'Address',
            'PostCode',
            'Phone',
            'EmailAddress',
            'City',
            'CountryCode',
            'StateCode'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return Company::whereBetween('e_invoice_requested_at', [$this->startDate, $this->endDate]);
    }

    /**
     * @param Company $company
     *
     * @return array
     */
    public function map($company): array
    {
        $employee = $company->employees()->first();
        $lastBooking = $company->bookings()->orderByDesc('id')->first();
        $identityNo = $company->documents->where('document_type', DocumentType::IDENTITY_CARD)->first();
        $identityType = DocumentType::IDENTITY_CARD;
        if(!$identityNo){
            $identityNo = $company->documents->where('document_type', DocumentType::SSM_REGISTRATION)->first();
            $identityType = DocumentType::SSM_REGISTRATION;
        }
        $identityReference = "";
        if($identityNo){
            $identityReference = preg_replace('/\s*\(.*?\)/', '', $identityNo->reference);
        }
        $address = $company->addresses()->where('e_invoice', '=', true)->latest()->first();
        if(!$address){
            $address = $company->addresses()->where('billing', '=', true)->first();
        }

        return [
            $company->tin,                                                                          // 'TIN',
            $identityReference,                                                                     // 'IdentityNo',
            $company->name,                                                                         // 'Name',
            $identityType === DocumentType::IDENTITY_CARD ? 'MyKAD' : '',                           // 'IdentityType',
            $company->type !== null ? (string) $company->type : '0',                                // 'TaxClassification',
            $company->msic_code,                                                                    // 'MSICCode',
            $company->msic_code ? Helper::getLHDNMsicDescriptionByCode($company->msic_code) : '',   // 'BusinessActivityDesc',
            $company->debtor,                                                                       // 'DebtorCode',
            $company->name,                                                                         // 'TradeName',
            $address ? $address->street_one . ',' . $address->street_two : '',                      // 'Address',
            $address ? $address->postcode : '',                                                     // 'PostCode',
            $company->contacts()->first() ? $company->contacts()->first()->phone : '',              // 'Phone',
            $employee ? $employee->email : '',                                                      // 'EmailAddress',
            $address ? $address->district()->first()->name : '',                                    // 'City',
            'MYS',                                                                                  // 'CountryCode',
            $address ? Helper::getLHDNStateCodeByName($address->state()->first()->name) : '',       // 'StateCode'
        ];
    }
}
